This rule is designed to prevent Cross-Site Scripting (XSS) attacks, which occur when untrusted data is included in a web page without proper validation or escaping, allowing an attacker to inject malicious scripts and perform actions on behalf of the user. It’s important because XSS attacks can lead to a variety of security breaches, including session hijacking, identity theft, and defacement of websites.
In Java, particularly in web applications, developers should always validate and sanitize user input before using it in HTML or JavaScript code. This involves ensuring that the input conforms to expected formats and does not contain potentially harmful characters or scripts.
To avoid violations of this rule, use context-specific output encoding whenever outputting user-controlled data. Libraries such as the OWASP Java Encoder can be used to safely encode user data for different HTML and JavaScript contexts. Also, consider using modern web development frameworks that automatically escape user-controlled data, such as Thymeleaf for Java.
In addition, setting the HTTP response header X-XSS-Protection to 0 can disable the browser’s built-in XSS protection, leaving the user more vulnerable to XSS attacks. Do not set this header to 0 unless you have a specific reason to do so and understand the security implications.
Non-Compliant Code Examples
/**
* OWASP Benchmark Project v1.2
*
* <p>This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
* details, please see <a
* href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* <p>The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* <p>The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/packageorg.owasp.benchmark.testcode;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet(value="/xss-05/BenchmarkTest02591")publicclassBenchmarkTest02591extendsHttpServlet{privatestaticfinallongserialVersionUID=1L;@OverridepublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}@OverridepublicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=UTF-8");StringqueryString=request.getQueryString();Stringparamval="BenchmarkTest02591"+"=";intparamLoc=-1;if(queryString!=null)paramLoc=queryString.indexOf(paramval);if(paramLoc==-1){response.getWriter().println("getQueryString() couldn't find expected parameter '"+"BenchmarkTest02591"+"' in query string.");return;}Stringparam=queryString.substring(paramLoc+paramval.length());// 1st assume "BenchmarkTest02591" param is last// parameter in query string.// And then check to see if its in the middle of the query string and if so, trim off what// comes after.intampersandLoc=queryString.indexOf("&",paramLoc);if(ampersandLoc!=-1){param=queryString.substring(paramLoc+paramval.length(),ampersandLoc);}param=java.net.URLDecoder.decode(param,"UTF-8");Stringbar=doSomething(request,param);response.setHeader("X-XSS-Protection","0");Object[]obj={bar,"b"};response.getWriter().printf("Formatted like: %1$s and %2$s.",obj);}// end doPostprivatestaticStringdoSomething(HttpServletRequestrequest,Stringparam)throwsServletException,IOException{StringBuildersbxyz9811=newStringBuilder(param);Stringbar=sbxyz9811.append("_SafeStuff").toString();returnbar;}}
/**
* OWASP Benchmark v1.2
*
* <p>This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
* details, please see <a
* href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* <p>The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* <p>The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* @author Dave Wichers
* @created 2015
*/packageorg.owasp.benchmark.testcode;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet(value="/ldapi-00/BenchmarkTest00012")publicclassBenchmarkTest00012extendsHttpServlet{privatestaticfinallongserialVersionUID=1L;@OverridepublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}@OverridepublicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// some coderesponse.setContentType("text/html;charset=UTF-8");Stringparam="";java.util.Enumeration<String>headers=request.getHeaders("BenchmarkTest00012");if(headers!=null&&headers.hasMoreElements()){param=headers.nextElement();// just grab first element}// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().param=java.net.URLDecoder.decode(param,"UTF-8");response.getWriter().println("LDAP query results: nothing found for query: "+org.owasp.esapi.ESAPI.encoder().encodeForHTML(filter));org.owasp.benchmark.helpers.LDAPManagerads=neworg.owasp.benchmark.helpers.LDAPManager();try{response.setContentType("text/html;charset=UTF-8");Stringbase="ou=users,ou=system";javax.naming.directory.SearchControlssc=newjavax.naming.directory.SearchControls();sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);Stringfilter="(&(objectclass=person))(|(uid="+param+")(street={0}))";Object[]filters=newObject[]{"The streetz 4 Ms bar"};javax.naming.directory.DirContextctx=ads.getDirContext();javax.naming.directory.InitialDirContextidc=(javax.naming.directory.InitialDirContext)ctx;booleanfound=false;javax.naming.NamingEnumeration<javax.naming.directory.SearchResult>results=idc.search(base,filter,filters,sc);while(results.hasMore()){javax.naming.directory.SearchResultsr=(javax.naming.directory.SearchResult)results.next();javax.naming.directory.Attributesattrs=sr.getAttributes();javax.naming.directory.Attributeattr=attrs.get("uid");javax.naming.directory.Attributeattr2=attrs.get("street");if(attr!=null){response.getWriter().println("LDAP query results:<br>"+"Record found with name "+attr.get()+"<br>"+"Address: "+attr2.get()+"<br>");// System.out.println("record found " + attr.get());found=true;}}if(!found){response.getWriter().println("LDAP query results: nothing found for query: "+org.owasp.esapi.ESAPI.encoder().encodeForHTML(filter));}}catch(javax.naming.NamingExceptione){thrownewServletException(e);}finally{try{ads.closeDirContext();}catch(Exceptione){thrownewServletException(e);}}}}
Compliant Code Examples
/**
* OWASP Benchmark Project v1.2
*
* <p>This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
* details, please see <a
* href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* <p>The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* <p>The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/packageorg.owasp.benchmark.testcode;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet(value="/xss-01/BenchmarkTest00717")publicclassBenchmarkTest00717extendsHttpServlet{privatestaticfinallongserialVersionUID=1L;@OverridepublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}@OverridepublicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=UTF-8");String[]values=request.getParameterValues("BenchmarkTest00717");Stringparam;if(values!=null&&values.length>0)param=values[0];elseparam="";// Chain a bunch of propagators in sequenceStringa59129=param;// assignStringBuilderb59129=newStringBuilder(a59129);// stick in stringbuilderb59129.append(" SafeStuff");// append some safe contentb59129.replace(b59129.length()-"Chars".length(),b59129.length(),"Chars");// replace some of the end contentjava.util.HashMap<String,Object>map59129=newjava.util.HashMap<String,Object>();map59129.put("key59129",b59129.toString());// put in a collectionStringc59129=(String)map59129.get("key59129");// get it back outStringd59129=c59129.substring(0,c59129.length()-1);// extract most of itStringe59129=newString(org.apache.commons.codec.binary.Base64.decodeBase64(org.apache.commons.codec.binary.Base64.encodeBase64(d59129.getBytes())));// B64 encode and decode itStringf59129=e59129.split(" ")[0];// split it on a spaceorg.owasp.benchmark.helpers.ThingInterfacething=org.owasp.benchmark.helpers.ThingFactory.createThing();Stringg59129="barbarians_at_the_gate";// This is static so this whole flow is 'safe'Stringbar=thing.doSomething(g59129);// reflectionresponse.setHeader("X-XSS-Protection","0");Object[]obj={"a",bar};response.getWriter().printf(java.util.Locale.US,"Formatted like: %1$s and %2$s.",obj);}}
/**
* OWASP Benchmark Project v1.2
*
* <p>This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
* details, please see <a
* href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* <p>The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* <p>The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/packageorg.owasp.benchmark.testcode;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet(value="/xss-04/BenchmarkTest02133")publicclassBenchmarkTest02133extendsHttpServlet{privatestaticfinallongserialVersionUID=1L;@OverridepublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}@OverridepublicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=UTF-8");Stringparam=request.getParameter("BenchmarkTest02133");if(param==null)param="";Stringbar=doSomething(request,param);response.setHeader("X-XSS-Protection","0");response.getWriter().println(bar);}// end doPostprivatestaticStringdoSomething(HttpServletRequestrequest,Stringparam)throwsServletException,IOException{Stringbar;// Simple ? condition that assigns param to bar on false conditionintnum=106;bar=(7*42)-num>200?"This should never happen":param;returnbar;}}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- java-security # Rules to enforce Java security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines