org.sonar.plugins.findbugs.rules-findsecbugs.xml Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sonar-findbugs-plugin Show documentation
Show all versions of sonar-findbugs-plugin Show documentation
SpotBugs is a program that uses static analysis to look for bugs in Java code. It can detect a variety of common coding mistakes, including thread synchronization problems, misuse of API methods.
<rules><!-- This file is auto-generated. --> <rule key='PREDICTABLE_RANDOM' priority='MAJOR'> <name>Security - Predictable pseudorandom number generator</name> <configKey>PREDICTABLE_RANDOM</configKey> <description><p>The use of a predictable random value can lead to vulnerabilities when used in certain security critical contexts. For example, when the value is used as:</p> <ul> <li>a CSRF token: a predictable token can lead to a CSRF attack as an attacker will know the value of the token</li> <li>a password reset token (sent by email): a predictable password token can lead to an account takeover, since an attacker will guess the URL of the "change password" form</li> <li>any other secret value</li> </ul> <p> A quick fix could be to replace the use of <code>java.util.Random</code> with something stronger, such as <code>java.security.SecureRandom</code>. </p> <p> <b>Vulnerable Code:</b><br/> <pre>String generateSecretToken() { Random r = new Random(); return Long.toHexString(r.nextLong()); }</pre> </p> <p> <b>Solution:</b> <pre>import org.apache.commons.codec.binary.Hex; String generateSecretToken() { SecureRandom secRandom = new SecureRandom(); byte[] result = new byte[32]; secRandom.nextBytes(result); return Hex.encodeHexString(result); }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://jazzy.id.au/2010/09/20/cracking_random_number_generators_part_1.html">Cracking Random Number Generators - Part 1 (https://jazzy.id.au)</a><br/> <a href="https://www.securecoding.cert.org/confluence/display/java/MSC02-J.+Generate+strong+random+numbers">CERT: MSC02-J. Generate strong random numbers</a><br/> <a href="https://cwe.mitre.org/data/definitions/330.html">CWE-330: Use of Insufficiently Random Values</a><br/> <a href="https://blog.h3xstream.com/2014/12/predicting-struts-csrf-token-cve-2014.html">Predicting Struts CSRF Token (Example of real-life vulnerability and exploitation)</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_PARAMETER' priority='INFO'> <name>Security - Untrusted servlet parameter</name> <configKey>SERVLET_PARAMETER</configKey> <description><p>The Servlet can read GET and POST parameters from various methods. The value obtained should be considered unsafe. You may need to validate or sanitize those values before passing them to sensitive APIs such as:</p> <ul> <li>SQL query (May leads to SQL injection)</li> <li>File opening (May leads to path traversal)</li> <li>Command execution (Potential Command injection)</li> <li>HTML construction (Potential XSS)</li> <li>etc...</li> </ul> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_CONTENT_TYPE' priority='INFO'> <name>Security - Untrusted Content-Type header</name> <configKey>SERVLET_CONTENT_TYPE</configKey> <description><p> The HTTP header Content-Type can be controlled by the client. As such, its value should not be used in any security critical decisions. </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/807.html">CWE-807: Untrusted Inputs in a Security Decision</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_SERVER_NAME' priority='INFO'> <name>Security - Untrusted Hostname header</name> <configKey>SERVLET_SERVER_NAME</configKey> <description><p>The hostname header can be controlled by the client. As such, its value should not be used in any security critical decisions. Both <code>ServletRequest.getServerName()</code> and <code>HttpServletRequest.getHeader("Host")</code> have the same behavior which is to extract the <code>Host</code> header.</p> <pre> GET /testpage HTTP/1.1 Host: www.example.com [...]</pre> <p> The web container serving your application may redirect requests to your application by default. This would allow a malicious user to place any value in the Host header. It is recommended that you do not trust this value in any security decisions you make with respect to a request. </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/807.html">CWE-807: Untrusted Inputs in a Security Decision</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_SESSION_ID' priority='INFO'> <name>Security - Untrusted session cookie value</name> <configKey>SERVLET_SESSION_ID</configKey> <description><p> The method <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRequestedSessionId()"><code>HttpServletRequest.getRequestedSessionId()</code></a> typically returns the value of the cookie <code>JSESSIONID</code>. This value is normally only accessed by the session management logic and not normal developer code. </p> <p> The value passed to the client is generally an alphanumeric value (e.g., <code>JSESSIONID=jp6q31lq2myn</code>). However, the value can be altered by the client. The following HTTP request illustrates the potential modification. <pre> GET /somePage HTTP/1.1 Host: yourwebsite.com User-Agent: Mozilla/5.0 Cookie: JSESSIONID=Any value of the user&#39;s choice!!??'''&quot;&gt; </pre> </p> <p>As such, the JSESSIONID should only be used to see if its value matches an existing session ID. If it does not, the user should be considered an unauthenticated user. In addition, the session ID value should never be logged. If it is, then the log file could contain valid active session IDs, allowing an insider to hijack any sessions whose IDs have been logged and are still active. </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Session_Management_Cheat_Sheet">OWASP: Session Management Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_QUERY_STRING' priority='INFO'> <name>Security - Untrusted query string</name> <configKey>SERVLET_QUERY_STRING</configKey> <description><p>The query string is the concatenation of the GET parameter names and values. Parameters other than those intended can be passed in.</p> <p>For the URL request <code>/app/servlet.htm?a=1&b=2</code>, the query string extract will be <code>a=1&b=2</code></p> <p>Just as is true for individual parameter values retrieved via methods like <code>HttpServletRequest.getParameter()</code>, the value obtained from <code>HttpServletRequest.getQueryString()</code> should be considered unsafe. You may need to validate or sanitize anything pulled from the query string before passing it to sensitive APIs. </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_HEADER' priority='INFO'> <name>Security - HTTP headers untrusted</name> <configKey>SERVLET_HEADER</configKey> <description><p>Request headers can easily be altered by the requesting user. In general, no assumption should be made that the request came from a regular browser without modification by an attacker. As such, it is recommended that you not trust this value in any security decisions you make with respect to a request.</p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/807.html">CWE-807: Untrusted Inputs in a Security Decision</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_HEADER_REFERER' priority='INFO'> <name>Security - Untrusted Referer header</name> <configKey>SERVLET_HEADER_REFERER</configKey> <description><p> Behavior: <ul> <li>Any value can be assigned to this header if the request is coming from a malicious user.</li> <li>The "Referer" will not be present if the request was initiated from another origin that is secure (HTTPS).</li> </ul> </p> <p> Recommendations: <ul> <li>No access control should be based on the value of this header.</li> <li>No CSRF protection should be based only on this value (<a href="https://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z14">because it is optional</a>).</li> </ul> </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/807.html">CWE-807: Untrusted Inputs in a Security Decision</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SERVLET_HEADER_USER_AGENT' priority='INFO'> <name>Security - Untrusted User-Agent header</name> <configKey>SERVLET_HEADER_USER_AGENT</configKey> <description><p>The header "User-Agent" can easily be spoofed by the client. Adopting different behaviors based on the User-Agent (for crawler UA) is not recommended.</p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/807.html">CWE-807: Untrusted Inputs in a Security Decision</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='COOKIE_USAGE' priority='INFO'> <name>Security - Potentially sensitive data in a cookie</name> <configKey>COOKIE_USAGE</configKey> <description><p>The information stored in a custom cookie should not be sensitive or related to the session. In most cases, sensitive data should only be stored in session and referenced by the user's session cookie. See HttpSession (<code>HttpServletRequest.getSession()</code>)</p> <p>Custom cookies can be used for information that needs to live longer than and is independent of a specific session.</p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/315.html">CWE-315: Cleartext Storage of Sensitive Information in a Cookie</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='PATH_TRAVERSAL_IN' priority='MAJOR'> <name>Security - Potential Path Traversal (file read)</name> <configKey>PATH_TRAVERSAL_IN</configKey> <description><p>A file is opened to read its content. The filename comes from an <b>input</b> parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read.</p> <p>This rule identifies <b>potential</b> path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive.</p> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>@GET @Path("/images/{image}") @Produces("images/*") public Response getImage(@javax.ws.rs.PathParam("image") String image) { File file = new File("resources/images/", image); //Weak point if (!file.exists()) { return Response.status(Status.NOT_FOUND).build(); } return Response.ok().entity(new FileInputStream(file)).build(); }</pre> </p> <br/> <p> <b>Solution:</b><br/> <pre>import org.apache.commons.io.FilenameUtils; @GET @Path("/images/{image}") @Produces("images/*") public Response getImage(@javax.ws.rs.PathParam("image") String image) { File file = new File("resources/images/", FilenameUtils.getName(image)); //Fix if (!file.exists()) { return Response.status(Status.NOT_FOUND).build(); } return Response.ok().entity(new FileInputStream(file)).build(); }</pre> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246952/Path%20Traversal">WASC: Path Traversal</a><br/> <a href="https://www.owasp.org/index.php/Path_Traversal">OWASP: Path Traversal</a><br/> <a href="https://capec.mitre.org/data/definitions/126.html">CAPEC-126: Path Traversal</a><br/> <a href="https://cwe.mitre.org/data/definitions/22.html">CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')</a> </p></description> <tag>owasp-a4</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='PATH_TRAVERSAL_OUT' priority='MAJOR'> <name>Security - Potential Path Traversal (file write)</name> <configKey>PATH_TRAVERSAL_OUT</configKey> <description><p>A file is opened to write to its contents. The filename comes from an <b>input</b> parameter. If an unfiltered parameter is passed to this file API, files at an arbitrary filesystem location could be modified.</p> <p>This rule identifies <b>potential</b> path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive.</p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246952/Path%20Traversal">WASC-33: Path Traversal</a><br/> <a href="https://www.owasp.org/index.php/Path_Traversal">OWASP: Path Traversal</a><br/> <a href="https://capec.mitre.org/data/definitions/126.html">CAPEC-126: Path Traversal</a><br/> <a href="https://cwe.mitre.org/data/definitions/22.html">CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')</a> </p></description> <tag>owasp-a4</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='COMMAND_INJECTION' priority='CRITICAL'> <name>Security - Potential Command Injection</name> <configKey>COMMAND_INJECTION</configKey> <description><p>The highlighted API is used to execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution.</p> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>import java.lang.Runtime; Runtime r = Runtime.getRuntime(); r.exec("/bin/sh -c some_tool" + input);</pre> </p> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Command_Injection">OWASP: Command Injection</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/78.html">CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')</a> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WEAK_FILENAMEUTILS' priority='INFO'> <name>Security - FilenameUtils not filtering null bytes</name> <configKey>WEAK_FILENAMEUTILS</configKey> <description><p>Some <code>FilenameUtils'</code> methods don't filter NULL bytes (<code>0x00</code>).</p> <p>If a null byte is injected into a filename, if this filename is passed to the underlying OS, the file retrieved will be the name of the file that is specified prior to the NULL byte, since at the OS level, all strings are terminated by a null byte even though Java itself doesn't care about null bytes or treat them special. This OS behavior can be used to bypass filename validation that looks at the end of the filename (e.g., ends with <code>".log"</code>) to make sure it's a safe file to access.</p> <p>To fix this, two things are recommended: <ul> <li>Upgrade to Java 7 update 40 or later, or Java 8+ since <a href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8014846">NULL byte injection in filenames is fixed in those versions</a>.</li> <li>Strongly validate any filenames provided by untrusted users to make sure they are valid (i.e., don't contain null, don't include path characters, etc).</li> </ul> <p>If you know you are using a modern version of Java immune to NULL byte injection, you can probably disable this rule. </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246949/Null%20Byte%20Injection">WASC-28: Null Byte Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/158.html">CWE-158: Improper Neutralization of Null Byte or NUL Character</a> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WEAK_TRUST_MANAGER' priority='MAJOR'> <name>Security - TrustManager that accept any certificates</name> <configKey>WEAK_TRUST_MANAGER</configKey> <description><p>Empty TrustManager implementations are often used to connect easily to a host that is not signed by a root <a href="https://en.wikipedia.org/wiki/Certificate_authority">certificate authority</a>. As a consequence, this is vulnerable to <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">Man-in-the-middle attacks</a> since the client will trust any certificate. </p> <p> A TrustManager allowing specific certificates (based on a TrustStore for example) should be built. Detailed information for a proper implementation is available at: <a href="https://stackoverflow.com/a/6378872/89769">[1]</a> <a href="https://stackoverflow.com/a/5493452/89769">[2]</a> </p> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>class TrustAllManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { //Trust any client connecting (no certificate validation) } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { //Trust any remote server (no certificate validation) } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }</pre> </p> <br/> <p> <b>Solution (TrustMangager based on a keystore):</b><br/> <pre>KeyStore ks = //Load keystore containing the certificates trusted SSLContext sc = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),null); </pre> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246945/Insufficient%20Transport%20Layer%20Protection">WASC-04: Insufficient Transport Layer Protection</a><br/> <a href="https://cwe.mitre.org/data/definitions/295.html">CWE-295: Improper Certificate Validation</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WEAK_HOSTNAME_VERIFIER' priority='MAJOR'> <name>Security - HostnameVerifier that accept any signed certificates</name> <configKey>WEAK_HOSTNAME_VERIFIER</configKey> <description><p>A <code>HostnameVerifier</code> that accept any host are often use because of certificate reuse on many hosts. As a consequence, this is vulnerable to <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">Man-in-the-middle attacks</a> since the client will trust any certificate. </p> <p> A TrustManager allowing specific certificates (based on a truststore for example) should be built. Wildcard certificates should be created for reused on multiples subdomains. Detailed information for a proper implementation is available at: <a href="https://stackoverflow.com/a/6378872/89769">[1]</a> <a href="https://stackoverflow.com/a/5493452/89769">[2]</a> </p> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>public class AllHosts implements HostnameVerifier { public boolean verify(final String hostname, final SSLSession session) { return true; } }</pre> </p> <br/> <p> <b>Solution (TrustMangager based on a keystore):</b><br/> <pre>KeyStore ks = //Load keystore containing the certificates trusted SSLContext sc = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),null); </pre> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246945/Insufficient%20Transport%20Layer%20Protection">WASC-04: Insufficient Transport Layer Protection</a><br/> <a href="https://cwe.mitre.org/data/definitions/295.html">CWE-295: Improper Certificate Validation</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='JAXWS_ENDPOINT' priority='INFO'> <name>Security - Found JAX-WS SOAP endpoint</name> <configKey>JAXWS_ENDPOINT</configKey> <description><p>This method is part of a SOAP Web Service (JSR224).</p> <p> <b>The security of this web service should be analyzed. For example:</b> <ul> <li>Authentication, if enforced, should be tested.</li> <li>Access control, if enforced, should be tested.</li> <li>The inputs should be tracked for potential vulnerabilities.</li> <li>The communication should ideally be over SSL.</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Web_Service_Security_Cheat_Sheet">OWASP: Web Service Security Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='JAXRS_ENDPOINT' priority='INFO'> <name>Security - Found JAX-RS REST endpoint</name> <configKey>JAXRS_ENDPOINT</configKey> <description><p>This method is part of a REST Web Service (JSR311).</p> <p> <b>The security of this web service should be analyzed. For example:</b> <ul> <li>Authentication, if enforced, should be tested.</li> <li>Access control, if enforced, should be tested.</li> <li>The inputs should be tracked for potential vulnerabilities.</li> <li>The communication should ideally be over SSL.</li> <li>If the service supports writes (e.g., via POST), its vulnerability to CSRF should be investigated.<sup>[1]</sup></li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/REST_Assessment_Cheat_Sheet">OWASP: REST Assessment Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/REST_Security_Cheat_Sheet">OWASP: REST Security Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Web_Service_Security_Cheat_Sheet">OWASP: Web Service Security Cheat Sheet</a><br/> 1. <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)">OWASP: Cross-Site Request Forgery</a><br/> <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet">OWASP: CSRF Prevention Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='TAPESTRY_ENDPOINT' priority='INFO'> <name>Security - Found Tapestry page</name> <configKey>TAPESTRY_ENDPOINT</configKey> <description><p>A Tapestry endpoint was discovered at application startup. Tapestry apps are structured with a backing Java class and a corresponding Tapestry Markup Language page (a <code>.tml</code> file) for each page. When a request is received, the GET/POST parameters are mapped to specific inputs in the backing Java class. The mapping is either done with field name:</p> <pre><code> [...] protected String input; [...] </code></pre> <p>or the definition of an explicit annotation: </p> <pre><code> [...] @org.apache.tapestry5.annotations.Parameter protected String parameter1; @org.apache.tapestry5.annotations.Component(id = "password") private PasswordField passwordField; [...] </code></pre> <p>The page is mapped to the view <code>/resources/package/PageName.tml</code>.</p> <p>Each Tapestry page in this application should be researched to make sure all inputs that are automatically mapped in this way are properly validated before they are used.</p> <br/> <p> <b>References</b><br/> <a href="https://tapestry.apache.org/">Apache Tapestry Home Page</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WICKET_ENDPOINT' priority='INFO'> <name>Security - Found Wicket WebPage</name> <configKey>WICKET_ENDPOINT</configKey> <description><p>This class represents a Wicket WebPage. Input is automatically read from a PageParameters instance passed to the constructor. The current page is mapped to the view <code>/package/WebPageName.html</code>.</p> <p>Each Wicket page in this application should be researched to make sure all inputs that are automatically mapped in this way are properly validated before they are used.</p> <br/> <p> <b>References</b><br/> <a href="https://wicket.apache.org/">Apache Wicket Home Page</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WEAK_MESSAGE_DIGEST_MD5' priority='MAJOR'> <name>Security - MD2, MD4 and MD5 are weak hash functions</name> <configKey>WEAK_MESSAGE_DIGEST_MD5</configKey> <description><p>The algorithms MD2, MD4 and MD5 are not a recommended MessageDigest. <b>PBKDF2</b> should be used to hash password for example.</p> <blockquote> "The security of the MD5 hash function is severely compromised. A collision attack exists that can find collisions within seconds on a computer with a 2.6 GHz Pentium 4 processor (complexity of 2<sup>24.1</sup>).[1] Further, there is also a chosen-prefix collision attack that can produce a collision for two inputs with specified prefixes within hours, using off-the-shelf computing hardware (complexity 2<sup>39</sup>).[2]"<br/> - <a href="https://en.wikipedia.org/wiki/MD5#Security">Wikipedia: MD5 - Security</a> </blockquote> <blockquote> "<b>SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256</b>:<br/> The use of these hash functions is acceptable for all hash function applications."<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15</a> </blockquote> <blockquote> "The main idea of a PBKDF is to slow dictionary or brute force attacks on the passwords by increasing the time needed to test each password. An attacker with a list of likely passwords can evaluate the PBKDF using the known iteration counter and the salt. Since an attacker has to spend a significant amount of computing time for each try, it becomes harder to apply the dictionary or brute force attacks."<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST: Recommendation for Password-Based Key Derivation p.12</a> </blockquote> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>MessageDigest md5Digest = MessageDigest.getInstance("MD5"); md5Digest.update(password.getBytes()); byte[] hashValue = md5Digest.digest();</pre> <br/> <pre>byte[] hashValue = DigestUtils.getMd5Digest().digest(password.getBytes());</pre> </p> <br/> <p> <b>Solution (Using bouncy castle):</b><br/> <pre>public static byte[] getEncryptedPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init(password.getBytes("UTF-8"), salt.getBytes(), 4096); return ((KeyParameter) gen.generateDerivedParameters(256)).getKey(); }</pre> <br/> <b>Solution (Java 8 and later):</b><br/> <pre>public static byte[] getEncryptedPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 4096, 256 * 8); SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); return f.generateSecret(spec).getEncoded(); }</pre> </p> <br/> <p> <b>References</b><br/> [1] <a href="https://www.win.tue.nl/hashclash/On%20Collisions%20for%20MD5%20-%20M.M.J.%20Stevens.pdf">On Collisions for MD5</a>: Master Thesis by M.M.J. Stevens<br/> [2] <a href="https://homepages.cwi.nl/~stevens/papers/stJOC%20-%20Chosen-Prefix%20Collisions%20for%20MD5%20and%20Applications.pdf">Chosen-prefix collisions for MD5 and applications</a>: Paper written by Marc Stevens<br/> <a href="https://en.wikipedia.org/wiki/MD5">Wikipedia: MD5</a><br/> <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Transitioning the Use of Cryptographic Algorithms and Key Lengths</a><br/> <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST: Recommendation for Password-Based Key Derivation</a><br/> <a href="https://stackoverflow.com/q/22580853/89769">Stackoverflow: Reliable implementation of PBKDF2-HMAC-SHA256 for Java</a><br/> <a href="https://cwe.mitre.org/data/definitions/327.html">CWE-327: Use of a Broken or Risky Cryptographic Algorithm</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='WEAK_MESSAGE_DIGEST_SHA1' priority='MAJOR'> <name>Security - SHA-1 is a weak hash function</name> <configKey>WEAK_MESSAGE_DIGEST_SHA1</configKey> <description><p>The algorithms SHA-1 is not a recommended algorithm for hash password, for signature verification and other uses. <b>PBKDF2</b> should be used to hash password for example.</p> <blockquote> "<b>SHA-1 for digital signature generation:</b><br/> SHA-1 may only be used for digital signature generation where specifically allowed by NIST protocol-specific guidance. For all other applications, <u>SHA-1 shall not be used for digital signature generation</u>.<br/> <b>SHA-1 for digital signature verification:</b><br/> For digital signature verification, <u>SHA-1 is allowed for legacy-use</u>.<br/> [...]<br/> <b>SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256</b>:<br/> The use of these hash functions is acceptable for all hash function applications."<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15</a> </blockquote> <blockquote> "The main idea of a PBKDF is to slow dictionary or brute force attacks on the passwords by increasing the time needed to test each password. An attacker with a list of likely passwords can evaluate the PBKDF using the known iteration counter and the salt. Since an attacker has to spend a significant amount of computing time for each try, it becomes harder to apply the dictionary or brute force attacks."<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST: Recommendation for Password-Based Key Derivation p.12</a> </blockquote> <br/> <p> <b>Vulnerable Code:</b><br/> <pre>MessageDigest sha1Digest = MessageDigest.getInstance("SHA1"); sha1Digest.update(password.getBytes()); byte[] hashValue = sha1Digest.digest();</pre> <br/> <pre>byte[] hashValue = DigestUtils.getSha1Digest().digest(password.getBytes());</pre> </p> <br/> <p> <b>Solution (Using bouncy castle):</b><br/> <pre>public static byte[] getEncryptedPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init(password.getBytes("UTF-8"), salt.getBytes(), 4096); return ((KeyParameter) gen.generateDerivedParameters(256)).getKey(); }</pre> <br/> <b>Solution (Java 8 and later):</b><br/> <pre>public static byte[] getEncryptedPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 4096, 256 * 8); SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); return f.generateSecret(spec).getEncoded(); }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://community.qualys.com/blogs/securitylabs/2014/09/09/sha1-deprecation-what-you-need-to-know">Qualys blog: SHA1 Deprecation: What You Need to Know</a><br/> <a href="https://googleonlinesecurity.blogspot.ca/2014/09/gradually-sunsetting-sha-1.html">Google Online Security Blog: Gradually sunsetting SHA-1</a><br/> <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Transitioning the Use of Cryptographic Algorithms and Key Lengths</a><br/> <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST: Recommendation for Password-Based Key Derivation</a><br/> <a href="https://stackoverflow.com/q/22580853/89769">Stackoverflow: Reliable implementation of PBKDF2-HMAC-SHA256 for Java</a><br/> <a href="https://cwe.mitre.org/data/definitions/327.html">CWE-327: Use of a Broken or Risky Cryptographic Algorithm</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='DEFAULT_HTTP_CLIENT' priority='MAJOR'> <name>Security - DefaultHttpClient with default constructor is not compatible with TLS 1.2</name> <configKey>DEFAULT_HTTP_CLIENT</configKey> <description><p> <b>Vulnerable Code:</b><br/> <pre>HttpClient client = new DefaultHttpClient();</pre> </p> <p> <p><b>Solution:</b><br/> Upgrade your implementation to use one of the recommended constructs and configure <code>https.protocols</code> JVM option to include TLSv1.2:</p> <p> <ul> <li>Use <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">SystemDefaultHttpClient</a> instead</li> <p> <b>Sample Code:</b><br/> <pre>HttpClient client = new SystemDefaultHttpClient();</pre> </p> <li>Create an HttpClient based on SSLSocketFactory - get an SSLScoketFactory instance with <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html#getSystemSocketFactory()"><code>getSystemSocketFactory()</code></a> and use this instance for HttpClient creation</li> <li>Create an HttpClient based on SSLConnectionSocketFactory - get an instance with <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLConnectionSocketFactory.html#getSystemSocketFactory()"><code>getSystemSocketFactory()</code></a> and use this instance for HttpClient creation</li> <li>Use HttpClientBuilder - call <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html#useSystemProperties()"><code>useSystemProperties()</code></a> before calling <code>build()</code></li> <p> <b>Sample Code:</b><br/> <pre>HttpClient client = HttpClientBuilder.create().useSystemProperties().build();</pre> </p> <li>HttpClients - call <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClients.html#createSystem()"><code>createSystem()</code></a> to create an instance</li> <p> <b>Sample Code:</b><br/> <pre>HttpClient client = HttpClients.createSystem();</pre> </p> </ul> </p> <br/> <p> <b>References</b><br/> <a href="https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https">Diagnosing TLS, SSL, and HTTPS</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>security</tag> </rule> <rule key='SSL_CONTEXT' priority='MAJOR'> <name>Security - Weak SSLContext</name> <configKey>SSL_CONTEXT</configKey> <description><p> <b>Vulnerable Code:</b><br/> <pre>SSLContext.getInstance("SSL");</pre> </p> <p> <p><b>Solution:</b><br/> Upgrade your implementation to the following, and configure <code>https.protocols</code> JVM option to include TLSv1.2:</p> <pre>SSLContext.getInstance("TLS");</pre> <p> </p> <br/> <p> <b>References</b><br/> <a href="https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https">Diagnosing TLS, SSL, and HTTPS</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>security</tag> </rule> <rule key='CUSTOM_MESSAGE_DIGEST' priority='MAJOR'> <name>Security - Message digest is custom</name> <configKey>CUSTOM_MESSAGE_DIGEST</configKey> <description><p>Implementing a custom MessageDigest is error-prone.</p> <p><a href="https://csrc.nist.gov/projects/hash-functions">NIST</a> recommends the use of SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, or SHA-512/256.</p> <blockquote> "<b>SHA-1 for digital signature generation:</b><br/> SHA-1 may only be used for digital signature generation where specifically allowed by NIST protocol-specific guidance. For all other applications, <u>SHA-1 shall not be used for digital signature generation</u>.<br/> <b>SHA-1 for digital signature verification:</b><br/> For digital signature verification, <u>SHA-1 is allowed for legacy-use</u>.<br/> [...]<br/> <b>SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256</b>:<br/> The use of these hash functions is acceptable for all hash function applications."<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15</a> </blockquote> <p> <b>Vulnerable Code:</b><br/> <pre>MyProprietaryMessageDigest extends MessageDigest { @Override protected byte[] engineDigest() { [...] //Creativity is a bad idea return [...]; } }</pre> </p> <p> <p>Upgrade your implementation to use one of the approved algorithms. Use an algorithm that is sufficiently strong for your specific security needs.</p> <p> <b>Example Solution:</b><br/> <pre>MessageDigest sha256Digest = MessageDigest.getInstance("SHA256"); sha256Digest.update(password.getBytes());</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://csrc.nist.gov/projects/hash-functions">NIST Approved Hash Functions</a><br/> <a href="https://cwe.mitre.org/data/definitions/327.html">CWE-327: Use of a Broken or Risky Cryptographic Algorithm</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='FILE_UPLOAD_FILENAME' priority='INFO'> <name>Security - Tainted filename read</name> <configKey>FILE_UPLOAD_FILENAME</configKey> <description><p>The filename provided by the FileUpload API can be tampered with by the client to reference unauthorized files.</p> <p>For example:</p> <ul> <li><code>"../../../config/overide_file"</code></li> <li><code>"shell.jsp\u0000expected.gif"</code></li> </ul> <p>Therefore, such values should not be passed directly to the filesystem API. If acceptable, the application should generate its own file names and use those. Otherwise, the provided filename should be properly validated to ensure it's properly structured, contains no unauthorized path characters (e.g., / \), and refers to an authorized file.</p> <br/> <p> <b>References</b><br/> <a href="https://blogs.securiteam.com/index.php/archives/1268">Securiteam: File upload security recommendations</a><br/> <a href="https://cwe.mitre.org/data/definitions/22.html">CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')</a><br/> <a href="http://projects.webappsec.org/w/page/13246952/Path%20Traversal">WASC-33: Path Traversal</a><br/> <a href="https://www.owasp.org/index.php/Path_Traversal">OWASP: Path Traversal</a><br/> <a href="https://capec.mitre.org/data/definitions/126.html">CAPEC-126: Path Traversal</a><br/> <a href="https://cwe.mitre.org/data/definitions/22.html">CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')</a> </p></description> <tag>owasp-a4</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='REDOS' priority='MAJOR'> <name>Security - Regex DOS (ReDOS)</name> <configKey>REDOS</configKey> <description><p> Regular expressions (Regex) are frequently subject to Denial of Service (DOS) attacks (called ReDOS). This is due to the fact that regex engines may take a large amount of time when analyzing certain strings, depending on how the regex is defined. <p> For example, for the regex: <code>^(a+)+$</code>, the input "<code>aaaaaaaaaaaaaaaaX</code>" will cause the regex engine to analyze 65536 different paths.<sup>[1] Example taken from OWASP references</sup></p> <p> Therefore, it is possible that a single request may cause a large amount of computation on the server side. The problem with this regex, and others like it, is that there are two different ways the same input character can be accepted by the Regex due to the <code>+</code> (or a <code>*</code>) inside the parenthesis, and the <code>+</code> (or a <code>*</code>) outside the parenthesis. The way this is written, either <code>+</code> could consume the character 'a'. To fix this, the regex should be rewritten to eliminate the ambiguity. For example, this could simply be rewritten as: <code>^a+$</code>, which is presumably what the author meant anyway (any number of a's). Assuming that's what the original regex meant, this new regex can be evaluated quickly, and is not subject to ReDOS. </p> <br/> <p> <b>References</b><br/> <a href="https://sebastiankuebeck.wordpress.com/2011/03/01/detecting-and-preventing-redos-vulnerabilities/">Sebastian Kubeck's Weblog: Detecting and Preventing ReDoS Vulnerabilities</a><br/> <sup>[1]</sup> <a href="https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS">OWASP: Regular expression Denial of Service</a><br/> <a href="https://cwe.mitre.org/data/definitions/400.html">CWE-400: Uncontrolled Resource Consumption ('Resource Exhaustion')</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_XMLSTREAMREADER' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (XMLStreamReader)</name> <configKey>XXE_XMLSTREAMREADER</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre>public void parseXML(InputStream input) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newFactory(); XMLStreamReader reader = factory.createXMLStreamReader(input); [...] }</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one property or both. </p> <p><b>Solution disabling External Entities:</b></p> <p> <pre>public void parseXML(InputStream input) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); XMLStreamReader reader = factory.createXMLStreamReader(input); [...] }</pre> </p> <p><b>Solution disabling DTD:</b></p> <p> <pre>public void parseXML(InputStream input) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader reader = factory.createXMLStreamReader(input); [...] }</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> <a href="https://openjdk.java.net/jeps/185">JEP 185: Restrict Fetching of External XML Resources</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_XPATH' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (XPathExpression)</name> <configKey>XXE_XPATH</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre>DocumentBuilder builder = df.newDocumentBuilder(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression xPathExpr = xpath.compile("/somepath/text()"); xPathExpr.evaluate(new InputSource(inputStream));</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one feature or both. </p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against Denial of Service attack and remote file access. <pre> DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); df.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = df.newDocumentBuilder(); [...] xPathExpr.evaluate( builder.parse(inputStream) );</pre> </p> <p><b>Solution disabling DTD:</b></p> <p> By disabling DTD, almost all XXE attacks will be prevented. <pre> DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = df.newDocumentBuilder(); [...] xPathExpr.evaluate( builder.parse(inputStream) );</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XPathExpression">XML External Entity (XXE) Prevention Cheat Sheet</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_SAXPARSER' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (SAXParser)</name> <configKey>XXE_SAXPARSER</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre> SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(inputStream, customHandler);</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one feature or both. </p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against Denial of Service attack and remote file access. <pre> SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser parser = spf.newSAXParser(); parser.parse(inputStream, customHandler);</pre> </p> <p><b>Solution disabling DTD:</b></p> <p> By disabling DTD, almost all XXE attacks will be prevented. <pre> SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); SAXParser parser = spf.newSAXParser(); parser.parse(inputStream, customHandler);</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> <a href="https://xerces.apache.org/xerces-j/features.html">Xerces complete features list</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_XMLREADER' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (XMLReader)</name> <configKey>XXE_XMLREADER</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre> XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(customHandler); reader.parse(new InputSource(inputStream));</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one property or both. </p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against Denial of Service attack and remote file access. <pre> XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); reader.setContentHandler(customHandler); reader.parse(new InputSource(inputStream));</pre> </p> <p><b>Solution disabling DTD:</b></p> <p> By disabling DTD, almost all XXE attacks will be prevented. <pre> XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setContentHandler(customHandler); reader.parse(new InputSource(inputStream));</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> <a href="https://xerces.apache.org/xerces-j/features.html">Xerces complete features list</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_DOCUMENT' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (DocumentBuilder)</name> <configKey>XXE_DOCUMENT</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre> DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(input);</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one feature or both. </p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against Denial of Service attack and remote file access. <pre> DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(input);</pre> </p> <p><b>Solution disabling DTD:</b></p> <p> By disabling DTD, almost all XXE attacks will be prevented. <pre> DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(input);</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> <a href="http://xerces.apache.org/xerces2-j/features.html">Xerces2 complete features list</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_DTD_TRANSFORM_FACTORY' priority='CRITICAL'> <name>Security - XML parsing vulnerable to XXE (TransformerFactory)</name> <configKey>XXE_DTD_TRANSFORM_FACTORY</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.</p> <p><b>Risk 1: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM &quot;file:///etc/passwd&quot; &gt; ]&gt; &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</pre> </p> <b>Risk 2: Denial of service (XEE: <u>X</u>ML <u>E</u>ntity <u>E</u>xpansion)</b> <p> <pre> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;!DOCTYPE lolz [ &lt;!ENTITY lol &quot;lol&quot;&gt; &lt;!ELEMENT lolz (#PCDATA)&gt; &lt;!ENTITY lol1 &quot;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&amp;lol;&quot;&gt; &lt;!ENTITY lol2 &quot;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&amp;lol1;&quot;&gt; &lt;!ENTITY lol3 &quot;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&amp;lol2;&quot;&gt; [...] &lt;!ENTITY lol9 &quot;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&amp;lol8;&quot;&gt; ]&gt; &lt;lolz&gt;&amp;lol9;&lt;/lolz&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre> Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(input, result);</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one feature or both. </p> <p><b>Solution disabling DTD:</b></p> <p> This setting will protect you against remote file access but not denial of service. <pre> TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, result);</pre> </p> <p>An empty string denies all access to external references for both attributes.</p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against remote file access but not denial of service. <pre> TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, result);</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XXE_XSLT_TRANSFORM_FACTORY' priority='CRITICAL'> <name>Security - XSLT parsing vulnerable to XXE (TransformerFactory)</name> <configKey>XXE_XSLT_TRANSFORM_FACTORY</configKey> <description><!--XXE_GENERIC_START--> <h3>Attack</h3> <p>XSLT External Entity (XXE) attacks can occur when an XSLT parser supports external entities while processing XSLT received from an untrusted source.</p> <p><b>Risk: Expose local file content (XXE: <u>X</u>ML E<u>x</u>ternal <u>E</u>ntity)</b></p> <p> <pre> &lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt; &lt;xsl:template match=&quot;/&quot;&gt; &lt;xsl:value-of select=&quot;document(&apos;/etc/passwd&apos;)&quot;&gt; &lt;/xsl:value-of&gt;&lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt;</pre> </p> <h3>Solution</h3> <p> In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code. </p> <!--XXE_GENERIC_END--> <p><b>Vulnerable Code:</b></p> <p> <pre> Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(input, result);</pre> </p> <br/> <p> The following snippets show two available solutions. You can set one feature or both. </p> <p><b>Solution disabling DTD:</b></p> <p> This setting will protect you against remote file access but not denial of service. <pre> TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, result);</pre> </p> <p>An empty string denies all access to external references for both attributes.</p> <p><b>Solution using "Secure processing" mode:</b></p> <p> This setting will protect you against remote file access but not denial of service. <pre> TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, result);</pre> </p> <br/> <p> <b>References</b><br/> <!--XXE_GENERIC_START--> <a href="https://cwe.mitre.org/data/definitions/611.html">CWE-611: Improper Restriction of XML External Entity Reference ('XXE')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61702260">CERT: IDS10-J. Prevent XML external entity attacks</a><br/> <a href="https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing">OWASP.org: XML External Entity (XXE) Processing</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Expansion">WS-Attacks.org: XML Entity Expansion</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_External_Entity_DOS">WS-Attacks.org: XML External Entity DOS</a><br/> <a href="https://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack">WS-Attacks.org: XML Entity Reference Attack</a><br/> <a href="https://blog.h3xstream.com/2014/06/identifying-xml-external-entity.html">Identifying XML External Entity vulnerability (XXE)</a><br/> <!--XXE_GENERIC_END--> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XPATH_INJECTION' priority='CRITICAL'> <name>Security - Potential XPath Injection</name> <configKey>XPATH_INJECTION</configKey> <description><p> XPath injection risks are similar to SQL injection. If the XPath query contains untrusted user input, the complete data source could be exposed. This could allow an attacker to access unauthorized data or maliciously modify the target XML. </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-39: XPath Injection</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/643.html">CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath Injection')</a><br/> <a href="https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=61407250">CERT: IDS09-J. Prevent XPath Injection (archive)</a><br/> <a href="https://media.blackhat.com/bh-eu-12/Siddharth/bh-eu-12-Siddharth-Xpath-WP.pdf">Black Hat Europe 2012: Hacking XPath 2.0</a><br/> <a href="https://www.balisage.net/Proceedings/vol7/html/Vlist02/BalisageVol7-Vlist02.html">Balisage.net: XQuery Injection</a> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='STRUTS1_ENDPOINT' priority='INFO'> <name>Security - Found Struts 1 endpoint</name> <configKey>STRUTS1_ENDPOINT</configKey> <description><p>This class is a Struts 1 Action.</p> <p>Once a request is routed to this controller, a Form object will automatically be instantiated that contains the HTTP parameters. The use of these parameters should be reviewed to make sure they are used safely.</p></description> <tag>security</tag> </rule> <rule key='STRUTS2_ENDPOINT' priority='INFO'> <name>Security - Found Struts 2 endpoint</name> <configKey>STRUTS2_ENDPOINT</configKey> <description><p>In Struts 2, the endpoints are Plain Old Java Objects (POJO) which means no Interface/Class needs to be implemented/extended.</p> <p>When a request is routed to its controller (like the selected class), the supplied HTTP parameters are automatically mapped to setters for the class. Therefore, all setters of this class should be considered as untrusted input even if the form doesn't include those values. An attacker can simply provide additional values in the request, and they will be set in the object anyway, as long as that object has such a setter. The use of these parameters should be reviewed to make sure they are used safely.</p></description> <tag>security</tag> </rule> <rule key='SPRING_ENDPOINT' priority='INFO'> <name>Security - Found Spring endpoint</name> <configKey>SPRING_ENDPOINT</configKey> <description><p>This class is a Spring Controller. All methods annotated with <code>RequestMapping</code> (as well as its shortcut annotations <code>GetMapping</code>, <code>PostMapping</code>, <code>PutMapping</code>, <code>DeleteMapping</code>, and <code>PatchMapping</code>) are reachable remotely. This class should be analyzed to make sure that remotely exposed methods are safe to expose to potential attackers.</p></description> <tag>security</tag> </rule> <rule key='SPRING_CSRF_PROTECTION_DISABLED' priority='MAJOR'> <name>Security - Spring CSRF protection disabled</name> <configKey>SPRING_CSRF_PROTECTION_DISABLED</configKey> <description><p>Disabling Spring Security's CSRF protection is unsafe for standard web applications.</p> <p>A valid use case for disabling this protection would be a service exposing state-changing operations that is guaranteed to be used only by non-browser clients.</p> <p> <b>Insecure configuration:</b><br/> <pre>@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }</pre> </p> <p> <b>References</b><br/> <a href="https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection">Spring Security Official Documentation: When to use CSRF protection</a><br/> <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29">OWASP: Cross-Site Request Forgery</a><br/> <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet">OWASP: CSRF Prevention Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/352.html">CWE-352: Cross-Site Request Forgery (CSRF)</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING' priority='MAJOR'> <name>Security - Spring CSRF unrestricted RequestMapping</name> <configKey>SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING</configKey> <description><p>Methods annotated with <code>RequestMapping</code> are by default mapped to all the HTTP request methods. However, Spring Security's CSRF protection is not enabled by default for the HTTP request methods <code>GET</code>, <code>HEAD</code>, <code>TRACE</code>, and <code>OPTIONS</code> (as this could cause the tokens to be leaked). Therefore, state-changing methods annotated with <code>RequestMapping</code> and not narrowing the mapping to the HTTP request methods <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, or <code>PATCH</code> are vulnerable to CSRF attacks.</p> <p> <b>Vulnerable Code:</b><br/> <pre>@Controller public class UnsafeController { @RequestMapping("/path") public void writeData() { // State-changing operations performed within this method. } }</pre> </p> <p> <b>Solution (Spring Framework 4.3 and later):</b><br/> <pre>@Controller public class SafeController { /** * For methods without side-effects use @GetMapping. */ @GetMapping("/path") public String readData() { // No state-changing operations performed within this method. return ""; } /** * For state-changing methods use either @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping. */ @PostMapping("/path") public void writeData() { // State-changing operations performed within this method. } }</pre> </p> <p> <b>Solution (Before Spring Framework 4.3):</b><br/> <pre>@Controller public class SafeController { /** * For methods without side-effects use either * RequestMethod.GET, RequestMethod.HEAD, RequestMethod.TRACE, or RequestMethod.OPTIONS. */ @RequestMapping(value = "/path", method = RequestMethod.GET) public String readData() { // No state-changing operations performed within this method. return ""; } /** * For state-changing methods use either * RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, or RequestMethod.PATCH. */ @RequestMapping(value = "/path", method = RequestMethod.POST) public void writeData() { // State-changing operations performed within this method. } }</pre> </p> <p> <b>References</b><br/> <a href="https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-use-proper-verbs">Spring Security Official Documentation: Use proper HTTP verbs (CSRF protection)</a><br/> <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29">OWASP: Cross-Site Request Forgery</a><br/> <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet">OWASP: CSRF Prevention Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/352.html">CWE-352: Cross-Site Request Forgery (CSRF)</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION' priority='CRITICAL'> <name>Security - Potential SQL Injection</name> <configKey>SQL_INJECTION</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Alternatively to prepare statements, each parameter can be escaped manually. </p> <p> <b>Vulnerable Code:</b><br/> <pre> createQuery("select * from User where id = '"+inputId+"'"); </pre> </p> <p> <b>Solution:</b><br/> <pre> import org.owasp.esapi.Encoder; createQuery("select * from User where id = '"+Encoder.encodeForSQL(inputId)+"'"); </pre> </p> <br/> <p> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_TURBINE' priority='CRITICAL'> <name>Security - Potential SQL Injection with Turbine</name> <configKey>SQL_INJECTION_TURBINE</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Turbine API provide a DSL to build query with Java code. </p> <p> <b>Vulnerable Code:</b><br/> <pre> List&lt;Record&gt; BasePeer.executeQuery( "select * from Customer where id=" + inputId ); </pre> </p> <p> <b>Solution (using Criteria DSL):</b><br/> <pre> Criteria c = new Criteria(); c.add( CustomerPeer.ID, inputId ); List&lt;Customer&gt; customers = CustomerPeer.doSelect( c ); </pre> <b>Solution (using specialized method):</b><br/> <pre> Customer customer = CustomerPeer.retrieveByPK( new NumberKey( inputId ) ); </pre> <b>Solution (using OWASP Encoder):</b><br/> <pre> import org.owasp.esapi.Encoder; BasePeer.executeQuery("select * from Customer where id = '"+Encoder.encodeForSQL(inputId)+"'"); </pre> </p> <br/> <p> <b>References (Turbine)</b><br/> <a href="https://turbine.apache.org/turbine/turbine-2.1/howto/criteria-howto.html">Turbine Documentation: Criteria Howto</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_HIBERNATE' priority='CRITICAL'> <name>Security - Potential SQL/HQL Injection (Hibernate)</name> <configKey>SQL_INJECTION_HIBERNATE</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Alternatively to prepare statements, Hibernate Criteria can be used. </p> <p> <b>Vulnerable Code:</b><br/> <pre> Session session = sessionFactory.openSession(); Query q = session.createQuery("select t from UserEntity t where id = " + input); q.execute();</pre> </p> <p> <b>Solution:</b><br/> <pre> Session session = sessionFactory.openSession(); Query q = session.createQuery("select t from UserEntity t where id = :userId"); q.setString("userId",input); q.execute();</pre> </p> <p> <b>Solution for dynamic queries (with Hibernate Criteria):</b><br/> <pre> Session session = sessionFactory.openSession(); Query q = session.createCriteria(UserEntity.class) .add( Restrictions.like("id", input) ) .list(); q.execute();</pre> </p> <br/> <p> <b>References (Hibernate)</b><br/> <a href="https://cwe.mitre.org/data/definitions/564.html">CWE-564: SQL Injection: Hibernate</a><br/> <a href="https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html">Hibernate Documentation: Query Criteria</a><br/> <a href="https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html">Hibernate Javadoc: Query Object</a><br/> <a href="https://blog.h3xstream.com/2014/02/hql-for-pentesters.html">HQL for pentesters</a>: Guideline to test if the suspected code is exploitable.<br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_JDO' priority='CRITICAL'> <name>Security - Potential SQL/JDOQL Injection (JDO)</name> <configKey>SQL_INJECTION_JDO</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. </p> <p> <b>Vulnerable Code:</b><br/> <pre> PersistenceManager pm = getPM(); Query q = pm.newQuery("select * from Users where name = " + input); q.execute();</pre> </p> <p> <b>Solution:</b><br/> <pre> PersistenceManager pm = getPM(); Query q = pm.newQuery("select * from Users where name = nameParam"); q.declareParameters("String nameParam"); q.execute(input);</pre> </p> <br/> <p> <b>References (JDO)</b><br/> <a href="https://db.apache.org/jdo/object_retrieval.html">JDO: Object Retrieval</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_JPA' priority='CRITICAL'> <name>Security - Potential SQL/JPQL Injection (JPA)</name> <configKey>SQL_INJECTION_JPA</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. </p> <p> <b>Vulnerable Code:</b><br/> <pre> EntityManager pm = getEM(); TypedQuery&lt;UserEntity&gt; q = em.createQuery( String.format("select * from Users where name = %s", username), UserEntity.class); UserEntity res = q.getSingleResult();</pre> </p> <p> <b>Solution:</b><br/> <pre> TypedQuery&lt;UserEntity&gt; q = em.createQuery( "select * from Users where name = usernameParam",UserEntity.class) .setParameter("usernameParam", username); UserEntity res = q.getSingleResult();</pre> </p> <br/> <p> <b>References (JPA)</b><br/> <a href="https://docs.oracle.com/javaee/6/tutorial/doc/bnbrg.html">The Java EE 6 Tutorial: Creating Queries Using the Java Persistence Query Language</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_SPRING_JDBC' priority='CRITICAL'> <name>Security - Potential JDBC Injection (Spring JDBC)</name> <configKey>SQL_INJECTION_SPRING_JDBC</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. </p> <p> <b>Vulnerable Code:</b><br/> <pre>JdbcTemplate jdbc = new JdbcTemplate(); int count = jdbc.queryForObject("select count(*) from Users where name = '"+paramName+"'", Integer.class); </pre> <pre>@Value("properties") private String sql; public function count() { JdcbOperation jdbc = new JdcbOperation(); int count = jdbc.query(sql); }</pre> </p> <p> <b>Solution:</b><br/> <pre>JdbcTemplate jdbc = new JdbcTemplate(); int count = jdbc.queryForObject("select count(*) from Users where name = ?", Integer.class, paramName);</pre> <pre>private final static String sql = "select count(*) from Users"; public function count() { JdcbOperation jdbc = new JdcbOperation(); int count = jdbc.query(sql); }</pre> </p> <br/> <b>References (Spring JDBC)</b><br/> <a href="https://spring.io/guides/gs/relational-data-access/">Spring Official Documentation: Data access with JDBC</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_JDBC' priority='CRITICAL'> <name>Security - Potential JDBC Injection</name> <configKey>SQL_INJECTION_JDBC</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. </p> <p> <b>Vulnerable Code:</b><br/> <pre>Connection conn = [...]; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("update COFFEES set SALES = "+nbSales+" where COF_NAME = '"+coffeeName+"'");</pre> </p> <p> <b>Solution:</b><br/> <pre>Connection conn = [...]; conn.prepareStatement("update COFFEES set SALES = ? where COF_NAME = ?"); updateSales.setInt(1, nbSales); updateSales.setString(2, coffeeName);</pre> </p> <br/> <b>References (JDBC)</b><br/> <a href="https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html">Oracle Documentation: The Java Tutorials &gt; Prepared Statements</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_VERTX' priority='CRITICAL'> <name>Security - Potential SQL Injection with Vert.x Sql Client</name> <configKey>SQL_INJECTION_VERTX</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Vert.x Sql Client API provide a DSL to build query with Java code. </p> <p> <b>Vulnerable Code:</b><br/> <pre> SqlClient.query( "select * from Customer where id=" + inputId ).execute(ar -> ...); </pre> </p> <p> <b>Solution (using Prepared Statements):</b><br/> <pre> client .preparedQuery( "SELECT * FROM users WHERE id=$1" ) .execute(Tuple.of("julien")) .onSuccess(rows -> ...) .onFailure(err -> ...); </pre> </p> <br/> <p> <b>References (Vert.x Sql Client)</b><br/> <a href="https://vertx.io/docs/#databases">Vertx Database Access Documentation</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SQL_INJECTION_ANDROID' priority='CRITICAL'> <name>Security - Potential Android SQL Injection</name> <configKey>SQL_INJECTION_ANDROID</configKey> <description><p> The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. </p> <p> <b>Vulnerable Code:</b><br/> <pre>String query = "SELECT * FROM messages WHERE uid= '"+userInput+"'" ; Cursor cursor = this.getReadableDatabase().rawQuery(query,null);</pre> </p> <p> <b>Solution:</b><br/> <pre>String query = "SELECT * FROM messages WHERE uid= ?" ; Cursor cursor = this.getReadableDatabase().rawQuery(query,new String[] {userInput});</pre> </p> <br/> <b>References (Android SQLite)</b><br/> <a href="http://www.informit.com/articles/article.aspx?p=2268753&seqNum=5">InformIT.com: Practical Advice for Building Secure Android Databases in SQLite</a><br/> <a href="https://www.packtpub.com/books/content/knowing-sql-injection-attacks-and-securing-our-android-applications-them">Packtpub.com: Knowing the SQL-injection attacks and securing our Android applications from them</a><br/> <a href="https://books.google.ca/books?id=SXlMAQAAQBAJ&lpg=PR1&pg=PA64#v=onepage&q&f=false">Android Database Support (Enterprise Android: Programming Android Database Applications for the Enterprise)</a><br/> <a href="https://stackoverflow.com/a/29797229/89769">Safe example of Insert, Select, Update and Delete queries provided by Suragch</a><br/> <b>References (SQL injection)</b><br/> <a href="http://projects.webappsec.org/w/page/13246963/SQL%20Injection">WASC-19: SQL Injection</a><br/> <a href="https://capec.mitre.org/data/definitions/66.html">CAPEC-66: SQL Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A1-Injection">OWASP: Top 10 2013-A1-Injection</a><br/> <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet">OWASP: SQL Injection Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet">OWASP: Query Parameterization Cheat Sheet</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='LDAP_INJECTION' priority='CRITICAL'> <name>Security - Potential LDAP Injection</name> <configKey>LDAP_INJECTION</configKey> <description><p> Just like SQL, all inputs passed to an LDAP query need to be passed in safely. Unfortunately, LDAP doesn't have prepared statement interfaces like SQL. Therefore, the primary defense against LDAP injection is strong input validation of any untrusted data before including it in an LDAP query. </p> <p> <strong>Code at risk:</strong><br/> <pre>NamingEnumeration&lt;SearchResult&gt; answers = context.search("dc=People,dc=example,dc=com", "(uid=" + username + ")", ctrls);</pre> </p> <br/> <p><strong>Solution:</strong></p> <p> Safe evaluation of Java code using "StringUtils" library.<br/> <pre>if(StringUtils.isAlphanumeric(username)) { NamingEnumeration&lt;SearchResult&gt; answers = context.search("dc=People,dc=example,dc=com", "(uid=" + username + ")", ctrls); }</pre> </p> <br/><p> <strong>References</strong><br/> <a href="https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html">LDAP Injection Prevention Cheat Sheet</a><br/> <a href="https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A1-Injection">OWASP: Top 10 A1:2017-Injection</a><br/> <a href="http://projects.webappsec.org/w/page/13246947/LDAP%20Injection">WASC-29: LDAP Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/90.html">CWE-90: Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SCRIPT_ENGINE_INJECTION' priority='CRITICAL'> <name>Security - Potential code injection when using Script Engine</name> <configKey>SCRIPT_ENGINE_INJECTION</configKey> <description><p> Dynamic code is being evaluated. A careful analysis of the code construction should be made. Malicious code execution could lead to data leakage or operating system compromised. </p> <p> If the evaluation of user code is intended, a proper sandboxing should be applied (see references). </p> <p><b>Code at risk:</b></p> <p> <pre> public void runCustomTrigger(String script) { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(script); //Bad things can happen here. }</pre> </p> <p><b>Solution:</b></p> <p> Safe evaluation of JavaScript code using "Cloudbees Rhino Sandbox" library.<br/> <pre> public void runCustomTrigger(String script) { SandboxContextFactory contextFactory = new SandboxContextFactory(); Context context = contextFactory.makeContext(); contextFactory.enterContext(context); try { ScriptableObject prototype = context.initStandardObjects(); prototype.setParentScope(null); Scriptable scope = context.newObject(prototype); scope.setPrototype(prototype); context.evaluateString(scope,script, null, -1, null); } finally { context.exit(); } }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://github.com/cloudbees/rhino-sandbox">Cloudbees Rhino Sandbox</a>: Utility to create sandbox with Rhino (block access to all classes)<br/> <a href="https://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/">CodeUtopia.net: Sandboxing Rhino in Java</a><br/> <a href="https://blog.h3xstream.com/2014/11/remote-code-execution-by-design.html">Remote Code Execution .. by design</a>: Example of malicious payload. The samples given could be used to test sandboxing rules.<br/> <a href="https://cwe.mitre.org/data/definitions/94.html">CWE-94: Improper Control of Generation of Code ('Code Injection')</a><br/> <a href="https://cwe.mitre.org/data/definitions/95.html">CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SPEL_INJECTION' priority='CRITICAL'> <name>Security - Potential code injection when using Spring Expression</name> <configKey>SPEL_INJECTION</configKey> <description><p> A Spring expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. </p> <p><b>Code at risk:</b></p> <p> <pre> public void parseExpressionInterface(Person personObj,String property) { ExpressionParser parser = new SpelExpressionParser(); //Unsafe if the input is control by the user.. Expression exp = parser.parseExpression(property+" == 'Albert'"); StandardEvaluationContext testContext = new StandardEvaluationContext(personObj); boolean result = exp.getValue(testContext, Boolean.class); [...]</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/94.html">CWE-94: Improper Control of Generation of Code ('Code Injection')</a><br/> <a href="https://cwe.mitre.org/data/definitions/95.html">CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')</a><br/> <a href="https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/expressions.html">Spring Expression Language (SpEL) - Official Documentation</a><br/> <a href="https://www.mindedsecurity.com/fileshare/ExpressionLanguageInjection.pdf">Minded Security: Expression Language Injection</a><br/> <a href="https://blog.h3xstream.com/2014/11/remote-code-execution-by-design.html">Remote Code Execution .. by design</a>: Example of malicious payload. The samples given could be used to test sandboxing rules.<br/> <a href="https://gosecure.net/2018/05/15/beware-of-the-magic-spell-part-1-cve-2018-1273/">Spring Data-Commons: (CVE-2018-1273)</a><br/> <a href="https://gosecure.net/2018/05/17/beware-of-the-magic-spell-part-2-cve-2018-1260/">Spring OAuth2: CVE-2018-1260</a> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='EL_INJECTION' priority='CRITICAL'> <name>Security - Potential code injection when using Expression Language (EL)</name> <configKey>EL_INJECTION</configKey> <description><p> An expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. </p> <p><b>Code at risk:</b></p> <p> <pre>public void evaluateExpression(String expression) { FacesContext context = FacesContext.getCurrentInstance(); ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory(); ELContext elContext = context.getELContext(); ValueExpression vex = expressionFactory.createValueExpression(elContext, expression, String.class); return (String) vex.getValue(elContext); }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://blog.mindedsecurity.com/2015/11/reliable-os-shell-with-el-expression.html">Minded Security: Abusing EL for executing OS commands</a><br/> <a href="https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html">The Java EE 6 Tutorial: Expression Language</a><br/> <a href="https://cwe.mitre.org/data/definitions/94.html">CWE-94: Improper Control of Generation of Code ('Code Injection')</a><br/> <a href="https://cwe.mitre.org/data/definitions/95.html">CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')</a><br/> <a href="https://www.mindedsecurity.com/fileshare/ExpressionLanguageInjection.pdf">Minded Security: Expression Language Injection</a><br/> <a href="http://danamodio.com/appsec/research/spring-remote-code-with-expression-language-injection/">Dan Amodio's blog: Remote Code with Expression Language Injection</a><br/> <a href="https://blog.h3xstream.com/2014/11/remote-code-execution-by-design.html">Remote Code Execution .. by design</a>: Example of malicious payload. The samples given could be used to test sandboxing rules.<br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SEAM_LOG_INJECTION' priority='CRITICAL'> <name>Security - Potential code injection in Seam logging call</name> <configKey>SEAM_LOG_INJECTION</configKey> <description><p> Seam Logging API support an expression language to introduce bean property to log messages. The expression language can also be the source to unwanted code execution. </p> <p> In this context, an expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. </p> <p><b>Code at risk:</b></p> <p> <pre>public void logUser(User user) { log.info("Current logged in user : " + user.getUsername()); //... }</pre> </p> <p><b>Solution:</b></p> <p> <pre>public void logUser(User user) { log.info("Current logged in user : #0", user.getUsername()); //... }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://issues.jboss.org/browse/JBSEAM-5130">JBSEAM-5130: Issue documenting the risk</a><br/> <a href="https://docs.jboss.org/seam/2.3.1.Final/reference/html_single/#d0e4185">JBoss Seam: Logging (Official documentation)</a><br/> <a href="https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html">The Java EE 6 Tutorial: Expression Language</a><br/> <a href="https://cwe.mitre.org/data/definitions/94.html">CWE-94: Improper Control of Generation of Code ('Code Injection')</a><br/> <a href="https://cwe.mitre.org/data/definitions/95.html">CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='OGNL_INJECTION' priority='CRITICAL'> <name>Security - Potential code injection when using OGNL expression</name> <configKey>OGNL_INJECTION</configKey> <description><p> A expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. </p> <p><b>Code at risk:</b></p> <p> <pre> public void getUserProperty(String property) { [...] //The first argument is the dynamic expression. return ognlUtil.getValue("user."+property, ctx, root, String.class); } </pre> </p> <p><b>Solution:</b></p> <p> In general, method evaluating OGNL expression should not receive user input. It is intended to be used in static configurations. </p> <br/> <p> <b>References</b><br/> <a href="https://community.saas.hpe.com/t5/Security-Research/Struts-2-OGNL-Expression-Injections/ba-p/288881">HP Enterprise: Struts 2 OGNL Expression Injections by Alvaro Mu&Atilde;&plusmn;oz</a><br/> <a href="https://blog.gdssecurity.com/labs/2017/3/27/an-analysis-of-cve-2017-5638.html">Gotham Digital Science: An Analysis Of CVE-2017-5638</a><br/> <a href="https://struts.apache.org/docs/s2-016.html">Apache Struts2: Vulnerability S2-016</a><br/> <a href="https://struts.apache.org/docs/ognl.html">Apache Struts 2 Documentation: OGNL</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>security</tag> </rule> <rule key='GROOVY_SHELL' priority='CRITICAL'> <name>Security - Potential code injection when using GroovyShell</name> <configKey>GROOVY_SHELL</configKey> <description><p> A expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. </p> <p><b>Code at risk:</b></p> <p> <pre> public void evaluateScript(String script) { GroovyShell shell = new GroovyShell(); shell.evaluate(script); } </pre> </p> <p><b>Solution:</b></p> <p> In general, method evaluating Groovy expression should not receive user input from low privilege users. </p> <br/> <p> <b>References</b><br/> <a href="https://blog.orange.tw/2019/02/abusing-meta-programming-for-unauthenticated-rce.html">Hacking Jenkins Part 2 - Abusing Meta Programming for Unauthenticated RCE!</a> by Orange Tsai<br/> <a href="https://github.com/orangetw/awesome-jenkins-rce-2019">Jenkins RCE payloads</a> by Orange Tsai<br/> <a href="https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc">POC for CVE-2019-1003001</a> by Adam Jordan<br/> <a href="https://github.com/welk1n/exploiting-groovy-in-Java/">Various payloads of exploiting Groovy code evaluation</a><br/> </p></description> <tag>security</tag> </rule> <rule key='HTTP_RESPONSE_SPLITTING' priority='INFO'> <name>Security - Potential HTTP Response Splitting</name> <configKey>HTTP_RESPONSE_SPLITTING</configKey> <description><p> When an HTTP request contains unexpected <code>CR</code> and <code>LF</code> characters, the server may respond with an output stream that is interpreted as two different HTTP responses (instead of one). An attacker can control the second response and mount attacks such as cross-site scripting and cache poisoning attacks. According to OWASP, the issue has been fixed in virtually all modern Java EE application servers, but it is still better to validate the input. If you are concerned about this risk, you should test on the platform of concern to see if the underlying platform allows for <code>CR</code> or <code>LF</code> characters to be injected into headers. This weakness is reported with low priority because it requires the web container to be vulnerable. </p> <br/> <p> <b>Code at risk:</b><br/> <pre>String author = request.getParameter(AUTHOR_PARAMETER); // ... Cookie cookie = new Cookie("author", author); response.addCookie(cookie);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/HTTP_Response_Splitting">OWASP: HTTP Response Splitting</a><br/> <a href="https://cwe.mitre.org/data/definitions/113.html">CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')</a> <a href="https://cwe.mitre.org/data/definitions/93.html">CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='CRLF_INJECTION_LOGS' priority='INFO'> <name>Security - Potential CRLF Injection for logs</name> <configKey>CRLF_INJECTION_LOGS</configKey> <description><p> When data from an untrusted source is put into a logger and not neutralized correctly, an attacker could forge log entries or include malicious content. Inserted false entries could be used to skew statistics, distract the administrator or even to implicate another party in the commission of a malicious act. If the log file is processed automatically, the attacker can render the file unusable by corrupting the format of the file or injecting unexpected characters. An attacker may also inject code or other commands into the log file and take advantage of a vulnerability in the log processing utility (e.g. command injection or XSS). </p> <br/> <p> <b>Code at risk:</b><br/> <pre>String val = request.getParameter("user"); String metadata = request.getParameter("metadata"); [...] if(authenticated) { log.info("User " + val + " (" + metadata + ") was authenticated successfully"); } else { log.info("User " + val + " (" + metadata + ") was not authenticated"); } </pre> A malicious user could send the metadata parameter with the value: <code>"Firefox) was authenticated successfully\r\n[INFO] User bbb (Internet Explorer"</code>. </p> <b>Solution:</b><br/> <p> You can manually sanitize each parameter. <pre> log.info("User " + val.replaceAll("[\r\n]","") + " (" + userAgent.replaceAll("[\r\n]","") + ") was not authenticated"); </pre> </p> <p> You can also configure your logger service to replace new line for all message events. Here is sample configuration for LogBack <a href="https://logback.qos.ch/manual/layouts.html#replace">using the <code>replace</code> function</a>. <pre> &lt;pattern&gt;%-5level - %replace(%msg){'[\r\n]', ''}%n&lt;/pattern&gt; </pre> </p> <p> Finally, you can use a logger implementation that replace new line by spaces. The project <a href="https://github.com/javabeanz/owasp-security-logging">OWASP Security Logging</a> has an implementation for Logback and Log4j. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/117.html">CWE-117: Improper Output Neutralization for Logs</a><br/> <a href="https://cwe.mitre.org/data/definitions/93.html">CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')</a><br/> <a href="https://logback.qos.ch/manual/layouts.html#replace">CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')</a><br/> <a href="https://github.com/javabeanz/owasp-security-logging">OWASP Security Logging</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='EXTERNAL_CONFIG_CONTROL' priority='INFO'> <name>Security - Potential external control of configuration</name> <configKey>EXTERNAL_CONFIG_CONTROL</configKey> <description><p> Allowing external control of system settings can disrupt service or cause an application to behave in unexpected, and potentially malicious ways. An attacker could cause an error by providing a nonexistent catalog name or connect to an unauthorized portion of the database. </p> <br/> <p> <b>Code at risk:</b><br/> <pre>conn.setCatalog(request.getParameter("catalog"));</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/15.html">CWE-15: External Control of System or Configuration Setting</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='BAD_HEXA_CONVERSION' priority='MAJOR'> <name>Security - Bad hexadecimal concatenation</name> <configKey>BAD_HEXA_CONVERSION</configKey> <description><p>When converting a byte array containing a hash signature to a human readable string, a conversion mistake can be made if the array is read byte by byte. The following sample illustrates the use of the method <code>Integer.toHexString()</code> which will trim any leading zeroes from each byte of the computed hash value. <pre> MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] resultBytes = md.digest(password.getBytes("UTF-8")); StringBuilder stringBuilder = new StringBuilder(); for(byte b :resultBytes) { stringBuilder.append( Integer.toHexString( b & 0xFF ) ); } return stringBuilder.toString();</pre> </p> <p> This mistake weakens the hash value computed since it introduces more collisions. For example, the hash values "0x0679" and "0x6709" would both output as "679" for the above function. </p> <p> In this situation, the method <code>Integer.toHexString()</code> should be replaced with <code>String.format()</code> as follows: <pre>stringBuilder.append( String.format( "%02X", b ) );</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/704.html">CWE-704: Incorrect Type Conversion or Cast</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='HAZELCAST_SYMMETRIC_ENCRYPTION' priority='MAJOR'> <name>Security - Hazelcast symmetric encryption</name> <configKey>HAZELCAST_SYMMETRIC_ENCRYPTION</configKey> <description><p>The network communications for Hazelcast is configured to use a symmetric cipher (probably DES or Blowfish).</p> <p>Those ciphers alone do not provide integrity or secure authentication. The use of asymmetric encryption is preferred.</p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246945/Insufficient%20Transport%20Layer%20Protection">WASC-04: Insufficient Transport Layer Protection</a><br/> <a href="https://docs.hazelcast.org/docs/3.5/manual/html/encryption.html">Hazelcast Documentation: Encryption</a><br/> <a href="https://cwe.mitre.org/data/definitions/326.html">CWE-326: Inadequate Encryption Strength</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='NULL_CIPHER' priority='MAJOR'> <name>Security - NullCipher is insecure</name> <configKey>NULL_CIPHER</configKey> <description><p> The NullCipher is rarely used intentionally in production applications. It implements the Cipher interface by returning ciphertext identical to the supplied plaintext. In a few contexts, such as testing, a NullCipher may be appropriate. </p> <p> <b>Vulnerable Code:</b><br/> <pre>Cipher doNothingCihper = new NullCipher(); [...] //The ciphertext produced will be identical to the plaintext. byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Solution:</b><br/> Avoid using the NullCipher. Its accidental use can introduce a significant confidentiality risk. </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/327.html">CWE-327: Use of a Broken or Risky Cryptographic Algorithm</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='UNENCRYPTED_SOCKET' priority='MAJOR'> <name>Security - Unencrypted Socket</name> <configKey>UNENCRYPTED_SOCKET</configKey> <description><p> The communication channel used is not encrypted. The traffic could be read by an attacker intercepting the network traffic. </p> <p> <b>Vulnerable Code:</b><br/> Plain socket (Cleartext communication): <pre>Socket soc = new Socket("www.google.com",80);</pre> </p> <p> <b>Solution:</b><br/> SSL Socket (Secure communication): <pre>Socket soc = SSLSocketFactory.getDefault().createSocket("www.google.com", 443);</pre> </p> <p>Beyond using an SSL socket, you need to make sure your use of SSLSocketFactory does all the appropriate certificate validation checks to make sure you are not subject to man-in-the-middle attacks. Please read the OWASP Transport Layer Protection Cheat Sheet for details on how to do this correctly. </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Top_10_2010-A9">OWASP: Top 10 2010-A9-Insufficient Transport Layer Protection</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A6-Sensitive_Data_Exposure">OWASP: Top 10 2013-A6-Sensitive Data Exposure</a><br/> <a href="https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet">OWASP: Transport Layer Protection Cheat Sheet</a><br/> <a href="http://projects.webappsec.org/w/page/13246945/Insufficient%20Transport%20Layer%20Protection">WASC-04: Insufficient Transport Layer Protection</a><br/> <a href="https://cwe.mitre.org/data/definitions/319.html">CWE-319: Cleartext Transmission of Sensitive Information</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='UNENCRYPTED_SERVER_SOCKET' priority='MAJOR'> <name>Security - Unencrypted Server Socket</name> <configKey>UNENCRYPTED_SERVER_SOCKET</configKey> <description><p> The communication channel used is not encrypted. The traffic could be read by an attacker intercepting the network traffic. </p> <p> <b>Vulnerable Code:</b><br/> Plain server socket (Cleartext communication): <pre>ServerSocket soc = new ServerSocket(1234);</pre> </p> <p> <b>Solution:</b><br/> SSL Server Socket (Secure communication): <pre>ServerSocket soc = SSLServerSocketFactory.getDefault().createServerSocket(1234);</pre> </p> <p>Beyond using an SSL server socket, you need to make sure your use of SSLServerSocketFactory does all the appropriate certificate validation checks to make sure you are not subject to man-in-the-middle attacks. Please read the OWASP Transport Layer Protection Cheat Sheet for details on how to do this correctly. </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Top_10_2010-A9">OWASP: Top 10 2010-A9-Insufficient Transport Layer Protection</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A6-Sensitive_Data_Exposure">OWASP: Top 10 2013-A6-Sensitive Data Exposure</a><br/> <a href="https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet">OWASP: Transport Layer Protection Cheat Sheet</a><br/> <a href="http://projects.webappsec.org/w/page/13246945/Insufficient%20Transport%20Layer%20Protection">WASC-04: Insufficient Transport Layer Protection</a><br/> <a href="https://cwe.mitre.org/data/definitions/319.html">CWE-319: Cleartext Transmission of Sensitive Information</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='DES_USAGE' priority='MAJOR'> <name>Security - DES is insecure</name> <configKey>DES_USAGE</configKey> <description><p> DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage of AES block ciphers instead of DES. </p> <p> <b>Example weak code:</b> <pre>Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Example solution:</b> <pre>Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.nist.gov/news-events/news/2005/06/nist-withdraws-outdated-data-encryption-standard">NIST Withdraws Outdated Data Encryption Standard</a><br/> <a href="https://cwe.mitre.org/data/definitions/326.html">CWE-326: Inadequate Encryption Strength</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='TDES_USAGE' priority='MAJOR'> <name>Security - DESede is insecure</name> <configKey>TDES_USAGE</configKey> <description><p> Triple DES (also known as 3DES or DESede) is considered strong ciphers for modern applications. Currently, NIST recommends the usage of AES block ciphers instead of 3DES. </p> <p> <b>Example weak code:</b> <pre>Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Example solution:</b> <pre>Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.nist.gov/news-events/news/2005/06/nist-withdraws-outdated-data-encryption-standard">NIST Withdraws Outdated Data Encryption Standard</a><br/> <a href="https://cwe.mitre.org/data/definitions/326.html">CWE-326: Inadequate Encryption Strength</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='RSA_NO_PADDING' priority='MAJOR'> <name>Security - RSA with no padding is insecure</name> <configKey>RSA_NO_PADDING</configKey> <description><p> The software uses the RSA algorithm but does not incorporate Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption. </p> <p> <b>Vulnerable Code:</b><br/> <pre>Cipher.getInstance("RSA/NONE/NoPadding")</pre> </p> <p> <b>Solution:</b><br/> The code should be replaced with:<br/> <pre>Cipher.getInstance("RSA/ECB/OAEPWithMD5AndMGF1Padding")</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/780.html">CWE-780: Use of RSA Algorithm without OAEP</a><br/> <a href="https://rdist.root.org/2009/10/06/why-rsa-encryption-padding-is-critical/">Root Labs: Why RSA encryption padding is critical</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='HARD_CODE_PASSWORD' priority='MAJOR'> <name>Security - Hard coded password</name> <configKey>HARD_CODE_PASSWORD</configKey> <description><p> Passwords should not be kept in the source code. The source code can be widely shared in an enterprise environment, and is certainly shared in open source. To be managed safely, passwords and secret keys should be stored in separate configuration files or keystores. (Hard coded keys are reported separately by <i>Hard Coded Key</i> pattern) </p> <p> <p><b>Vulnerable Code:</b><br/> <pre>private String SECRET_PASSWORD = "letMeIn!"; Properties props = new Properties(); props.put(Context.SECURITY_CREDENTIALS, "p@ssw0rd");</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/259.html">CWE-259: Use of Hard-coded Password</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='HARD_CODE_KEY' priority='MAJOR'> <name>Security - Hard coded key</name> <configKey>HARD_CODE_KEY</configKey> <description><p> Cryptographic keys should not be kept in the source code. The source code can be widely shared in an enterprise environment, and is certainly shared in open source. To be managed safely, passwords and secret keys should be stored in separate configuration files or keystores. (Hard coded passwords are reported separately by the <i>Hard coded password</i> pattern) </p> <p> <p><b>Vulnerable Code:</b><br/> <pre>byte[] key = {1, 2, 3, 4, 5, 6, 7, 8}; SecretKeySpec spec = new SecretKeySpec(key, "AES"); Cipher aes = Cipher.getInstance("AES"); aes.init(Cipher.ENCRYPT_MODE, spec); return aesCipher.doFinal(secretData);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/321.html">CWE-321: Use of Hard-coded Cryptographic Key</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='UNSAFE_HASH_EQUALS' priority='MAJOR'> <name>Security - Unsafe hash equals</name> <configKey>UNSAFE_HASH_EQUALS</configKey> <description><p> An attacker might be able to detect the value of the secret hash due to the exposure of comparison timing. When the functions <code>Arrays.equals()</code> or <code>String.equals()</code> are called, they will exit earlier if fewer bytes are matched. </p> <p> <p><b>Vulnerable Code:</b><br/> <pre> String actualHash = ... if(userInput.equals(actualHash)) { ... }</pre> </p> <p><b>Solution:</b><br/> <pre> String actualHash = ... if(MessageDigest.isEqual(userInput.getBytes(),actualHash.getBytes())) { ... }</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/203.html">CWE-203: Information Exposure Through DiscrepancyKey</a><br/> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='STRUTS_FORM_VALIDATION' priority='INFO'> <name>Security - Struts Form without input validation</name> <configKey>STRUTS_FORM_VALIDATION</configKey> <description><p> Form inputs should have minimal input validation. Preventive validation helps provide defense in depth against a variety of risks. </p> <p> Validation can be introduced by implementing a <code>validate</code> method. <pre> public class RegistrationForm extends ValidatorForm { private String name; private String email; [...] public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { //Validation code for name and email parameters passed in via the HttpRequest goes here } } </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a><br/> <a href="https://cwe.mitre.org/data/definitions/106.html">CWE-106: Struts: Plug-in Framework not in Use</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XSS_REQUEST_WRAPPER' priority='MAJOR'> <name>Security - XSSRequestWrapper is a weak XSS protection</name> <configKey>XSS_REQUEST_WRAPPER</configKey> <description><p> An implementation of <code>HttpServletRequestWrapper</code> called <code>XSSRequestWrapper</code> was published through various blog sites. <sup><a href="https://java.dzone.com/articles/stronger-anti-cross-site">[1]</a></sup> <sup><a href="https://www.javacodegeeks.com/2012/07/anti-cross-site-scripting-xss-filter.html">[2]</a></sup> </p> <p> The filtering is weak for a few reasons: <ul> <li>It covers only parameters not headers and side-channel inputs</li> <li>The chain of replace functions can be bypassed easily (see example below)</li> <li>It's a black list of very specific bad patterns (rather than a white list of good/valid input)</li> </ul> </p> <p> <b>Example of bypass:</b><br/> </p> <pre>&lt;scrivbscript:pt&gt;alert(1)&lt;/scrivbscript:pt&gt;</pre> <p> The previous input will be transformed into <b><code>"&lt;script&gt;alert(1)&lt;/script&gt;"</code></b>. The removal of <code>"vbscript:"</code> is after the replacement of <code>"&lt;script&gt;.*&lt;/script&gt;"</code>. </p> <p> For stronger protection, choose a solution that encodes characters automatically in the <b><u>view</u></b> (template or JSP) following the XSS protection rules defined in the OWASP XSS Prevention Cheat Sheet. </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246920/Cross%20Site%20Scripting">WASC-8: Cross Site Scripting</a><br/> <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet">OWASP: XSS Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_%28XSS%29">OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)</a><br/> <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')</a> </p></description> <tag>owasp-a3</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='BLOWFISH_KEY_SIZE' priority='MAJOR'> <name>Security - Blowfish usage with short key</name> <configKey>BLOWFISH_KEY_SIZE</configKey> <description><p> The Blowfish cipher supports key sizes from 32 bits to 448 bits. A small key size makes the ciphertext vulnerable to brute force attacks. At least 128 bits of entropy should be used when generating the key if use of Blowfish is required. </p> <p> If the algorithm can be changed, the AES block cipher should be used instead. </p> <p><b>Vulnerable Code:</b><br/> <pre>KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish"); keyGen.init(64);</pre> </p> <p><b>Solution:</b><br/> <pre>KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish"); keyGen.init(128);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://en.wikipedia.org/wiki/Blowfish_(cipher)">Blowfish (cipher)</a><br/> <a href="https://cwe.mitre.org/data/definitions/326.html">CWE-326: Inadequate Encryption Strength</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='RSA_KEY_SIZE' priority='MAJOR'> <name>Security - RSA usage with short key</name> <configKey>RSA_KEY_SIZE</configKey> <description><p> The NIST recommends the use of <u>2048 bits and higher</u> keys for the RSA algorithm. </p> <blockquote> "Digital Signature Verification | RSA: <code>1024 &le; len(n) &lt; 2048</code> | Legacy-use"<br/> "Digital Signature Verification | RSA: <code>len(n) &ge; 2048</code> | Acceptable"<br/> - <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths p.7</a> </blockquote> <p><b>Vulnerable Code:</b><br/> <pre> KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(512); </pre> </p> <p><b>Solution:</b><br/> The KeyPairGenerator creation should be as follows with at least 2048 bit key size.<br/> <pre> KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://csrc.nist.gov/projects/key-management">NIST: Latest publication on key management</a><br/> <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths p.7</a><br/> <a href="https://en.wikipedia.org/wiki/Key_size#Asymmetric%5Falgorithm%5Fkey%5Flengths">Wikipedia: Asymmetric algorithm key lengths</a><br/> <a href="https://cwe.mitre.org/data/definitions/326.html">CWE-326: Inadequate Encryption Strength</a><br/> <a href="https://www.keylength.com/en/compare/">Keylength.com (BlueKrypt): Aggregate key length recommendations.</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='UNVALIDATED_REDIRECT' priority='MAJOR'> <name>Security - Unvalidated Redirect</name> <configKey>UNVALIDATED_REDIRECT</configKey> <description><p> Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks. </p> <p> <b>Scenario</b><br/> 1. A user is tricked into visiting the malicious URL: <code>http://website.com/login?redirect=http://evil.vvebsite.com/fake/login</code><br/> 2. The user is redirected to a fake login page that looks like a site they trust. (<code>http://evil.vvebsite.com/fake/login</code>)<br/> 3. The user enters his credentials.<br/> 4. The evil site steals the user's credentials and redirects him to the original website.<br/> <br/> This attack is plausible because most users don't double check the URL after the redirection. Also, redirection to an authentication page is very common. </p> <p> <b>Vulnerable Code:</b></br/> <pre>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { [...] resp.sendRedirect(req.getParameter("redirectUrl")); [...] }</pre> </p> <p> <b>Solution/Countermeasures:</b><br/> <ul> <li>Don't accept redirection destinations from users</li> <li>Accept a destination key, and use it to look up the target (legal) destination</li> <li>Accept only relative paths</li> <li>White list URLs (if possible)</li> <li>Validate that the beginning of the URL is part of a white list</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246981/URL%20Redirector%20Abuse">WASC-38: URL Redirector Abuse</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards">OWASP: Top 10 2013-A10: Unvalidated Redirects and Forwards</a><br/> <a href="https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet">OWASP: Unvalidated Redirects and Forwards Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/601.html">CWE-601: URL Redirection to Untrusted Site ('Open Redirect')</a> </p></description> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='PLAY_UNVALIDATED_REDIRECT' priority='MAJOR'> <name>Security - Unvalidated Redirect (Play Framework)</name> <configKey>PLAY_UNVALIDATED_REDIRECT</configKey> <description><p> Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks. </p> <p> <b>Scenario</b><br/> 1. A user is tricked into visiting the malicious URL: <code>http://website.com/login?redirect=http://evil.vvebsite.com/fake/login</code><br/> 2. The user is redirected to a fake login page that looks like a site they trust. (<code>http://evil.vvebsite.com/fake/login</code>)<br/> 3. The user enters his credentials.<br/> 4. The evil site steals the user's credentials and redirects him to the original website.<br/> <br/> This attack is plausible because most users don't double check the URL after the redirection. Also, redirection to an authentication page is very common. </p> <p> <b>Vulnerable Code:</b></br/> <pre>def login(redirectUrl:String) = Action { [...] Redirect(url) }</pre> </p> <p> <b>Solution/Countermeasures:</b><br/> <ul> <li>Don't accept redirection destinations from users</li> <li>Accept a destination key, and use it to look up the target (legal) destination</li> <li>Accept only relative paths</li> <li>White list URLs (if possible)</li> <li>Validate that the beginning of the URL is part of a white list</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246981/URL%20Redirector%20Abuse">WASC-38: URL Redirector Abuse</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards">OWASP: Top 10 2013-A10: Unvalidated Redirects and Forwards</a><br/> <a href="https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet">OWASP: Unvalidated Redirects and Forwards Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/601.html">CWE-601: URL Redirection to Untrusted Site ('Open Redirect')</a> </p></description> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SPRING_UNVALIDATED_REDIRECT' priority='MAJOR'> <name>Security - Spring Unvalidated Redirect</name> <configKey>SPRING_UNVALIDATED_REDIRECT</configKey> <description><p> Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks. </p> <p> <b>Scenario</b><br/> 1. A user is tricked into visiting the malicious URL: <code>http://website.com/login?redirect=http://evil.vvebsite.com/fake/login</code><br/> 2. The user is redirected to a fake login page that looks like a site they trust. (<code>http://evil.vvebsite.com/fake/login</code>)<br/> 3. The user enters his credentials.<br/> 4. The evil site steals the user's credentials and redirects him to the original website.<br/> <br/> This attack is plausible because most users don't double check the URL after the redirection. Also, redirection to an authentication page is very common. </p> <p> <b>Vulnerable Code:</b></br/> <pre>@RequestMapping("/redirect") public String redirect(@RequestParam("url") String url) { [...] return "redirect:" + url; }</pre> </p> <p> <b>Solution/Countermeasures:</b><br/> <ul> <li>Don't accept redirection destinations from users</li> <li>Accept a destination key, and use it to look up the target (legal) destination</li> <li>Accept only relative paths</li> <li>White list URLs (if possible)</li> <li>Validate that the beginning of the URL is part of a white list</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246981/URL%20Redirector%20Abuse">WASC-38: URL Redirector Abuse</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards">OWASP: Top 10 2013-A10: Unvalidated Redirects and Forwards</a><br/> <a href="https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet">OWASP: Unvalidated Redirects and Forwards Cheat Sheet</a><br/> <a href="https://cwe.mitre.org/data/definitions/601.html">CWE-601: URL Redirection to Untrusted Site ('Open Redirect')</a> </p></description> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='ENTITY_LEAK' priority='MAJOR'> <name>Security - Unexpected property leak</name> <configKey>ENTITY_LEAK</configKey> <description><p> Persistent objects should never be returned by APIs. They might lead to leaking business logic over the UI, unauthorized tampering of persistent objects in database. </p> <p> <b>Vulnerable Code:</b></br/> <pre> @javax.persistence.Entity class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; } [...] @Controller class UserController { @GetMapping("/user/{id}") public UserEntity getUser(@PathVariable("id") String id) { return userService.findById(id).get(); //Return the user entity with ALL fields. } } </pre> </p> <p> <b>Solution/Countermeasures:</b><br/> <ul> <li>Data transfer objects should be used instead including only the parameters needed as input/response to/from the API.</li> <li>Sensitive parameters should be removed properly before transferring to UI.</li> <li>Data should be persisted in database only after proper sanitisation checks.</li> </ul> </p> <p> <b>Spring MVC Solution:</b><br/> In Spring specifically, you can apply the following solution to allow or disallow specific fields. <pre> @Controller class UserController { @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { binder.setAllowedFields(["username","firstname","lastname"]); } } </pre> </p> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure">OWASP Top 10-2017 A3: Sensitive Data Exposure</a><br/> <a href="https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html#spring-mvc">OWASP Cheat Sheet: Mass Assignment</a><br/> <a href="https://cwe.mitre.org/data/definitions/212.html">CWE-212: Improper Cross-boundary Removal of Sensitive Data</a><br/> <a href="https://cwe.mitre.org/data/definitions/213.html">CWE-213: Intentional Information Exposure</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='ENTITY_MASS_ASSIGNMENT' priority='MAJOR'> <name>Security - Mass assignment</name> <configKey>ENTITY_MASS_ASSIGNMENT</configKey> <description><p> Persistent objects should never be returned by APIs. They might lead to leaking business logic over the UI, unauthorized tampering of persistent objects in database. </p> <p> <b>Vulnerable Code:</b></br/> <pre> @javax.persistence.Entity class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private Long role; } [...] @Controller class UserController { @PutMapping("/user/") @ResponseStatus(value = HttpStatus.OK) public void update(UserEntity user) { userService.save(user); //ALL fields from the user can be altered } } </pre> </p> <p> <b>General Guidelines:</b><br/> <ul> <li>Data transfer objects should be used instead including only the parameters needed as input/response to/from the API.</li> <li>Sensitive parameters should be removed properly before transferring to UI.</li> <li>Data should be persisted in database only after proper sanitisation checks.</li> </ul> </p> <p> <b>Spring MVC Solution:</b><br/> In Spring specifically, you can apply the following solution to allow or disallow specific fields.<br/> <br/> With whitelist:<br/> <pre> @Controller class UserController { @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { binder.setAllowedFields(["username","password"]); } } </pre> <br/> With a blacklist:<br/> <pre> @Controller class UserController { @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { binder.setDisallowedFields(["role"]); } } </pre> </p> <p> <b>References</b><br/> <a href="https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html#spring-mvc">OWASP Cheat Sheet: Mass Assignment</a><br/> <a href="https://cwe.mitre.org/data/definitions/915.html">CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XSS_SERVLET' priority='MAJOR'> <name>Security - Potential XSS in Servlet</name> <configKey>XSS_SERVLET</configKey> <description><p> A potential XSS was found. It could be used to execute unwanted JavaScript in a client's browser. (See references) </p> <p> <b>Vulnerable Code:</b> <pre>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String input1 = req.getParameter("input1"); [...] resp.getWriter().write(input1); }</pre> </p> <p> <b>Solution:</b> <pre>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String input1 = req.getParameter("input1"); [...] resp.getWriter().write(Encode.forHtml(input1)); }</pre> </p> <p> The best defense against XSS is context sensitive output encoding like the example above. There are typically 4 contexts to consider: HTML, JavaScript, CSS (styles), and URLs. Please follow the XSS protection rules defined in the OWASP XSS Prevention Cheat Sheet, which explains these defenses in significant detail. </p> <p>Note that this XSS in Servlet rule looks for similar issues, but looks for them in a different way than the existing 'XSS: Servlet reflected cross site scripting vulnerability' and 'XSS: Servlet reflected cross site scripting vulnerability in error page' rules in FindBugs. </p> <br/> <p> <b>References</b><br/> <a href="http://projects.webappsec.org/w/page/13246920/Cross%20Site%20Scripting">WASC-8: Cross Site Scripting</a><br/> <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet">OWASP: XSS Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_%28XSS%29">OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)</a><br/> <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')</a><br/> <a href="https://code.google.com/p/owasp-java-encoder/">OWASP Java Encoder</a><br/> </p></description> <tag>owasp-a3</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='XML_DECODER' priority='CRITICAL'> <name>Security - XMLDecoder usage</name> <configKey>XML_DECODER</configKey> <description><p> XMLDecoder should not be used to parse untrusted data. Deserializing user input can lead to arbitrary code execution. This is possible because XMLDecoder supports arbitrary method invocation. This capability is intended to call setter methods, but in practice, any method can be called. </p> <p> <b>Malicious XML example:</b> </p> <pre> &lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;java version="1.4.0" class="java.beans.XMLDecoder"&gt; &lt;object class="java.io.PrintWriter"&gt; &lt;string>/tmp/Hacked.txt&lt;/string&gt; &lt;void method="println"&gt; &lt;string>Hello World!&lt;/string&gt; &lt;/void&gt; &lt;void method="close"/&gt; &lt;/object&gt; &lt;/java&gt; </pre> <p> The XML code above will cause the creation of a file with the content "Hello World!". </p> <p> <b>Vulnerable Code:</b></br/> <pre>XMLDecoder d = new XMLDecoder(in); try { Object result = d.readObject(); } [...]</pre> </p> <p> <b>Solution:</b></br/> The solution is to avoid using XMLDecoder to parse content from an untrusted source. </p> <br/> <p> <b>References</b><br/> <a href="http://blog.diniscruz.com/2013/08/using-xmldecoder-to-execute-server-side.html">Dinis Cruz Blog: Using XMLDecoder to execute server-side Java Code on a Restlet application</a><br/> <a href="https://securityblog.redhat.com/2014/01/23/java-deserialization-flaws-part-2-xml-deserialization/">RedHat blog : Java deserialization flaws: Part 2, XML deserialization</a><br/> <a href="https://cwe.mitre.org/data/definitions/20.html">CWE-20: Improper Input Validation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='STATIC_IV' priority='MAJOR'> <name>Security - Static IV</name> <configKey>STATIC_IV</configKey> <description><p> Initialization vector must be regenerated for each message to be encrypted. </p> <p><b>Vulnerable Code:</b></p> <p> <pre> private static byte[] IV = new byte[16] {(byte)0,(byte)1,(byte)2,[...]}; public void encrypt(String message) throws Exception { IvParameterSpec ivSpec = new IvParameterSpec(IV); [...] </pre> <p><b>Solution:</b></p> <p> <pre> public void encrypt(String message) throws Exception { byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); [...] </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://en.wikipedia.org/wiki/Initialization_vector">Wikipedia: Initialization vector</a><br/> <a href="https://cwe.mitre.org/data/definitions/329.html">CWE-329: Not Using a Random IV with CBC Mode</a><br/> <a href="https://defuse.ca/cbcmodeiv.htm">Encryption - CBC Mode IV: Secret or Not?</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='ECB_MODE' priority='MAJOR'> <name>Security - ECB mode is insecure</name> <configKey>ECB_MODE</configKey> <description><p>An authentication cipher mode which provides better confidentiality of the encrypted data should be used instead of Electronic Code Book (ECB) mode, which does not provide good confidentiality. Specifically, ECB mode produces the same output for the same input each time. So, for example, if a user is sending a password, the encrypted value is the same each time. This allows an attacker to intercept and replay the data.</p> <p> To fix this, something like Galois/Counter Mode (GCM) should be used instead. </p> <p> <b>Code at risk:</b> <pre>Cipher c = Cipher.getInstance("AES/ECB/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Solution:</b> <pre>Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">Wikipedia: Authenticated encryption</a><br/> <a href="https://csrc.nist.gov/projects/block-cipher-techniques/bcm/modes-develoment#01">NIST: Authenticated Encryption Modes</a><br/> <a href="https://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29">Wikipedia: Block cipher modes of operation</a><br/> <a href="https://csrc.nist.gov/publications/detail/sp/800-38a/final">NIST: Recommendation for Block Cipher Modes of Operation</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>security</tag> </rule> <rule key='PADDING_ORACLE' priority='MAJOR'> <name>Security - Cipher is susceptible to Padding Oracle</name> <configKey>PADDING_ORACLE</configKey> <description><p> This specific mode of CBC with PKCS5Padding is susceptible to padding oracle attacks. An adversary could potentially decrypt the message if the system exposed the difference between plaintext with invalid padding or valid padding. The distinction between valid and invalid padding is usually revealed through distinct error messages being returned for each condition. </p> <p> <b>Code at risk:</b> <pre>Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Solution:</b> <pre>Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <br/> <p> <b>References</b><br/> <a href="http://www.infobytesec.com/down/paddingoracle_openjam.pdf">Padding Oracles for the masses (by Matias Soler)</a><br/> <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">Wikipedia: Authenticated encryption</a><br/> <a href="https://csrc.nist.gov/projects/block-cipher-techniques/bcm/modes-develoment#01">NIST: Authenticated Encryption Modes</a><br/> <a href="https://capec.mitre.org/data/definitions/463.html">CAPEC: Padding Oracle Crypto Attack</a><br/> <a href="https://cwe.mitre.org/data/definitions/696.html">CWE-696: Incorrect Behavior Order</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='CIPHER_INTEGRITY' priority='MAJOR'> <name>Security - Cipher with no integrity</name> <configKey>CIPHER_INTEGRITY</configKey> <description><p> The ciphertext produced is susceptible to alteration by an adversary. This mean that the cipher provides no way to detect that the data has been tampered with. If the ciphertext can be controlled by an attacker, it could be altered without detection. </p> <p> The solution is to use a cipher that includes a Hash based Message Authentication Code (HMAC) to sign the data. Combining a HMAC function to the existing cipher is prone to error <sup><a href="https://moxie.org/blog/the-cryptographic-doom-principle/">[1]</a></sup>. Specifically, it is always recommended that you be able to verify the HMAC first, and only if the data is unmodified, do you then perform any cryptographic functions on the data. </p> <p>The following modes are vulnerable because they don't provide a HMAC:<br/> - CBC<br/> - OFB<br/> - CTR<br/> - ECB<br/><br/> The following snippets code are some examples of vulnerable code.<br/><br/> <b>Code at risk:</b><br/> <i>AES in CBC mode</i><br/> <pre>Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> <br/> <i>Triple DES with ECB mode</i><br/> <pre>Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> <b>Solution:</b> <pre>Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); c.init(Cipher.ENCRYPT_MODE, k, iv); byte[] cipherText = c.doFinal(plainText);</pre> </p> <p> In the example solution above, the GCM mode introduces an HMAC into the resulting encrypted data, providing integrity of the result. </p> <br/> <p> <b>References</b><br/> <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">Wikipedia: Authenticated encryption</a><br/> <a href="https://csrc.nist.gov/projects/block-cipher-techniques/bcm/modes-develoment#01">NIST: Authenticated Encryption Modes</a><br/> <a href="https://moxie.org/blog/the-cryptographic-doom-principle/">Moxie Marlinspike's blog: The Cryptographic Doom Principle</a><br/> <a href="https://cwe.mitre.org/data/definitions/353.html">CWE-353: Missing Support for Integrity Check</a> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='ESAPI_ENCRYPTOR' priority='INFO'> <name>Security - Use of ESAPI Encryptor</name> <configKey>ESAPI_ENCRYPTOR</configKey> <description><p> The ESAPI has a small history of vulnerabilities within the cryptography component. Here is a quick validation list to make sure the Authenticated Encryption is working as expected. </p> <p><b>1. Library Version</b></p> <p> This issue is corrected in ESAPI version 2.1.0. Versions <= 2.0.1 are vulnerable to a MAC bypass (CVE-2013-5679).<br/> </p> <p> For Maven users, the plugin <a href="https://www.mojohaus.org/versions-maven-plugin/">versions</a> can be called using the following command. The effective version of ESAPI will be available in the output.<br/> <pre>$ mvn versions:display-dependency-updates</pre> <br/>Output:<br/> <pre> [...] [INFO] The following dependencies in Dependencies have newer versions: [INFO] org.slf4j:slf4j-api ................................... 1.6.4 -> 1.7.7 [INFO] org.owasp.esapi:esapi ................................. 2.0.1 -> 2.1.0 [...] </pre> </p> <p> or by looking at the configuration directly.<br/> <pre> &lt;dependency&gt; &lt;groupId&gt;org.owasp.esapi&lt;/groupId&gt; &lt;artifactId&gt;esapi&lt;/artifactId&gt; &lt;version&gt;2.1.0&lt;/version&gt; &lt;/dependency&gt;</pre> </p> <p> For Ant users, the jar used should be <a href="https://repo1.maven.org/maven2/org/owasp/esapi/esapi/2.1.0/esapi-2.1.0.jar">esapi-2.1.0.jar</a>. </p> <p><b>2. Configuration:</b></p> <p> The library version 2.1.0 is still vulnerable to key size being changed in the ciphertext definition (CVE-2013-5960). Some precautions need to be taken.<br/> <br/> <div><b>The cryptographic configuration of ESAPI can also be vulnerable if any of these elements are present:</b><br/> <b>Insecure configuration:</b><br/> <pre> Encryptor.CipherText.useMAC=false Encryptor.EncryptionAlgorithm=AES Encryptor.CipherTransformation=AES/CBC/PKCS5Padding Encryptor.cipher_modes.additional_allowed=CBC</pre> </div> </p> <p> <div> <b>Secure configuration:</b><br/> <pre> #Needed Encryptor.CipherText.useMAC=true #Needed to have a solid auth. encryption Encryptor.EncryptionAlgorithm=AES Encryptor.CipherTransformation=AES/GCM/NoPadding #CBC mode should be removed to avoid padding oracle Encryptor.cipher_modes.additional_allowed=</pre> </div> </p> <br/> <p> <b>References</b><br/> <a href="https://github.com/peval/owasp-esapi-java/blob/master/documentation/ESAPI-security-bulletin1.pdf">ESAPI Security bulletin 1 (CVE-2013-5679)</a><br/> <a href="https://nvd.nist.gov/vuln/detail/CVE-2013-5679">Vulnerability Summary for CVE-2013-5679</a><br/> <a href="https://www.synacktiv.com/ressources/synacktiv_owasp_esapi_hmac_bypass.pdf">Synactiv: Bypassing HMAC validation in OWASP ESAPI symmetric encryption</a><br/> <a href="https://cwe.mitre.org/data/definitions/310.html">CWE-310: Cryptographic Issues</a><br/> <a href="https://lists.owasp.org/pipermail/esapi-dev/2015-March/002533">ESAPI-dev mailing list: Status of CVE-2013-5960</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='ANDROID_EXTERNAL_FILE_ACCESS' priority='MAJOR'> <name>Security - External file access (Android)</name> <configKey>ANDROID_EXTERNAL_FILE_ACCESS</configKey> <description><p> The application write data to external storage (potentially SD card). There are multiple security implication to this action. First, file store on SD card will be accessible to the application having the <a href="https://developer.android.com/reference/android/Manifest.permission.html#READ_EXTERNAL_STORAGE"><code>READ_EXTERNAL_STORAGE</code></a> permission. Also, if the data persisted contains confidential information about the user, encryption would be needed. </p> <p> <b>Code at risk:</b><br/> <pre> file file = new File(getExternalFilesDir(TARGET_TYPE), filename); fos = new FileOutputStream(file); fos.write(confidentialData.getBytes()); fos.flush(); </pre> </p> <p> <b>Better alternative:</b><br/> <pre> fos = openFileOutput(filename, Context.MODE_PRIVATE); fos.write(string.getBytes()); </pre> </p> <br/> <p> <b>References</b><br/> <a href="http://developer.android.com/training/articles/security-tips.html#ExternalStorage">Android Official Doc: Security Tips</a><br/> <a href="https://www.securecoding.cert.org/confluence/display/java/DRD00-J.+Do+not+store+sensitive+information+on+external+storage+%28SD+card%29+unless+encrypted+first">CERT: DRD00-J: Do not store sensitive information on external storage [...]</a><br/> <a href="https://developer.android.com/guide/topics/data/data-storage.html#filesExternal">Android Official Doc: Using the External Storage</a><br/> <a href="https://www.owasp.org/index.php/Mobile_Top_10_2014-M2">OWASP Mobile Top 10 2014-M2: Insecure Data Storage</a><br/> <a href="https://cwe.mitre.org/data/definitions/312.html">CWE-312: Cleartext Storage of Sensitive Information</a> </p></description> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='ANDROID_BROADCAST' priority='INFO'> <name>Security - Broadcast (Android)</name> <configKey>ANDROID_BROADCAST</configKey> <description><p> Broadcast intents can be listened by any application with the appropriate permission. It is suggested to avoid transmitting sensitive information when possible. </p> <p> <b>Code at risk:</b><br/> <pre> Intent i = new Intent(); i.setAction("com.insecure.action.UserConnected"); i.putExtra("username", user); i.putExtra("email", email); i.putExtra("session", newSessionId); this.sendBroadcast(v1); </pre> </p> <br/> <p> <b>Solution (if possible):</b><br/> <pre> Intent i = new Intent(); i.setAction("com.secure.action.UserConnected"); sendBroadcast(v1); </pre> </p> <br/> <p> <b>Configuration (receiver)<sup>[1] Source: StackOverflow</sup>:</b><br/> <pre> &lt;manifest ...&gt; &lt;!-- Permission declaration --&gt; &lt;permission android:name="my.app.PERMISSION" /&gt; &lt;receiver android:name="my.app.BroadcastReceiver" android:permission="my.app.PERMISSION"&gt; &lt;!-- Permission enforcement --&gt; &lt;intent-filter> &lt;action android:name="com.secure.action.UserConnected" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; ... &lt;/manifest> </pre> </p> <p> <b>Configuration (sender)<sup>[1] Source: StackOverflow</sup>:</b><br/> <pre> &lt;manifest&gt; &lt;!-- We declare we own the permission to send broadcast to the above receiver --&gt; &lt;uses-permission android:name="my.app.PERMISSION"/&gt; &lt;!-- With the following configuration, both the sender and the receiver apps need to be signed by the same developer certificate. --&gt; &lt;permission android:name="my.app.PERMISSION" android:protectionLevel="signature"/&gt; &lt;/manifest&gt; </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.securecoding.cert.org/confluence/display/java/DRD03-J.+Do+not+broadcast+sensitive+information+using+an+implicit+intent">CERT: DRD03-J. Do not broadcast sensitive information using an implicit intent</a><br/> <a href="https://developer.android.com/reference/android/content/BroadcastReceiver.html#Security">Android Official Doc: BroadcastReceiver (Security)</a><br/> <a href="https://developer.android.com/guide/topics/manifest/receiver-element.html">Android Official Doc: Receiver configuration (see <code>android:permission</code>)</a><br/> <sup>[1]</sup> <a href="https://stackoverflow.com/a/21513368/89769">StackOverflow: How to set permissions in broadcast sender and receiver in android</a><br/> <a href="https://cwe.mitre.org/data/definitions/925.html">CWE-925: Improper Verification of Intent by Broadcast Receiver</a><br/> <a href="https://cwe.mitre.org/data/definitions/927.html">CWE-927: Use of Implicit Intent for Sensitive Communication</a> </p></description> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='ANDROID_WORLD_WRITABLE' priority='MAJOR'> <name>Security - World writable file (Android)</name> <configKey>ANDROID_WORLD_WRITABLE</configKey> <description><p> The file written in this context is using the creation mode <code>MODE_WORLD_READABLE</code>. It might not be the expected behavior to expose the content being written. </p> <p> <b>Code at risk:</b><br/> <pre> fos = openFileOutput(filename, MODE_WORLD_READABLE); fos.write(userInfo.getBytes()); </pre> </p> <br/> <p> <b>Solution (using MODE_PRIVATE):</b><br/> <pre> fos = openFileOutput(filename, MODE_PRIVATE); </pre> </p> <p> <b>Solution (using local SQLite Database):</b><br/> Using a local SQLite database is probably the best solution to store structured data. Make sure the database file is not create on external storage. See references below for implementation guidelines. </p> <br/> <p> <b>References</b><br/> <a href="https://www.securecoding.cert.org/confluence/display/java/DRD11-J.+Ensure+that+sensitive+data+is+kept+secure">CERT: DRD11-J. Ensure that sensitive data is kept secure</a><br/> <a href="https://developer.android.com/training/articles/security-tips.html#InternalStorage">Android Official Doc: Security Tips</a><br/> <a href="https://developer.android.com/reference/android/content/Context.html#MODE_PRIVATE">Android Official Doc: Context.MODE_PRIVATE</a><br/> <a href="https://www.vogella.com/tutorials/AndroidSQLite/article.html#databasetutorial_database">vogella.com: Android SQLite database and content provider - Tutorial</a><br/> <a href="https://www.vogella.com/tutorials/AndroidSQLite/article.html#databasetutorial_database">vogella.com: Android SQLite database and content provider - Tutorial</a><br/> <a href="https://www.owasp.org/index.php/Mobile_Top_10_2014-M2">OWASP Mobile Top 10 2014-M2: Insecure Data Storage</a><br/> <a href="https://cwe.mitre.org/data/definitions/312.html">CWE-312: Cleartext Storage of Sensitive Information</a> </p></description> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='ANDROID_GEOLOCATION' priority='INFO'> <name>Security - WebView with geolocation activated (Android)</name> <configKey>ANDROID_GEOLOCATION</configKey> <description><p> It is suggested to ask the user for a confirmation about obtaining its geolocation. </p> <p> <b>Code at risk:</b><br/> <pre> webView.setWebChromeClient(new WebChromeClient() { @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } }); </pre> </p> <p> <b>Suggested code:</b><br/> Limit the sampling of geolocation and ask the user for confirmation. <pre> webView.setWebChromeClient(new WebChromeClient() { @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); //Ask the user for confirmation } }); </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.securecoding.cert.org/confluence/display/java/DRD15-J.+Consider+privacy+concerns+when+using+Geolocation+API">CERT: DRD15-J. Consider privacy concerns when using Geolocation API</a><br/> <a href="https://en.wikipedia.org/wiki/W3C_Geolocation_API">Wikipedia: W3C Geolocation API</a><br/> <a href="https://w3c.github.io/geolocation-api/">W3C: Geolocation Specification</a><br/> </p></description> <tag>android</tag> <tag>security</tag> </rule> <rule key='ANDROID_WEB_VIEW_JAVASCRIPT' priority='INFO'> <name>Security - WebView with JavaScript enabled (Android)</name> <configKey>ANDROID_WEB_VIEW_JAVASCRIPT</configKey> <description><p> Enabling JavaScript for the WebView means that it is now susceptible to XSS. The page render should be inspected for potential reflected XSS, stored XSS and DOM XSS.<br/> <pre> WebView myWebView = (WebView) findViewById(R.id.webView); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); </pre> </p> <p> <b>Code at risk:</b><br/> Enabling JavaScript is not a bad practice. It just means that the backend code need to be audited for potential XSS. The XSS can also be introduced client-side with DOM XSS. <pre> function updateDescription(newDescription) { $("#userDescription").html("&lt;p&gt;"+newDescription+"&lt;/p&gt;"); } </pre> </p> <br/> <p> <b>References</b><br/> <a href="http://www.technotalkative.com/issue-using-setjavascriptenabled-can-introduce-xss-vulnerabilities-application-review-carefully/">Issue: Using <code>setJavaScriptEnabled</code> can introduce XSS vulnerabilities</a><br/> <a href="https://developer.android.com/guide/webapps/webview.html#UsingJavaScript">Android Official Doc: WebView</a><br/> <a href="http://projects.webappsec.org/w/page/13246920/Cross%20Site%20Scripting">WASC-8: Cross Site Scripting</a><br/> <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet">OWASP: XSS Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_%28XSS%29">OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)</a><br/> <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')</a> </p></description> <tag>owasp-a3</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='ANDROID_WEB_VIEW_JAVASCRIPT_INTERFACE' priority='INFO'> <name>Security - WebView with JavaScript interface (Android)</name> <configKey>ANDROID_WEB_VIEW_JAVASCRIPT_INTERFACE</configKey> <description><p> The use of JavaScript Interface could expose the WebView to risky API. If an XSS is triggered in the WebView, the class could be called by the malicious JavaScript code. </p> <p> <b>Code at risk:</b><br/> <pre> WebView myWebView = (WebView) findViewById(R.id.webView); myWebView.addJavascriptInterface(new FileWriteUtil(this), "fileWriteUtil"); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); [...] class FileWriteUtil { Context mContext; FileOpenUtil(Context c) { mContext = c; } public void writeToFile(String data, String filename, String tag) { [...] } } </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface%28java.lang.Object,%20java.lang.String%29">Android Official Doc: <code>WebView.addJavascriptInterface()</code></a><br/> <a href="https://cwe.mitre.org/data/definitions/749.html">CWE-749: Exposed Dangerous Method or Function</a> </p></description> <tag>cwe</tag> <tag>android</tag> <tag>security</tag> </rule> <rule key='INSECURE_COOKIE' priority='MAJOR'> <name>Security - Cookie without the secure flag</name> <configKey>INSECURE_COOKIE</configKey> <description><p> A new cookie is created without the <code>Secure</code> flag set. The <code>Secure</code> flag is a directive to the browser to make sure that the cookie is not sent for insecure communication (<code>http://</code>). </p> <p> <b>Code at risk:</b><br/> <pre> Cookie cookie = new Cookie("userName",userName); response.addCookie(cookie); </pre> </p> <p> <b>Solution (Specific configuration):</b><br/> <pre> Cookie cookie = new Cookie("userName",userName); cookie.setSecure(true); // Secure flag cookie.setHttpOnly(true); </pre> </p> <p> <b>Solution (Servlet 3.0 configuration):</b><br/> <pre> &lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0"&gt; [...] &lt;session-config&gt; &lt;cookie-config&gt; &lt;http-only&gt;true&lt;/http-only&gt; &lt;secure&gt;true&lt;/secure&gt; &lt;/cookie-config&gt; &lt;/session-config&gt; &lt;/web-app&gt; </pre> </p> <br/> <p> <b>Reference</b><br/> <a href="https://cwe.mitre.org/data/definitions/614.html">CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute</a><br/> <a href="https://cwe.mitre.org/data/definitions/315.html">CWE-315: Cleartext Storage of Sensitive Information in a Cookie</a><br/> <a href="https://cwe.mitre.org/data/definitions/311.html">CWE-311: Missing Encryption of Sensitive Data</a><br/> <a href="https://www.owasp.org/index.php/SecureFlag">OWASP: Secure Flag</a><br/> <a href="https://www.rapid7.com/db/vulnerabilities/http-cookie-secure-flag">Rapid7: Missing Secure Flag From SSL Cookie</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='HTTPONLY_COOKIE' priority='MAJOR'> <name>Security - Cookie without the HttpOnly flag</name> <configKey>HTTPONLY_COOKIE</configKey> <description><p> A new cookie is created without the <code>HttpOnly</code> flag set. The <code>HttpOnly</code> flag is a directive to the browser to make sure that the cookie can not be red by malicious script. When a user is the target of a "Cross-Site Scripting", the attacker would benefit greatly from getting the session id for example. </p> <p> <b>Code at risk:</b><br/> <pre> Cookie cookie = new Cookie("email",userName); response.addCookie(cookie); </pre> </p> <p> <b>Solution (Specific configuration):</b><br/> <pre> Cookie cookie = new Cookie("email",userName); cookie.setSecure(true); cookie.setHttpOnly(true); //HttpOnly flag </pre> </p> <p> <b>Solution (Servlet 3.0 configuration):</b><br/> <pre> &lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0"&gt; [...] &lt;session-config&gt; &lt;cookie-config&gt; &lt;http-only&gt;true&lt;/http-only&gt; &lt;secure&gt;true&lt;/secure&gt; &lt;/cookie-config&gt; &lt;/session-config&gt; &lt;/web-app&gt; </pre> </p> <br/> <p> <b>Reference</b><br/> <a href="https://blog.codinghorror.com/protecting-your-cookies-httponly/">Coding Horror blog: Protecting Your Cookies: HttpOnly</a><br/> <a href="https://www.owasp.org/index.php/HttpOnly">OWASP: HttpOnly</a><br/> <a href="https://www.rapid7.com/db/vulnerabilities/http-cookie-http-only-flag">Rapid7: Missing HttpOnly Flag From Cookie</a> </p></description> <tag>security</tag> </rule> <rule key='OBJECT_DESERIALIZATION' priority='CRITICAL'> <name>Security - Object deserialization is used in {1}</name> <configKey>OBJECT_DESERIALIZATION</configKey> <description><p> Object deserialization of untrusted data can lead to remote code execution, if there is a class in classpath that allows the trigger of malicious operation. </p> <p> Libraries developers tend to fix class that provided potential malicious trigger. There are still classes that are known to trigger Denial of Service<sup>[1]</sup>. </p> <p> Deserialization is a sensible operation that has a great history of vulnerabilities. The web application might become vulnerable as soon as a new vulnerability is found in the Java Virtual Machine<sup>[2] [3]</sup>. </p> <p> <b>Code at risk:</b><br/> <pre> public UserData deserializeObject(InputStream receivedFile) throws IOException, ClassNotFoundException { try (ObjectInputStream in = new ObjectInputStream(receivedFile)) { return (UserData) in.readObject(); } } </pre> </p> <p> <b>Solutions:</b><br/> <p> Avoid deserializing object provided by remote users. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/502.html">CWE-502: Deserialization of Untrusted Data</a><br/> <a href="https://www.owasp.org/index.php/Deserialization_of_untrusted_data">Deserialization of untrusted data</a><br/> <a href="https://www.oracle.com/technetwork/java/seccodeguide-139067.html#8">Serialization and Deserialization </a><br/> <a href="https://github.com/frohoff/ysoserial">A tool for generating payloads that exploit unsafe Java object deserialization</a><br/> [1] <a href="https://gist.github.com/coekie/a27cc406fc9f3dc7a70d">Example of Denial of Service using the class <code>java.util.HashSet</code></a><br/> [2] <a href="https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2015-2590">OpenJDK: Deserialization issue in ObjectInputStream.readSerialData() (CVE-2015-2590)</a><br/> [3] <a href="https://www.rapid7.com/db/modules/exploit/multi/browser/java_calendar_deserialize">Rapid7: Sun Java Calendar Deserialization Privilege Escalation (CVE-2008-5353)</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='JACKSON_UNSAFE_DESERIALIZATION' priority='CRITICAL'> <name>Security - Unsafe Jackson deserialization configuration</name> <configKey>JACKSON_UNSAFE_DESERIALIZATION</configKey> <description><p>When the Jackson databind library is used incorrectly the deserialization of untrusted data can lead to remote code execution, if there is a class in classpath that allows the trigger of malicious operation. <p> <b>Solutions:</b><br/> <p> Explicitly define what types and subtypes you want to be available when using polymorphism through JsonTypeInfo.Id.NAME. Also, never call <code>ObjectMapper.enableDefaultTyping</code> (and then <code>readValue</code> a type that holds a Object or Serializable or Comparable or a known deserialization type). </p> <p> <b>Code at risk:</b><br/> <pre> public class Example { static class ABean { public int id; public Object obj; } static class AnotherBean { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) // or JsonTypeInfo.Id.MINIMAL_CLASS public Object obj; } public void example(String json) throws JsonMappingException { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); mapper.readValue(json, ABean.class); } public void exampleTwo(String json) throws JsonMappingException { ObjectMapper mapper = new ObjectMapper(); mapper.readValue(json, AnotherBean.class); } } </pre> </p> <p> <b>References</b><br/> <a href="https://github.com/FasterXML/jackson-databind/issues/1599">Jackson Deserializer security vulnerability</a><br> <a href="https://github.com/mbechler/marshalsec">Java Unmarshaller Security - Turning your data into code execution</a><br> </p></description> <tag>security</tag> </rule> <rule key='DESERIALIZATION_GADGET' priority='INFO'> <name>Security - This class could be used as deserialization gadget</name> <configKey>DESERIALIZATION_GADGET</configKey> <description><p> Deserialization gadget are class that could be used by an attacker to take advantage of a remote API using Native Serialization. This class is either adding custom behavior to deserialization with the <code>readObject</code> method (Serializable) or can be called from a serialized object (InvocationHandler). </p> <p> This detector is intended to be used mostly by researcher. The real issue is using deserialization for remote operation. Removing gadget is a hardening practice to reduce the risk of being exploited. </p> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/502.html">CWE-502: Deserialization of Untrusted Data</a><br/> <a href="https://www.owasp.org/index.php/Deserialization_of_untrusted_data">Deserialization of untrusted data</a><br/> <a href="https://www.oracle.com/technetwork/java/seccodeguide-139067.html#8">Serialization and Deserialization </a><br/> <a href="https://github.com/frohoff/ysoserial">A tool for generating payloads that exploit unsafe Java object deserialization</a><br/> [1] <a href="https://gist.github.com/coekie/a27cc406fc9f3dc7a70d">Example of Denial of Service using the class <code>java.util.HashSet</code></a><br/> [2] <a href="https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2015-2590">OpenJDK: Deserialization issue in ObjectInputStream.readSerialData() (CVE-2015-2590)</a><br/> [3] <a href="https://www.rapid7.com/db/modules/exploit/multi/browser/java_calendar_deserialize">Rapid7: Sun Java Calendar Deserialization Privilege Escalation (CVE-2008-5353)</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='TRUST_BOUNDARY_VIOLATION' priority='MAJOR'> <name>Security - Trust Boundary Violation</name> <configKey>TRUST_BOUNDARY_VIOLATION</configKey> <description><p> "A trust boundary can be thought of as line drawn through a program. On one side of the line, data is untrusted. On the other side of the line, data is assumed to be trustworthy. The purpose of validation logic is to allow data to safely cross the trust boundary - to move from untrusted to trusted. A trust boundary violation occurs when a program blurs the line between what is trusted and what is untrusted. By combining trusted and untrusted data in the same data structure, it becomes easier for programmers to mistakenly trust unvalidated data." <sup>[1]</sup> </p> <p> <b>Code at risk:</b><br/> <pre> public void doSomething(HttpServletRequest req, String activateProperty) { //.. req.getSession().setAttribute(activateProperty,"true"); } </pre> <br/> <pre> public void loginEvent(HttpServletRequest req, String userSubmitted) { //.. req.getSession().setAttribute("user",userSubmitted); } </pre> </p> <p> <b>Solution:</b><br/> <p> The solution would be to add validation prior setting a new session attribute. When possible, prefer data from safe location rather than using direct user input. </p> <br/> <p> <b>References</b><br/> [1] <a href="https://cwe.mitre.org/data/definitions/501.html">CWE-501: Trust Boundary Violation</a><br/> <a href="https://www.owasp.org/index.php/Trust_Boundary_Violation">OWASP : Trust Boundary Violation</a> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='MALICIOUS_XSLT' priority='CRITICAL'> <name>Security - A malicious XSLT could be provided</name> <configKey>MALICIOUS_XSLT</configKey> <description><p> "XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other XML documents".<sup>[1]</sup><br/> It is possible to attach malicious behavior to those style sheets. Therefore, if an attacker can control the content or the source of the style sheet, he might be able to trigger remote code execution.<sup>[2]</sup> </p> <p> <b>Code at risk:</b><br/> <pre> Source xslt = new StreamSource(new FileInputStream(inputUserFile)); //Dangerous source Transformer transformer = TransformerFactory.newInstance().newTransformer(xslt); Source text = new StreamSource(new FileInputStream("/data_2_process.xml")); transformer.transform(text, new StreamResult(...)); </pre> </p> <p> <b>Solution:</b><br/> <p>The solution is to enable the secure processing mode which will block potential reference to Java classes such as <code>java.lang.Runtime</code>.</p> <pre> TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Source xslt = new StreamSource(new FileInputStream(inputUserFile)); Transformer transformer = factory.newTransformer(xslt); </pre> <p> Alternatively, make sure the style sheet is loaded from a safe sources and make sure that vulnerabilities such as Path traversal <sup>[3][4]</sup> are not possible. </p> <p> <b>References</b><br/> [1] <a href="https://en.wikipedia.org/wiki/XSLT">Wikipedia: XSLT (Extensible Stylesheet Language Transformations)</a><br/> <a href="https://prezi.com/y_fuybfudgnd/offensive-xslt/">Offensive XSLT</a> by Nicolas Grégoire<br/> [2] <a href="https://www.agarri.fr/blog/archives/2012/07/02/from_xslt_code_execution_to_meterpreter_shells/index.html">From XSLT code execution to Meterpreter shells</a> by Nicolas Grégoire<br/> <a href="https://xhe.myxwiki.org/xwiki/bin/view/Main/">XSLT Hacking Encyclopedia</a> by Nicolas Grégoire<br/> <a href="https://www.acunetix.com/blog/articles/the-hidden-dangers-of-xsltprocessor-remote-xsl-injection/">Acunetix.com : The hidden dangers of XSLTProcessor - Remote XSL injection</a><br/> <a href="https://www.w3.org/TR/xslt">w3.org XSL Transformations (XSLT) Version 1.0</a> : w3c specification<br/> [3] <a href="http://projects.webappsec.org/w/page/13246952/Path%20Traversal">WASC: Path Traversal</a><br/> [4] <a href="https://www.owasp.org/index.php/Path_Traversal">OWASP: Path Traversal</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>owasp-a4</tag> <tag>wasc</tag> <tag>security</tag> </rule> <rule key='URLCONNECTION_SSRF_FD' priority='MAJOR'> <name>Security - URLConnection Server-Side Request Forgery (SSRF) and File Disclosure</name> <configKey>URLCONNECTION_SSRF_FD</configKey> <description><p> Server-Side Request Forgery occur when a web server executes a request to a user supplied destination parameter that is not validated. Such vulnerabilities could allow an attacker to access internal services or to launch attacks from your web server. </p> <p> URLConnection can be used with file:// protocol or other protocols to access local filesystem and potentially other services. <p> <b>Vulnerable Code:</b> <pre> new URL(String url).openConnection() </pre> <pre> new URL(String url).openStream() </pre> <pre> new URL(String url).getContent() </pre> </p> <p> <b>Solution/Countermeasures:</b><br/> <ul> <li>Don't accept URL destinations from users</li> <li>Accept a destination key, and use it to look up the target destination associate with the key</li> <li>White list URLs (if possible)</li> <li>Validate that the beginning of the URL is part of a white list</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/918.html">CWE-918: Server-Side Request Forgery (SSRF)</a><br/> <a href="https://www.bishopfox.com/blog/2015/04/vulnerable-by-design-understanding-server-side-request-forgery/">Understanding Server-Side Request Forgery</a><br/> <a href="https://cwe.mitre.org/data/definitions/73.html">CWE-73: External Control of File Name or Path</a><br/> <a href="https://www.pwntester.com/blog/2013/11/28/abusing-jar-downloads/">Abusing jar:// downloads</a><br /> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='TEMPLATE_INJECTION_VELOCITY' priority='CRITICAL'> <name>Security - Potential template injection with Velocity</name> <configKey>TEMPLATE_INJECTION_VELOCITY</configKey> <description><p> Velocity template engine is powerful. It is possible to add logic including condition statements, loops and external calls. It is not designed to be a sandbox to templating operations. A malicious user in control of a template can run malicious code on the server-side. Velocity templates should be seen as scripts. </p> <p> <b>Vulnerable Code:</b> <pre>[...] Velocity.evaluate(context, swOut, "test", userInput);</pre> </p> <p> <b>Solution:</b> <br/> Avoid letting end users manipulate templates with Velocity. If you need to expose template editing to your users, prefer logic-less template engines such as Handlebars or Moustache (See references). </p> <br/> <p> <b>References</b><br/> <a href="https://blog.portswigger.net/2015/08/server-side-template-injection.html">PortSwigger: Server-Side Template Injection </a><br/> <a href="https://jknack.github.io/handlebars.java/">Handlebars.java</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>security</tag> </rule> <rule key='TEMPLATE_INJECTION_FREEMARKER' priority='CRITICAL'> <name>Security - Potential template injection with Freemarker</name> <configKey>TEMPLATE_INJECTION_FREEMARKER</configKey> <description><p> Freemarker template engine is powerful. It is possible to add logic including condition statements, loops and external calls. It is not design to be sandbox to templating operations. A malicious user in control of a template can run malicious code on the server-side. Freemarker templates should be seen as scripts. </p> <p> <b>Vulnerable Code:</b> <pre>Template template = cfg.getTemplate(inputTemplate); [...] template.process(data, swOut);</pre> </p> <p> <b>Solution:</b> <br/> Avoid letting end users manipulate templates with Freemarker. If you need to expose template editing to your users, prefer logic-less template engines such as Handlebars or Moustache (See references). </p> <br/> <p> <b>References</b><br/> <a href="https://portswigger.net/research/server-side-template-injection">PortSwigger: Server-Side Template Injection</a><br/> <a href="https://jknack.github.io/handlebars.java/">Handlebars.java</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>security</tag> </rule> <rule key='TEMPLATE_INJECTION_PEBBLE' priority='CRITICAL'> <name>Security - Potential template injection with Pebble</name> <configKey>TEMPLATE_INJECTION_PEBBLE</configKey> <description><p> Pebble template engine is powerful. It is possible to add logic including condition statements, loops and external calls. It is not design to be sandbox to templating operations. A malicious user in control of a template can run malicious code on the server-side. Pebble templates should be seen as scripts. </p> <p> <b>Vulnerable Code:</b> <pre>PebbleTemplate compiledTemplate = engine.getLiteralTemplate(inputFile); [...] compiledTemplate.evaluate(writer, context);</pre> </p> <p> <b>Solution:</b> <br/> Avoid letting end users manipulate templates with Pebble. If you need to expose template editing to your users, prefer logic-less template engines such as Handlebars or Moustache (See references). </p> <br/> <p> <b>References</b><br/> <a href="https://research.securitum.com/server-side-template-injection-on-the-example-of-pebble/">Server Side Template Injection – on the example of Pebble</a> by Michał Bentkowski<br/> <a href="https://portswigger.net/research/server-side-template-injection">PortSwigger: Server-Side Template Injection</a><br/> <a href="https://jknack.github.io/handlebars.java/">Handlebars.java</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>security</tag> </rule> <rule key='PERMISSIVE_CORS' priority='MAJOR'> <name>Security - Overly permissive CORS policy</name> <configKey>PERMISSIVE_CORS</configKey> <description><p> Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for JavaScript to access the contents of a Web page, both the JavaScript and the Web page must originate from the same domain. Without the Same Origin Policy, a malicious website could serve up JavaScript that loads sensitive information from other websites using a client's credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible for JavaScript to access data across domains if a new HTTP header called Access-Control-Allow-Origin is defined. With this header, a Web server defines which other domains are allowed to access its domain using cross-origin requests. However, caution should be taken when defining the header because an overly permissive CORS policy will allow a malicious application to communicate with the victim application in an inappropriate way, leading to spoofing, data theft, relay and other attacks. </p> <p> <b>Vulnerable Code:</b> <pre>response.addHeader("Access-Control-Allow-Origin", "*");</pre> </p> <p> <b>Solution:</b> <br/> Avoid using * as the value of the Access-Control-Allow-Origin header, which indicates that the application's data is accessible to JavaScript running on any domain. </p> <br/> <p> <b>References</b><br/> <a href="https://www.w3.org/TR/cors/">W3C Cross-Origin Resource Sharing</a><br/> <a href="https://enable-cors.org/">Enable Cross-Origin Resource Sharing</a><br/> </p></description> <tag>security</tag> </rule> <rule key='LDAP_ANONYMOUS' priority='MAJOR'> <name>Security - Anonymous LDAP bind</name> <configKey>LDAP_ANONYMOUS</configKey> <description><p> Without proper access control, executing an LDAP statement that contains a user-controlled value can allow an attacker to abuse poorly configured LDAP context. All LDAP queries executed against the context will be performed without authentication and access control. An attacker may be able to manipulate one of these queries in an unexpected way to gain access to records that would otherwise be protected by the directory's access control mechanism. </p> <p> <b>Vulnerable Code:</b> <pre>... env.put(Context.SECURITY_AUTHENTICATION, "none"); DirContext ctx = new InitialDirContext(env); ...</pre> </p> <p> <b>Solution:</b> <br/> Consider other modes of authentication to LDAP and ensure proper access control mechanism. </p> <br/> <p> <b>References</b><br/> <a href="https://docs.oracle.com/javase/tutorial/jndi/ldap/auth_mechs.html">Ldap Authentication Mechanisms</a><br/> </p></description> <tag>security</tag> </rule> <rule key='LDAP_ENTRY_POISONING' priority='CRITICAL'> <name>Security - LDAP Entry Poisoning</name> <configKey>LDAP_ENTRY_POISONING</configKey> <description><p> JNDI API support the binding of serialize object in LDAP directories. If certain attributes are presented, the deserialization of object will be made in the application querying the directory (See Black Hat USA 2016 white paper for details). Object deserialization should be consider a risky operation that can lead to remote code execution. </p> <p> The exploitation of the vulnerability will be possible if the attacker has an entry point in an LDAP base query, by adding attributes to an existing LDAP entry or by configuring the application to use a malicious LDAP server. </p> <p> <b>Vulnerable Code:</b> <pre> DirContext ctx = new InitialDirContext(); //[...] ctx.search(query, filter, new SearchControls(scope, countLimit, timeLimit, attributes, true, //Enable object deserialization if bound in directory deref)); </pre> </p> <p> <b>Solution:</b> <pre> DirContext ctx = new InitialDirContext(); //[...] ctx.search(query, filter, new SearchControls(scope, countLimit, timeLimit, attributes, false, //Disable deref)); </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE-wp.pdf">Black Hat USA 2016: A Journey From JNDI/LDAP Manipulation to Remote Code Execution Dream Land</a> (<a href="https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE.pdf">slides</a> &amp; <a href="https://www.youtube.com/watch?v=Y8a5nB-vy78">video</a>) by Alvaro Mu&#xF1;oz and Oleksandr Mirosh<br/> <a href="https://community.hpe.com/t5/Security-Research/Introducing-JNDI-Injection-and-LDAP-Entry-Poisoning/ba-p/6885118">HP Enterprise: Introducing JNDI Injection and LDAP Entry Poisoning</a> by Alvaro Mu&#xF1;oz<br/> <a href="http://blog.trendmicro.com/trendlabs-security-intelligence/new-headaches-how-the-pawn-storm-zero-day-evaded-javas-click-to-play-protection/">TrendMicro: How The Pawn Storm Zero-Day Evaded Java's Click-to-Play Protection</a> by Jack Tang </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>security</tag> </rule> <rule key='COOKIE_PERSISTENT' priority='MAJOR'> <name>Security - Persistent Cookie Usage</name> <configKey>COOKIE_PERSISTENT</configKey> <description><p> Storing sensitive data in a persistent cookie for an extended period can lead to a breach of confidentiality or account compromise. </p> <p> <b>Explanation:</b><br/> If private information is stored in persistent cookies, attackers have a larger time window in which to steal this data - especially since persistent cookies are often set to expire in the distant future. Persistent cookies are generally stored in a text file on the client and an attacker with access to the victim's machine can steal this information.<br/> Persistent cookies are often used to profile users as they interact with a site. Depending on what is done with this tracking data, it is possible to use persistent cookies to violate users' privacy. </p> <p> <b>Vulnerable Code:</b> The following code sets a cookie to expire in 1 year.<br/> <pre>[...] Cookie cookie = new Cookie("email", email); cookie.setMaxAge(60*60*24*365); [...]</pre> </p> <p> <b>Solution:</b><br/> <ul> <li>Use persistent cookies only if necessary and limit their maximum age.</li> <li>Don't use persistent cookies for sensitive data.</li> </ul> </p> <br/> <p> <b>References</b><br/> <a href="https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/Cookie.html#setMaxAge%28int%29">Class Cookie <code>setMaxAge</code> documentation</a><br/> <a href="https://cwe.mitre.org/data/definitions/539.html">CWE-539: Information Exposure Through Persistent Cookies</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='URL_REWRITING' priority='MAJOR'> <name>Security - URL rewriting method</name> <configKey>URL_REWRITING</configKey> <description><p> The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL.<br/> URL rewriting has significant security risks. Since session ID appears in the URL, it may be easily seen by third parties. Session ID in the URL can be disclosed in many ways, for example:<br/> <ul> <li>Log files,</li> <li>The browser history,</li> <li>By copy-and-pasting it into an e-mail or posting,</li> <li>The HTTP Referrer.</li> </ul> </p> <p> <b>Vulnerable Code:</b><br/> <pre>out.println("Click &lt;a href=" + res.encodeURL(HttpUtils.getRequestURL(req).toString()) + "&gt;here&lt;/a&gt;");</pre> </p> <p> <b>Solution:</b><br/> Avoid using those methods. If you are looking to encode a URL String or form parameters do not confuse the URL rewriting methods with the URLEncoder class. </p> <br/> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Top_10_2010-A3-Broken_Authentication_and_Session_Management">OWASP Top 10 2010-A3-Broken Authentication and Session Management</a><br/> </p></description> <tag>security</tag> </rule> <rule key='INSECURE_SMTP_SSL' priority='MAJOR'> <name>Security - Insecure SMTP SSL connection</name> <configKey>INSECURE_SMTP_SSL</configKey> <description><p> Server identity verification is disabled when making SSL connections. Some email libraries that enable SSL connections do not verify the server certificate by default. This is equivalent to trusting all certificates. When trying to connect to the server, this application would readily accept a certificate issued to "victim.com". The application would now potentially leak sensitive user information on a broken SSL connection to the victim server. </p> <p> <b>Vulnerable Code:</b><br/> <pre>... Email email = new SimpleEmail(); email.setHostName("smtp.servermail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); email.setFrom("[email protected]"); email.setSubject("TestMail"); email.setMsg("This is a test mail ... :-)"); email.addTo("[email protected]"); email.send(); ...</pre> </p> <p> <b>Solution:</b><br/> Please add the following check to verify the server certificate: <pre>email.setSSLCheckServerIdentity(true);</pre> </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/297.html">CWE-297: Improper Validation of Certificate with Host Mismatch</a><br/> </p></description> <tag>owasp-a6</tag> <tag>cryptography</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='AWS_QUERY_INJECTION' priority='CRITICAL'> <name>Security - AWS Query Injection</name> <configKey>AWS_QUERY_INJECTION</configKey> <description><p> Constructing SimpleDB queries containing user input can allow an attacker to view unauthorized records.<br/> The following example dynamically constructs and executes a SimpleDB SELECT query allowing the user to specify the productCategory. The attacker can modify the query, bypass the required authentication for customerID and view records matching any customer. </p> <p> <b>Vulnerable Code:</b><br/> <pre>... String customerID = getAuthenticatedCustomerID(customerName, customerCredentials); String productCategory = request.getParameter("productCategory"); ... AmazonSimpleDBClient sdbc = new AmazonSimpleDBClient(appAWSCredentials); String query = "select * from invoices where productCategory = '" + productCategory + "' and customerID = '" + customerID + "' order by '" + sortColumn + "' asc"; SelectResult sdbResult = sdbc.select(new SelectRequest(query)); </pre> </p> <p> <b>Solution:</b><br/> This issue is analogical to SQL Injection. Sanitize user input before using it in a SimpleDB query. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/943.html">CWE-943: Improper Neutralization of Special Elements in Data Query Logic</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='BEAN_PROPERTY_INJECTION' priority='CRITICAL'> <name>Security - JavaBeans Property Injection</name> <configKey>BEAN_PROPERTY_INJECTION</configKey> <description><p> An attacker can set arbitrary bean properties that can compromise system integrity. Bean population functions allow to set a bean property or a nested property. An attacker can leverage this functionality to access special bean properties like <code>class.classLoader</code> that will allow him to override system properties and potentially execute arbitrary code. </p> <p> <b>Vulnerable Code:</b><br/> <pre>MyBean bean = ...; HashMap map = new HashMap(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); map.put(name, request.getParameterValues(name)); } BeanUtils.populate(bean, map);</pre> </p> <p> <b>Solution:</b><br/> Avoid using user controlled values to populate Bean property names. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/15.html">CWE-15: External Control of System or Configuration Setting</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='STRUTS_FILE_DISCLOSURE' priority='MAJOR'> <name>Security - Struts File Disclosure</name> <configKey>STRUTS_FILE_DISCLOSURE</configKey> <description><p> Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories.<br/> An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting <code>"http://example.com/?returnURL=WEB-INF/applicationContext.xml"</code> would display the application's <code>applicationContext.xml</code> file. The attacker would be able to locate and download the <code>applicationContext.xml</code> referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. </p> <p> <b>Vulnerable Code:</b><br/> <pre>... String returnURL = request.getParameter("returnURL"); Return new ActionForward(returnURL); ...</pre> </p> <p> <b>Solution:</b><br/> Avoid constructing server-side redirects using user controlled input. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/552.html">CWE-552: Files or Directories Accessible to External Parties</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SPRING_FILE_DISCLOSURE' priority='MAJOR'> <name>Security - Spring File Disclosure</name> <configKey>SPRING_FILE_DISCLOSURE</configKey> <description><p> Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories.<br/> An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting <code>"http://example.com/?returnURL=WEB-INF/applicationContext.xml"</code> would display the application's <code>applicationContext.xml</code> file. The attacker would be able to locate and download the <code>applicationContext.xml</code> referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. </p> <p> <b>Vulnerable Code:</b><br/> <pre>... String returnURL = request.getParameter("returnURL"); return new ModelAndView(returnURL); ...</pre> </p> <p> <b>Solution:</b><br/> Avoid constructing server-side redirects using user controlled input. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/552.html">CWE-552: Files or Directories Accessible to External Parties</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='REQUESTDISPATCHER_FILE_DISCLOSURE' priority='MAJOR'> <name>Security - RequestDispatcher File Disclosure</name> <configKey>REQUESTDISPATCHER_FILE_DISCLOSURE</configKey> <description><p> Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories.<br/> An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting <code>"http://example.com/?jspFile=../applicationContext.xml%3F"</code> would display the application's <code>applicationContext.xml</code> file. The attacker would be able to locate and download the <code>applicationContext.xml</code> referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. </p> <p> <b>Vulnerable Code:</b><br/> <pre>... String jspFile = request.getParameter("jspFile"); request.getRequestDispatcher("/WEB-INF/jsps/" + jspFile + ".jsp").include(request, response); ...</pre> </p> <p> <b>Solution:</b><br/> Avoid constructing server-side redirects using user controlled input. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/552.html">CWE-552: Files or Directories Accessible to External Parties</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='FORMAT_STRING_MANIPULATION' priority='INFO'> <name>Security - Format String Manipulation</name> <configKey>FORMAT_STRING_MANIPULATION</configKey> <description><p> Allowing user input to control format parameters could enable an attacker to cause exceptions to be thrown or leak information.<br/> Attackers may be able to modify the format string argument, such that an exception is thrown. If this exception is left uncaught, it may crash the application. Alternatively, if sensitive information is used within the unused arguments, attackers may change the format string to reveal this information.<br/> The example code below lets the user specify the decimal points to which it shows the balance. The user can in fact specify anything causing an exception to be thrown which could lead to application failure. Even more critical within this example, if an attacker can specify the user input <code>"2f %3$s %4$.2"</code>, the format string would be <code>"The customer: %s %s has the balance %4$.2f %3$s %4$.2"</code>. This would then lead to the sensitive <code>accountNo</code> to be included within the resulting string. </p> <p> <b>Vulnerable Code:</b><br/> <pre>Formatter formatter = new Formatter(Locale.US); String format = "The customer: %s %s has the balance %4$." + userInput + "f"; formatter.format(format, firstName, lastName, accountNo, balance);</pre> </p> <p> <b>Solution:</b><br/> Avoid using user controlled values in the format string argument. </p> <br/> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/134.html">CWE-134: Use of Externally-Controlled Format String</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='HTTP_PARAMETER_POLLUTION' priority='MAJOR'> <name>Security - HTTP Parameter Pollution</name> <configKey>HTTP_PARAMETER_POLLUTION</configKey> <description><p> Concatenating unvalidated user input into a URL can allow an attacker to override the value of a request parameter. Attacker may be able to override existing parameter values, inject a new parameter or exploit variables out of a direct reach. HTTP Parameter Pollution (HPP) attacks consist of injecting encoded query string delimiters into other existing parameters. If a web application does not properly sanitize the user input, a malicious user may compromise the logic of the application to perform either client-side or server-side attacks.<br/> In the following example the programmer has not considered the possibility that an attacker could provide a parameter <code>lang</code> such as <code>en&user_id=1</code>, which would enable him to change the <code>user_id</code> at will. </p> <p> <b>Vulnerable Code:</b><br/> <pre>String input = request.getParameter("lang"); GetMethod get = new GetMethod("http://www.host.com/viewDetails"); get.setQueryString("lang=" + input + "&user_id=" + userId); get.execute();</pre> <p> <b>Solution:</b><br/> You can either encode user input before placing it in HTTP parameters or use the <a href="https://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html">UriBuilder class</a> from <a href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>. <pre> URIBuilder uriBuilder = new URIBuilder("http://www.host.com/viewDetails"); uriBuilder.addParameter("lang", input); uriBuilder.addParameter("user_id", userId); HttpGet httpget = new HttpGet(uriBuilder.build().toString()); //OK </pre> </p> <br/> <p> <b>References</b><br/> <a href="https://capec.mitre.org/data/definitions/460.html">CAPEC-460: HTTP Parameter Pollution (HPP)</a> </p></description> <tag>security</tag> </rule> <rule key='INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE' priority='INFO'> <name>Security - Information Exposure Through An Error Message</name> <configKey>INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE</configKey> <description><p> The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of ".." sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query. </p> <p> <b>Vulnerable Code:</b><br/> <pre>try { out = httpResponse.getOutputStream() } catch (Exception e) { e.printStackTrace(out); }</pre> </p> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/209.html">CWE-209: Information Exposure Through an Error Message</a><br/> <a href="https://cwe.mitre.org/data/definitions/211.html">CWE-211: Information Exposure Through Externally-Generated Error Message</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SMTP_HEADER_INJECTION' priority='MAJOR'> <name>Security - SMTP Header Injection</name> <configKey>SMTP_HEADER_INJECTION</configKey> <description><p> Simple Mail Transfer Protocol (SMTP) is a the text based protocol used for email delivery. Like with HTTP, headers are separate by new line separator. If user input is place in a header line, the application should remove or replace new line characters (<code>CR</code> / <code>LF</code>). You should use a safe wrapper such as <a href="https://commons.apache.org/proper/commons-email/userguide.html">Apache Common Email</a> and <a href="http://www.simplejavamail.org">Simple Java Mail</a> which filter special characters that can lead to header injection. </p> <b>Vulnerable Code:</b><br/> <p> <pre> Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] {new InternetAddress("[email protected]")}); message.setSubject(usernameDisplay + " has sent you notification"); //Injectable API message.setText("Visit your ACME Corp profile for more info."); Transport.send(message); </pre> </p> <b>Solution</b><br/> <p>Use <a href="https://commons.apache.org/proper/commons-email/userguide.html">Apache Common Email</a> or <a href="http://www.simplejavamail.org">Simple Java Mail</a>.</p> <p> <b>References</b><br/> <a href="https://www.owasp.org/index.php/Testing_for_IMAP/SMTP_Injection_(OTG-INPVAL-011)">OWASP SMTP Injection</a><br/> <a href="https://cwe.mitre.org/data/definitions/93.html">CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')</a><br/> <a href="https://commons.apache.org/proper/commons-email/userguide.html">Commons Email: User Guide</a><br/> <a href="http://www.simplejavamail.org">Simple Java Mail Website</a><br/> <a href="https://security.stackexchange.com/a/54100/24973">StackExchange InfoSec: What threats come from CRLF in email generation?</a><br/> </p></description> <tag>owasp-a1</tag> <tag>injection</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='RPC_ENABLED_EXTENSIONS' priority='CRITICAL'> <name>Security - Enabling extensions in Apache XML RPC server or client.</name> <configKey>RPC_ENABLED_EXTENSIONS</configKey> <description><p> Enabling extensions in Apache XML RPC server or client can lead to deserialization vulnerability which would allow an attacker to execute arbitrary code. <br/> It's recommended not to use <code>setEnabledForExtensions</code> method of <code>org.apache.xmlrpc.client.XmlRpcClientConfigImpl</code> or <code>org.apache.xmlrpc.XmlRpcConfigImpl</code>. By default, extensions are disabled both on the client and the server. </p> <p> <b>References</b><br/> <a href="https://0ang3el.blogspot.com/2016/07/beware-of-ws-xmlrpc-library-in-your.html">0ang3el's Blog: Beware of WS-XMLRPC library in your Java App</a><br/> <a href="https://nvd.nist.gov/vuln/detail/CVE-2016-5003">CVE-2016-5003 vulnerability reference</a><br/> </p></description> <tag>security</tag> </rule> <rule key='WICKET_XSS1' priority='MAJOR'> <name>Security - Disabling HTML escaping put the application at risk for XSS</name> <configKey>WICKET_XSS1</configKey> <description><p> Disabling HTML escaping put the application at risk for Cross-Site Scripting (XSS). </p> <p> <b>Vulnerable Code:</b><br/> <pre> add(new Label("someLabel").setEscapeModelStrings(false)); </pre> </p> <p> <b>References</b><br/> <a href="https://ci.apache.org/projects/wicket/guide/6.x/guide/modelsforms.html">Wicket models and forms - Reference Documentation</a><br/> <a href="http://projects.webappsec.org/w/page/13246920/Cross%20Site%20Scripting">WASC-8: Cross Site Scripting</a><br/> <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet">OWASP: XSS Prevention Cheat Sheet</a><br/> <a href="https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_%28XSS%29">OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)</a><br/> <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')</a> </p></description> <tag>owasp-a3</tag> <tag>wasc</tag> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='SAML_IGNORE_COMMENTS' priority='CRITICAL'> <name>Security - Ignoring XML comments in SAML may lead to authentication bypass</name> <configKey>SAML_IGNORE_COMMENTS</configKey> <description><p> Security Assertion Markup Language (SAML) is a single sign-on protocol that that used XML. The SAMLResponse message include statements that describe the authenticated user. If a user manage to place XML comments (<code>&lt;!-- --&gt;</code>), it may caused issue in the way the parser extract literal value. </p> <p> For example, let's take the following XML section: <pre>&lt;saml:Subject&gt;&lt;saml:NameID&gt;[email protected]&lt;!----&gt;.evil.com&lt;/saml:NameID&gt;&lt;/saml:Subject&gt;</pre> The user identity is <code>"[email protected]&lt;!----&gt;.evil.com"</code> but it is in fact a text node <code>"[email protected]"</code>, a comment <code>""</code> and a text node <code>".evil.com"</code>. When extracting the NameID, the service provider implementation might take first text node or the last one. </p> <p> <b>Vulnerable Code:</b><br/> <pre> @Bean ParserPool parserPool1() { BasicParserPool pool = new BasicParserPool(); pool.setIgnoreComments(false); return pool; } </pre> </p> <p> <b>Solution:</b><br/> <pre> @Bean ParserPool parserPool1() { BasicParserPool pool = new BasicParserPool(); pool.setIgnoreComments(true); return pool; } </pre> </p> <p> <b>References</b><br/> <a href="https://duo.com/blog/duo-finds-saml-vulnerabilities-affecting-multiple-implementations">Duo Finds SAML Vulnerabilities Affecting Multiple Implementations</a><br/> <a href="https://spring.io/blog/2018/03/01/spring-security-saml-and-this-week-s-saml-vulnerability">Spring Security SAML and this week's SAML Vulnerability</a><br/> </p></description> <tag>security</tag> </rule> <rule key='OVERLY_PERMISSIVE_FILE_PERMISSION' priority='MAJOR'> <name>Security - Overly permissive file permission</name> <configKey>OVERLY_PERMISSIVE_FILE_PERMISSION</configKey> <description><p> It is generally a bad practices to set overly permissive file permission such as read+write+exec for all users. If the file affected is a configuration, a binary, a script or sensitive data, it can lead to privilege escalation or information leakage. </p> <p> It is possible that another service, running on the same host as your application, gets compromised. Services typically run under a different user. A compromised service account could be use to read your configuration, add execution instruction to scripts or alter the data file. To limite the damage from other services or local users, you should limited to permission of your application files. </p> <p> <b>Vulnerable Code 1 (symbolic notation):</b><br/> <pre> Files.setPosixFilePermissions(configPath, PosixFilePermissions.fromString("rw-rw-rw-")); </pre> </p> <p> <b>Solution 1 (symbolic notation):</b><br/> <pre> Files.setPosixFilePermissions(configPath, PosixFilePermissions.fromString("rw-rw----")); </pre> </p> <p> <b>Vulnerable Code 2 (Object-oriented implementation):</b><br/> <pre> Set&lt;PosixFilePermission&gt; perms = new HashSet&lt;&gt;(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); </pre> </p> <p> <b>Solution 2 (Object-oriented implementation):</b><br/> <pre> Set&lt;PosixFilePermission&gt; perms = new HashSet&lt;&gt;(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); </pre> </p> <p> <b>References</b><br/> <a href="https://cwe.mitre.org/data/definitions/732.html">CWE-732: Incorrect Permission Assignment for Critical Resource</a><br/> <a href="https://payatu.com/guide-linux-privilege-escalation/">A guide to Linux Privilege Escalation</a><br/> <a href="https://en.wikipedia.org/wiki/File_system_permissions">File system permissions</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='IMPROPER_UNICODE' priority='CRITICAL'> <name>Security - Improper handling of Unicode transformations</name> <configKey>IMPROPER_UNICODE</configKey> <description><p> Unexpected behavior in unicode transformations can sometimes lead to bugs, some of them affecting software security. A code that applies the uppercase transformation to two strings could mistakenly interpret both strings as being equal. </p> <p> In the code bellow, the string <code>"ADM\u0131N"</code> would cause the condition to be true. When the uppercase transformation is applied, the character `\u0131` will becomme '\u0049' (I). It can be an issue if the developer only one user to be <code>"ADMIN"</code>.<br/> <pre> if(username.toUpperCase().equals("ADMIN")) { //... } </pre> </p> <p> Similar characters transformations can occurs with normalization functions. In the code bellow, the string <code>"BAC\u212AUP"</code> would cause the condition to be true. When the normalization transformation is applied, the character `\u212A` will becomme '\u0048' (K).<br/> <pre> if(Normalizer.normalize(input, Normalizer.Form.NFC).equals("BACKUP")) { //... } </pre> </p> <p> <b>References</b><br/> <a href="https://www.gosecure.net/blog/2020/08/04/unicode-for-security-professionals/">Unicode for Security Professionals</a><br/> <a href="http://websec.github.io/unicode-security-guide/character-transformations/">Unicode Security Guide: Character Transformations</a><br/> <a href="https://cwe.mitre.org/data/definitions/176.html">CWE-176: Improper Handling of Unicode Encoding</a><br/> <a href="http://unicode.org/reports/tr36/">Unicode: Unicode Security Considerations</a><br/> </p></description> <tag>cwe</tag> <tag>security</tag> </rule> <rule key='MODIFICATION_AFTER_VALIDATION' priority='MAJOR'> <name>Security - String is modified after validation and not before it</name> <configKey>MODIFICATION_AFTER_VALIDATION</configKey> <description><p> A string must not be modified after validation because it may allow an attacker to bypass validation using a tricky string which becomes malicious after the modification. For example, a program may filter out the &langle;script&rangle; tags from HTML input to avoid cross-site scripting (XSS) and other vulnerabilities. If non-character code points are deleted from the input following validation, an attacker may pass the string "&langle;scr"+"\uFDEF"+"ipt&rangle;" so that the validation check fails to detect the &langle;script&rangle; tag, but the subsequent removal of the non-character code pont creates a &langle;script&rangle; tag in the input: <pre> Pattern pattern = Pattern.compile("&lt;script&gt;"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalArgumentException("Invalid input"); } s = s.replaceAll("[\\p{Cn}]", ""); </pre> </p> <p> The proper way is to perform the modification before the validation so the passed string is first changed to &langle;script&rangle; which fails to be validated: <pre> s = s.replaceAll("[\\p{Cn}]", "\uFFFD"); Pattern pattern = Pattern.compile("&lt;script&gt;"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalArgumentException("Invalid input"); } </pre> </p> <p> <b>References</b><br/> <a href="https://wiki.sei.cmu.edu/confluence/display/java/IDS11-J.+Perform+any+string+modifications+before+validation">CERT: IDS11-J. Perform any string modifications before validation</a><br/> </p></description> <tag>security</tag> </rule> <rule key='NORMALIZATION_AFTER_VALIDATION' priority='MAJOR'> <name>Security - String is normalzied after validation and not before it</name> <configKey>NORMALIZATION_AFTER_VALIDATION</configKey> <description><p> A string must not be normalized after validation because it may allow an attacker to bypass validation using a tricky string which becomes malicious after the normalization. For example, a program may filter out the &langle;script&rangle; tags from HTML input to avoid cross-site scripting (XSS) and other vulnerabilities. However, in unicode, the same string can have many different representations. For example, \uFE64 is normalized to &langle; and \uFE65 is normalized to &rangle;. Thus the if an attacker passes the string "\uFE64" + "script" + "\uFE65" the validation check fails to detect the &langle;script&rangle; tag, but thereafter the string is normalized to the &langle;script&rangle; tag in the input: <pre> Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalStateException(); } s = Normalizer.normalize(s, Form.NFKC); </pre> </p> <p> The proper way is to do the normalization before the validation so the passed string is first changed to &langle;script&rangle; which fails to be validated: <pre> s = Normalizer.normalize(s, Form.NFKC); Pattern pattern = Pattern.compile("[<>]"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalStateException(); } </pre> </p> <p> <b>References</b><br/> <a href="https://wiki.sei.cmu.edu/confluence/display/java/IDS01-J.+Normalize+strings+before+validating+them">CERT: IDS01-J. Normalize strings before validating them</a><br/> </p></description> <tag>security</tag> </rule> <rule key='DANGEROUS_PERMISSION_COMBINATION' priority='CRITICAL'> <name>Security - Dangerous combination of permissions granted</name> <configKey>DANGEROUS_PERMISSION_COMBINATION</configKey> <description><p> Certain combinations of permissions can produce significant capability increases and should not be granted. Granting ReflectPermission on the target suppressAccessChecks is dangerous in that information (possibly confidential) and methods normally unavailable would be accessible to malicious code. Similarly, the permission <code>java.lang.RuntimePermission</code> applied to target createClassLoader grants code the permission to create a <code>ClassLoader</code> object. This is extremely dangerous, because malicious applications that can instantiate their own class loaders could then load their own rogue classes into the system. These newly loaded classes could be placed into any protection domain by the class loader, thereby automatically granting the classes the permissions for that domain. </p> <p> <b>Dangerous permission combinations:</b><br/> <pre> PermissionCollection pc = super.getPermissions(cs); pc.add(new ReflectPermission("suppressAccessChecks")); </pre> <br/> <pre> PermissionCollection pc = super.getPermissions(cs); pc.add(new RuntimePermission("createClassLoader")); </pre> </p> <p>References</b><br> <a href="https://wiki.sei.cmu.edu/confluence/display/java/ENV03-J.+Do+not+grant+dangerous+combinations+of+permissions">CERT: ENV03-J. Do not grant dangerous combinations of permissions</a><br/> </p></description> <tag>security</tag> </rule> </rules>
© 2015 - 2025 Weber Informatics LLC | Privacy Policy