Skip to content

Semgrep java rules


java_password_rule-ConstantDBPassword

Summary:

Use of hard-coded password

Severity: Critical

CWE: CWE-259

Description:

The application uses java.sql.DriverManager.getConnection() with a hard-coded password string literal in the third parameter. Hard-coded passwords embedded directly in source code create significant security risks because they cannot be rotated without code changes, are visible in version control history, and make access auditing impossible. If the source code is compromised or inadvertently exposed, the database credentials are immediately available to attackers. This pattern is particularly dangerous for database connections as it provides direct access to sensitive data stores.

Remediation:

Consider loading database credentials from secure external sources rather than hard-coding them in the application. For production applications, recommended to use a Key Management System (KMS) which provides auditing, access controls, and streamlined credential rotation. For Google Cloud Platform, use Cloud Key Management (https://cloud.google.com/kms/docs); for AWS, use AWS Secrets Manager or AWS KMS (https://aws.amazon.com/kms/); for on-premise or cloud-agnostic solutions, consider HashiCorp Vault (https://www.vaultproject.io/). Alternatively, environment variables or secure configuration files with restricted filesystem permissions can be used for simpler deployments. When using Spring Boot, leverage the application.properties or application.yml configuration with externalized values, and consider Spring Cloud Config for centralized credential management across multiple services.

OWASP:

  • A2:2017-Broken Authentication
  • A07:2021-Identification and Authentication Failures

java_password_rule-EmptyDBPassword

Summary:

Missing authentication for critical function (database)

Severity: Critical

CWE: CWE-306

Description:

The application uses java.sql.DriverManager.getConnection() with an empty string as the password parameter, resulting in unauthenticated database connections. This completely bypasses database authentication mechanisms and allows unrestricted access to the database from any code path that can invoke this connection. Unauthenticated database connections are extremely dangerous as they provide no access control, no audit trail of who performed which operations, and no ability to revoke access without code changes. Even in development environments, unauthenticated connections should be avoided to prevent insecure patterns from propagating to production deployments.

Remediation:

Recommended to configure the database server to require authentication and create dedicated database users with minimum necessary privileges for the application. Consult your database server documentation for authentication setup (e.g., PostgreSQL's pg_hba.conf, MySQL's user management, Oracle's authentication methods). Once authentication is enabled, load credentials from secure external sources such as environment variables, secure configuration files with restricted permissions, or a Key Management System. For production environments, consider using AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, or HashiCorp Vault for centralized credential management with automatic rotation capabilities. When using connection pooling libraries like HikariCP or Apache DBCP, configure credentials through their DataSource properties rather than passing them directly to DriverManager.

OWASP:

  • A2:2017-Broken Authentication
  • A07:2021-Identification and Authentication Failures

rules_lgpl_java_webview_rule-webview-external-storage

Summary:

Exposed dangerous method or function

Severity: Critical

CWE: CWE-749

Description:

The application calls WebView.loadUrl() with paths obtained from Environment.getExternalStorageDirectory() or getExternalFilesDir(), loading HTML or JavaScript files directly from external storage into a WebView. External storage on Android is world-readable and world-writable by any application with storage permissions (on devices below API 29) or accessible by malicious apps through scoped storage vulnerabilities. An attacker can replace legitimate HTML/JS files with malicious content that executes within the WebView's security context, potentially leading to XSS attacks, credential theft, or unauthorized access to WebView-accessible APIs including JavaScript interfaces exposed via addJavascriptInterface().

Remediation:

Consider storing web content in the app's internal storage using Context.getFilesDir() or package the content in the app's assets directory and load it using file:///android_asset/ URLs. Internal storage is private to the app and protected by Android's sandboxing mechanisms, preventing other apps from modifying the content. If you must load user-provided content, recommended to use a ContentProvider with FileProvider to serve files through content:// URIs with explicit permission grants, which provides controlled access and prevents arbitrary file modifications. For dynamic web content that changes frequently, consider loading from HTTPS endpoints with proper certificate validation and implementing Content Security Policy headers to mitigate injection risks. Never use external storage for security-sensitive web content such as authentication pages, payment forms, or pages with JavaScript interfaces that bridge to native Android functionality.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

Summary:

Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting')

Severity: High

CWE: CWE-113

Description:

The application passes user-supplied input from HttpServletRequest methods like getParameter() or getHeader() directly into a javax.servlet.http.Cookie constructor or setValue() call without proper validation. HTTP Response Splitting occurs when Carriage Return (CR \r) and Line Feed (LF \n) characters are injected into cookie values, allowing attackers to inject the \r\n sequence to manipulate HTTP responses. This could enable cache poisoning attacks or Cross-Site Scripting (XSS) by injecting additional headers or response bodies that will be interpreted by the client or intermediate caching proxies.

Remediation:

Consider validating all user-supplied input before using it in cookie values by rejecting any characters below 0x21 or the characters: '"' ',' ';' '\' and 0x7f as specified in RFC 6265. Modern Java application servers like Apache Tomcat 8.0+ and newer Jetty versions automatically reject \r and \n characters in cookies, but explicit validation provides defense-in-depth and ensures compatibility across environments. Recommended to implement a validation method that throws IllegalArgumentException for invalid characters, or use org.apache.commons.text.StringEscapeUtils.escapeJava() to escape the input before setting cookie values. Be aware that some older application servers may not provide automatic protection, making input validation critical for security. More information at https://owasp.org/www-community/attacks/HTTP_Response_Splitting

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

Summary:

Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting')

Severity: High

CWE: CWE-113

Description:

The application passes user-supplied input from HttpServletRequest methods like getParameter() or getHeader() directly into HttpServletResponse.setHeader() or addHeader() calls without proper validation. HTTP Response Splitting occurs when Carriage Return (CR \r) and Line Feed (LF \n) characters are injected into HTTP headers, allowing attackers to inject the \r\n sequence to split the response and inject additional headers or response content. This could enable cache poisoning attacks, session fixation, or Cross-Site Scripting (XSS) by manipulating how the response is interpreted by clients or downstream caching services.

Remediation:

Consider validating all user-supplied input before using it in HTTP response headers by rejecting any characters below 0x21 or the characters: '"' ',' ';' '\' and 0x7f. While some Java application servers like Apache Tomcat automatically encode CRLF characters as space (0x20) characters in response headers, explicit validation provides defense-in-depth and ensures compatibility across different server implementations. Recommended to implement a validation method that throws IllegalArgumentException for invalid characters, or use org.apache.commons.text.StringEscapeUtils.escapeJava() to sanitize the input before calling setHeader() or addHeader(). Be aware that some older or less common application servers may not provide automatic CRLF protection, making input validation critical. More information at https://owasp.org/www-community/attacks/HTTP_Response_Splitting

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_inject_rule-CommandInjection

Summary:

Improper neutralization of special elements used in an OS command ('OS Command Injection')

Severity: High

CWE: CWE-78

Description:

The application uses Runtime.exec(), ProcessBuilder.command(), or the ProcessBuilder constructor with user-controlled input which enables OS command injection attacks. This critical vulnerability allows adversaries to execute arbitrary system commands, potentially leading to full system compromise, data exfiltration, or denial of service. Command injection can occur when user input is incorporated into command strings, command arguments, or even filenames passed to these Java APIs without proper validation or sanitization.

Remediation:

Consider using ProcessBuilder with a list-based argument approach where each argument is a separate array element, which prevents shell interpretation and meta-character injection. Never pass user input directly into command strings or use string concatenation to build commands. When filenames from user uploads must be processed, generate random filenames using UUID.randomUUID() and store the original filename separately in a database or metadata file. It's strongly recommended to use native Java libraries instead of shelling out to external commands whenever possible to eliminate the attack surface entirely. If OS commands are unavoidable, use absolute paths to binaries (e.g., /usr/bin/convert instead of convert) to prevent untrusted search path vulnerabilities (CWE-426). Consider implementing an allowlist of permitted commands and arguments, and validate all inputs against strict patterns before use. More details at https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_inject_rule-FileDisclosureRequestDispatcher

Summary:

Files or directories accessible to external parties

Severity: High

CWE: CWE-552

Description:

The application uses HttpServletRequest.getRequestDispatcher() followed by RequestDispatcher.include() or RequestDispatcher.forward() with user-controlled input which can expose sensitive files within the web application context. These methods resolve and return any file accessible to the application including web.xml configuration files, compiled .class files, JSP source code, JAR/WAR archives, and other resources that should remain internal. This file disclosure vulnerability allows adversaries to read application source code, extract database credentials from configuration files, discover application structure, and gather information for further attacks.

Remediation:

Consider using a lookup table approach where user input is validated against a HashMap or enum of permitted view names, then mapped to hardcoded resource paths before calling getRequestDispatcher(). Never pass user input directly to getRequestDispatcher() or allow user-controlled path segments. As an alternative, use HttpServletResponse.sendRedirect() to perform HTTP 301/302 redirects which are safer than internal forwards because they don't expose the internal application structure and force a new request cycle. When using a lookup table, use HashMap.getOrDefault() to provide a safe fallback view when user input doesn't match any permitted value. For Spring MVC applications, rely on the framework's view resolution mechanism with controller methods returning logical view names rather than constructing paths directly. Consider implementing strict allowlist validation that only permits alphanumeric characters for any user-provided view identifiers, and log all attempts to access resources outside the permitted set for security monitoring.

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_inject_rule-FileDisclosureSpringFramework

Summary:

Files or directories accessible to external parties

Severity: High

CWE: CWE-552

Description:

The application uses org.springframework.web.servlet.ModelAndView constructor or the ModelAndView.setViewName() method with user-controlled input which can expose restricted JSP files and other view resources. Spring's ModelAndView class resolves view names through configured ViewResolvers, typically looking up .jsp files or other template resources. When view names are derived from user input without validation, adversaries can manipulate the path to access JSP files, configuration files, or other resources that should not be directly accessible. This vulnerability is particularly critical in Spring MVC applications where the view resolution mechanism might allow directory traversal or access to internal application views not intended for external users.

Remediation:

Consider using Spring MVC's standard controller pattern where methods return logical view names that are resolved through configured ViewResolvers, and use a lookup table or enum to map user input to permitted view names before constructing ModelAndView objects. Never pass user input directly to the ModelAndView constructor or setViewName() method. When different views must be selected based on user input, validate the input against an allowlist of permitted view identifiers using HashMap.getOrDefault() or a switch statement with only known-safe view names. Consider using redirect prefixes like redirect:/path in view names to perform HTTP redirects instead of internal forwards, which provides better isolation. For applications using Thymeleaf, FreeMarker, or other template engines, ensure the ViewResolver configuration restricts template resolution to specific directories and doesn't allow path traversal sequences. Implement logging for invalid view name requests to detect potential exploitation attempts. Modern Spring applications should consider using @ResponseBody with REST endpoints and client-side routing rather than server-side view resolution for improved security and architecture.

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_inject_rule-OgnlInjection

Summary:

Expression injection (OGNL)

Severity: High

CWE: CWE-917

Description:

The application uses Object Graph Navigation Language (OGNL) evaluation methods from Apache Struts2 packages such as OgnlUtil.getValue(), OgnlUtil.setValue(), OgnlUtil.compile(), TextParseUtil.translateVariables(), ValueStack.findValue(), OgnlReflectionProvider.setProperty(), or StrutsUtil.findValue() with user-controlled input which enables OGNL injection attacks. OGNL is a powerful expression language used by Struts2 to access Java objects and properties in the ActionContext, but when user input is evaluated as OGNL expressions, it allows adversaries to execute arbitrary Java code including OS commands through reflection and runtime manipulation. This vulnerability class has been responsible for numerous critical remote code execution exploits in Struts2 applications and should be treated as extremely dangerous.

Remediation:

Consider using standard Struts2 tags and value stack operations instead of low-level OGNL evaluation methods. Never pass user input directly to OGNL evaluation functions from the com.opensymphony.xwork2.ognl, com.opensymphony.xwork2.util, com.opensymphony.xwork2.util.reflection, or org.apache.struts2.util packages. Following the official Struts2 security guidelines, avoid using raw ${} expressions in JSP pages and templates with user-supplied data. When dynamic property access is needed, use Action setters and getters with validated property names from an allowlist rather than evaluating arbitrary OGNL expressions. Ensure you're running the latest patched version of Struts2 as many OGNL injection vulnerabilities have been addressed through framework updates and security patches. Consider migrating away from Struts2 to more modern frameworks like Spring MVC or Jakarta EE that don't rely on OGNL expression evaluation. If you must support dynamic expressions, implement strict input validation and use the SecurityMemberAccess features in Struts2 to restrict which classes and methods can be accessed via OGNL. More information at https://struts.apache.org/security/#do-not-use-incoming-untrusted-user-input-in-forced-expression-evaluation

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_ldap_rule-AnonymousLDAP

Summary:

Missing authentication for critical function (LDAP)

Severity: High

CWE: CWE-306

Description:

The application configures anonymous LDAP authentication by setting Context.SECURITY_AUTHENTICATION to "none" in the JNDI context environment. This disables authentication when communicating with the LDAP server, allowing any client to connect without credentials. Anonymous LDAP access exposes the directory to unauthorized queries and potential data exfiltration, as there are no access controls to restrict what information can be retrieved or which operations can be performed. This configuration violates the principle of least privilege and creates a significant security risk, especially when the LDAP directory contains sensitive user data, credentials, or organizational information.

Remediation:

Consider configuring proper authentication credentials when establishing LDAP connections using JNDI. Recommended to use Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS to specify the distinguished name (DN) and password for authentication, rather than setting Context.SECURITY_AUTHENTICATION to "none". Consider retrieving LDAP credentials from a secure credential store or key management system (KMS) rather than hardcoding them. Additionally, recommended to use parameterized search arguments with InitialDirContext.search() to prevent LDAP injection attacks when handling user-supplied input.

Example of secure LDAP connection with authentication and safe query handling:

// Create properties for LDAP connection configuration
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://ldap.example.org:3889");

// Configure authentication credentials (retrieve from secure store)
props.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org");
String ldapPassword = getAccountPasswordFromSecureStoreOrKMS();
props.put(Context.SECURITY_CREDENTIALS, ldapPassword);

// Establish authenticated LDAP connection
InitialDirContext ldapContext = new InitialDirContext(props);

// Configure search parameters
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

// Use parameterized queries to prevent LDAP injection
String userQuery = someUserInput;
Object[] searchArguments = new Object[]{userQuery};

// Execute search with automatic parameter encoding
NamingEnumeration answer = ldapContext.search(
  "dc=example,dc=org",
  "(cn={0})",
  searchArguments,
  searchControls
);

For more information on LDAP security best practices, see: LDAP_Injection_Prevention_Cheat_Sheet.html

OWASP:

  • A2:2017-Broken Authentication
  • A07:2021-Identification and Authentication Failures

java_password_rule-HardcodePassword

Summary:

Use of hard-coded password

Severity: High

CWE: CWE-259

Description:

The application uses hard-coded password string literals with security-sensitive Java APIs including java.security.KeyStore.PasswordProtection(), KeyStore.load(), KeyManagerFactory.init(), javax.security.auth.callback.PasswordCallback.setPassword(), javax.crypto.spec.PBEKeySpec, java.net.PasswordAuthentication, javax.security.auth.kerberos.KerberosKey, java.sql.DriverManager.getConnection(), io.vertx.ext.web.handler.CSRFHandler.create(), and generic setPassword() methods. Hard-coded passwords create multiple security vulnerabilities: they are visible in source code repositories and version control history, cannot be rotated without redeploying the application, make audit trails impossible to maintain, and provide no mechanism for access revocation. This pattern affects critical security components including keystore encryption, SSL/TLS certificate management, database authentication, Kerberos authentication, and password-based encryption schemes.

Remediation:

Consider loading credentials from secure external configuration sources rather than embedding them in source code. For production environments, recommended to use a Key Management System (KMS) that provides credential auditing, access controls, and automated rotation - such as AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, or HashiCorp Vault. For simpler deployments, use environment variables accessed via System.getenv() or secure properties files with restricted filesystem permissions loaded through java.util.Properties. When working with keystores and SSL/TLS certificates, consider using Java's JCEKS keystore type with externalized passwords, and leverage tools like keytool for secure keystore management. For database credentials in Spring applications, use Spring Boot's externalized configuration with encrypted properties via Jasypt or Spring Cloud Config Server. For PBE encryption, derive keys from user-supplied passphrases at runtime rather than hard-coding them. Important: ensure any migration plan includes rotating all previously hard-coded credentials as they should be considered compromised once committed to version control.

OWASP:

  • A2:2017-Broken Authentication
  • A07:2021-Identification and Authentication Failures

java_rule_sql_injection

Summary:

Unsafe SQL query with non parameterized parameters in Java

Severity: High

CWE: CWE-89

Description:

A SQL Injection vulnerability was detected where user-controlled input is unsafely incorporated into a SQL query through string concatenation (using +), string formatting (using .format() or .formatted()), or quoted placeholders ('%s'). The query is executed using methods such as executeQuery(), executeUpdate(), execute(), or similar SQL execution functions in JDBC, Spring JdbcTemplate, or other database APIs. SQL injection occurs when untrusted data is directly embedded into SQL statements without proper sanitization or parameterization, allowing attackers to manipulate the query logic, bypass authentication, extract sensitive data, modify or delete records, or execute arbitrary SQL commands against the database.

Remediation:

Consider using parameterized queries (also known as prepared statements) with positional (?) or named (:param) parameter placeholders instead of string concatenation or string formatting methods. Recommended to use established frameworks that provide built-in SQL injection protection, such as JDBC PreparedStatement, Spring JdbcTemplate, JPA/Hibernate Query API, or other reputable ORM libraries. These frameworks handle user input separately from the SQL command structure, ensuring that user data is properly escaped and cannot alter the query logic. Consider validating and sanitizing all user-controlled input before use, even when using parameterized queries, as an additional defense-in-depth measure.

Example of safe SQL query using JDBC PreparedStatement with positional parameters:

// Unsafe: String concatenation allows SQL injection
// String query = "SELECT * FROM users WHERE username = '" + username + "'";

// Safe: Use PreparedStatement with positional parameters
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet results = stmt.executeQuery();

Example of safe SQL query using Spring JdbcTemplate with positional parameters:

// Unsafe: String concatenation or .format()
// String query = String.format("INSERT INTO EMPLOYEE VALUES ('%s', '%s')",
//                              id, name);

// Safe: Use positional parameters with JdbcTemplate
jdbcTemplate.update(
  "INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)",
  id, "Bill", "Gates", "USA"
);

Example of safe SQL query using JPA with named parameters:

// Safe: Use named parameters in JPA queries
String jpql = "SELECT u FROM User u WHERE u.username = :username";
TypedQuery<User> query = entityManager.createQuery(jpql, User.class);
query.setParameter("username", username);
List<User> results = query.getResultList();

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_script_rule-ScriptInjection

Summary:

Improper control of generation of code ('Code Injection')

Severity: High

CWE: CWE-94

Description:

User-controlled input is passed to javax.script.ScriptEngine.eval() or javax.script.Invocable methods without proper sanitization. This allows attackers to execute arbitrary code, including OS commands through expressions like java.lang.Runtime.getRuntime().exec('/bin/sh'), leading to complete system compromise.

Remediation:

Never pass user-supplied input directly to ScriptEngine.eval() or Invocable methods. Consider hardcoding all script content or using a lookup table to map user input to predefined safe values. If dynamic values are required, recommended to use javax.script.Bindings to pass user input as data rather than code (e.g., bindings.put("name", userInput); eval(script, bindings)). This ensures user input is treated as string data and cannot be executed as code.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_script_rule-SpringSpelExpressionParser

Summary:

Improper neutralization of special elements used in an expression language statement ('Expression Language Injection')

Severity: High

CWE: CWE-917

Description:

User-controlled input is passed to Spring Framework's SpelExpressionParser.parseExpression() or parseRaw() methods without proper validation. This allows attackers to inject and execute arbitrary SpEL expressions, potentially accessing sensitive Java runtime objects, invoking methods, and executing OS commands, leading to complete system compromise.

Remediation:

Never pass user-supplied input directly to parseExpression() or parseRaw() methods. Consider using a lookup table to map user input to predefined safe expressions. If dynamic evaluation is required, recommended to use SimpleEvaluationContext (Spring 4.3+) instead of StandardEvaluationContext when calling getValue() on parsed expressions (e.g., parsedExpr.getValue(SimpleEvaluationContext.forReadOnlyDataBinding().build())). Note that even with SimpleEvaluationContext, attackers may access public properties of bound objects, so use with caution and minimize exposed data.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_templateinjection_rule-TemplateInjection

Summary:

Improper control of generation of code ('Code Injection')

Severity: High

CWE: CWE-94

Description:

The application allows control over template strings by dynamically passing user input to Velocity.evaluate(), getTemplate(), or process() methods. This enables adversaries to execute arbitrary Java code, including OS system commands, through template injection attacks.

Remediation:

Consider using a VelocityContext object to safely bind user-supplied data instead of passing it directly in template strings. Never call Velocity.evaluate() with user input in the template parameter. Recommended to use context.put(key, value) to pass user data, which treats it as data rather than executable template code. For FreeMarker and Pebble engines, use hardcoded template names with getTemplate("fixed-name") and pass user input only through the data context.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_xml_rule-XmlDecoder

Summary:

Deserialization of untrusted data

Severity: High

CWE: CWE-502

Description:

The application uses java.beans.XMLDecoder.readObject() to deserialize XML data, which is vulnerable to arbitrary code execution attacks. XMLDecoder interprets XML as executable Java code using JavaBeans conventions, allowing adversaries to craft malicious XML that instantiates arbitrary classes and invokes methods during deserialization. This can lead to remote code execution, as attackers can call constructors or setter methods that trigger dangerous operations. Unlike standard Java deserialization, XMLDecoder processes untrusted XML directly into object instantiation without built-in safeguards, making it particularly dangerous for processing user-controlled input. Public exploits exist (such as ysoserial) that can automatically generate payloads to exploit XMLDecoder vulnerabilities.

Remediation:

Consider migrating away from XMLEncoder and XMLDecoder entirely, as these APIs are inherently unsafe and deprecated for security reasons. Recommended alternatives include JSON serialization libraries like Jackson or Gson, which provide type-safe deserialization with configurable restrictions on allowed classes. If you must continue using XMLDecoder temporarily, implement a custom ClassLoader that explicitly whitelists only the specific bean classes your application needs, rejecting all other class loading attempts. Even with a custom ClassLoader, be aware that this is a defense-in-depth measure and not a complete solution, as subtle vulnerabilities may still exist. Ensure you never deserialize to base types like Object, always cast to the exact expected type, and consider creating intermediary DTOs with only the necessary fields to protect against mass assignment attacks. Additional guidance is available in the OWASP Deserialization Cheat Sheet at https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html

OWASP:

  • A8:2017-Insecure Deserialization
  • A08:2021-Software and Data Integrity Failures

java_xss_injection

Summary:

XSS vulnerability in Java web application

Severity: High

CWE: CWE-79

Description:

A Cross-Site Scripting (XSS) vulnerability was detected where untrusted data flows from request-derived variables into server-side rendering APIs without proper escaping or encoding. The rule detects taint flow from sources like Spring's @RequestParam and @PathVariable annotations, JSF's FacesContext parameters, Struts ActionContext parameters, GWT Window.Location methods, and standard servlet request methods into sinks including HttpServletResponse.getWriter() methods, JSF ResponseWriter.write(), Spring MVC model attributes, GWT HTML/HTMLPanel constructors, and bean property setters in managed beans. Without context-aware output encoding, attackers can inject malicious JavaScript that executes in victims' browsers, potentially leading to session hijacking, credential theft, phishing, or complete account takeover.

Remediation:

Consider using framework-specific output encoding functions appropriate to the rendering context. For Spring applications, use HtmlUtils.htmlEscape() when adding data to model attributes. For JSF applications, ensure auto-escaping is enabled (it is by default) and avoid using h:outputText escape="false". For plain servlet responses, use org.apache.commons.text.StringEscapeUtils.escapeHtml4() or OWASP Java Encoder's Encode.forHtml(). For GWT applications, use SafeHtmlUtils.fromString() instead of constructing HTML/HTMLPanel objects directly from strings. When data will be embedded in JavaScript contexts, use Encode.forJavaScript(), for CSS use Encode.forCssString(), and for URLs use Encode.forUriComponent(). Modern template engines like Thymeleaf provide automatic context-aware escaping and should be preferred over manual string construction. Implement Content Security Policy (CSP) headers with restrictive directives as defense-in-depth.

OWASP:

  • A03:2021-Injection

java_crypto_rule-BlowfishKeySize

Summary:

Inadequate encryption strength

Severity: Medium

CWE: CWE-326

Description:

The application uses KeyGenerator.getInstance("Blowfish") with a key size smaller than 128 bits, which may make the ciphertext vulnerable to birthday attacks. The Blowfish encryption algorithm was created in 1993 as a drop-in replacement for DES and has a 64-bit block size. This limited block size means Blowfish should never be used to encrypt files over 4GB in size, as birthday attacks become practical with approximately 32GB of data encrypted under the same key. Modern applications requiring strong encryption should migrate away from Blowfish entirely due to these fundamental limitations.

Remediation:

Consider migrating to KeyGenerator.getInstance("AES") with at least a 256-bit key size for modern symmetric encryption needs. AES provides a 128-bit block size which is resistant to birthday attacks and is widely supported across Java versions. When initializing the KeyGenerator, use keyGenerator.init(256) to specify the key size. For applications that absolutely must continue using Blowfish temporarily, increase the key size to at least 256 bits by calling keyGenerator.init(256) after obtaining the Blowfish KeyGenerator instance. More information on Java cryptography is available at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CipherDESInsecure

Summary:

Inadequate encryption strength

Severity: Medium

CWE: CWE-326

Description:

The application uses Cipher.getInstance("DES/...") which implements the Data Encryption Standard (DES), a broken cryptographic algorithm. DES has a 56-bit key size and 64-bit block size, making it vulnerable to brute-force attacks and birthday attacks. Modern computing power can break DES encryption in hours or days, and it has been officially deprecated by NIST since 2005. DES and its variants lack built-in message integrity, which means ciphertext tampering cannot be detected, potentially allowing adversaries to manipulate encrypted data without detection.

Remediation:

Consider migrating to Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which provides authenticated encryption with built-in message integrity. ChaCha20-Poly1305 is faster than AES-GCM on systems without hardware AES acceleration and is easier to use correctly. For applications requiring AES compatibility, use Cipher.getInstance("AES/GCM/NoPadding") with at least a 256-bit key and ensure unique nonces are generated for each encryption operation using SecureRandom. When using AES-GCM, nonce reuse leads to catastrophic security failures that can expose the encryption key. For random number generation, prefer SecureRandom.getInstance("DRBG") with appropriate DrbgParameters for enhanced security. More information available at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CipherDESedeInsecure

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application uses Cipher.getInstance("DESede/...") which implements Triple DES (3DES), a deprecated cryptographic algorithm. While 3DES applies DES three times with different keys to achieve effective 112-bit or 168-bit security, it still suffers from DES's fundamental 64-bit block size limitation. This small block size makes 3DES vulnerable to birthday attacks after encrypting approximately 32GB of data under the same key. NIST has deprecated 3DES for new applications and plans to disallow it entirely. Additionally, 3DES lacks built-in message integrity, meaning tampering with ciphertext cannot be detected.

Remediation:

Consider migrating to Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which provides authenticated encryption with superior performance and built-in message integrity protection. ChaCha20-Poly1305 is recommended for modern Java applications as it's faster than AES-GCM on most hardware and simpler to implement correctly. For applications requiring AES compatibility, use Cipher.getInstance("AES/GCM/NoPadding") with at least 256-bit keys and ensure unique 12-byte nonces are generated using SecureRandom for each encryption operation. When generating nonces or IVs, use SecureRandom.getInstance("DRBG") with DrbgParameters configured for appropriate security strength (at least 256 bits). More information at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CipherECBMode

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application uses Cipher.getInstance() with ECB (Electronic Codebook) mode, such as "AES/ECB/PKCS5Padding" or "DES/ECB/NoPadding". ECB mode is fundamentally insecure because it encrypts identical plaintext blocks into identical ciphertext blocks, revealing patterns in the encrypted data. This makes ECB unsuitable for encrypting any data larger than a single block, as attackers can analyze ciphertext patterns to infer information about the plaintext structure. Additionally, ECB mode provides no message integrity protection, allowing adversaries to tamper with ciphertext without detection.

Remediation:

Consider migrating to Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which provides authenticated encryption with built-in message integrity and eliminates the need for manual mode configuration. ChaCha20-Poly1305 is recommended for modern applications as it's simpler to use correctly and faster than AES-GCM on most hardware. For applications requiring AES, use Cipher.getInstance("AES/GCM/NoPadding") which provides authenticated encryption with 128-bit block sizes. When using AES-GCM, ensure unique 12-byte nonces are generated for each encryption using SecureRandom, as nonce reuse catastrophically compromises security. Avoid CBC mode unless specifically required, as it requires careful IV management and doesn't provide message integrity. More information at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CipherIntegrity

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application uses Cipher.getInstance() with cipher modes that lack built-in message integrity protection, including CBC, CTR, CFB, OFB, and ECB modes with AES, DES, DESede, or RC4 algorithms. Without message integrity, adversaries can tamper with ciphertext without detection, potentially leading to plaintext recovery attacks or compromise of the encryption key. Modes like CBC with padding are also vulnerable to padding oracle attacks, while ECB mode reveals patterns in the plaintext. These older cipher configurations require manual implementation of authenticated encryption, which is error-prone and frequently done incorrectly.

Remediation:

Consider migrating to Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which provides Authenticated Encryption with Associated Data (AEAD) and built-in message integrity. ChaCha20-Poly1305 is recommended as it performs well across all hardware platforms and is simpler to implement correctly than alternatives. For applications requiring AES compatibility, use Cipher.getInstance("AES/GCM/NoPadding") with at least 256-bit keys. When using GCM mode, generate unique 12-byte nonces for each encryption operation using SecureRandom.getInstance("DRBG") and never reuse nonces with the same key, as this leads to catastrophic security failures. Avoid implementing manual MAC-then-encrypt or encrypt-then-MAC schemes, as these are difficult to implement securely. More information at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CipherPaddingOracle

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application uses Cipher.getInstance() with CBC mode and PKCS5Padding or PKCS7Padding, such as "AES/CBC/PKCS5Padding" or "DES/CBC/PKCS5Padding". This combination is vulnerable to padding oracle attacks, where adversaries can decrypt ciphertext by observing whether padding is valid or invalid during decryption attempts. Applications often leak this information through distinct error messages, response timing differences, or different HTTP status codes when encountering padding errors versus other decryption failures. Successful padding oracle attacks allow complete plaintext recovery without knowing the encryption key.

Remediation:

Consider migrating to Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which eliminates padding entirely and provides built-in authenticated encryption. ChaCha20-Poly1305 is recommended as it's simpler to use correctly, faster on most hardware, and immune to padding oracle attacks. For applications requiring AES compatibility, use Cipher.getInstance("AES/GCM/NoPadding") which also eliminates padding while providing message integrity. When using GCM mode, ensure unique 12-byte nonces are generated for each encryption operation using SecureRandom. If CBC mode must be used temporarily, ensure all decryption errors return identical error messages and response times, and consider implementing additional HMAC verification before attempting decryption. More information on padding oracle attacks at https://en.wikipedia.org/wiki/Padding_oracle_attack and Java cryptography at https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-CustomMessageDigest

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application implements a custom class that extends java.security.MessageDigest, creating a custom cryptographic hash function. Implementing cryptographic hash functions correctly requires deep expertise in cryptanalysis and is extremely error-prone. Custom hash implementations almost always contain subtle flaws that make them vulnerable to collision attacks, preimage attacks, or other cryptographic weaknesses. Even minor implementation errors can completely compromise the security properties of a hash function.

Remediation:

Consider using a standard hash algorithm by calling MessageDigest.getInstance() with a NIST-recommended algorithm such as "SHA-256", "SHA-384", or "SHA-512". These algorithms have undergone extensive cryptanalysis and are implemented correctly in the Java standard library. For most applications, SHA-256 provides adequate security with good performance, while SHA-384 or SHA-512 offer higher security margins for sensitive applications. Avoid using deprecated algorithms like MD5 or SHA-1 even through the standard library, as they are cryptographically broken. The MessageDigest.update() method can be called multiple times to hash large data incrementally, and MessageDigest.digest() produces the final hash value. More information at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A6:2017-Security Misconfiguration
  • A04:2021-Insecure Design

java_crypto_rule-HazelcastSymmetricEncryption

Summary:

Inadequate encryption strength

Severity: Medium

CWE: CWE-326

Description:

The application uses new com.hazelcast.config.SymmetricEncryptionConfig() to configure Hazelcast network communications with deprecated symmetric encryption. Hazelcast's SymmetricEncryptionConfig has been deprecated because it provides only confidentiality without authentication, making it vulnerable to man-in-the-middle attacks where adversaries can intercept and modify cluster communications. The lack of mutual authentication means cluster members cannot verify each other's identity, allowing potential unauthorized nodes to join the cluster.

Remediation:

Consider migrating to TLS/SSL configuration for Hazelcast cluster communications using the SSLConfig class, which provides both encryption and mutual authentication between cluster members. TLS protects against man-in-the-middle attacks and ensures only authorized nodes can join the cluster. Configure TLS by setting up SSLConfig with appropriate keystores and truststores containing valid certificates. Use TLS 1.2 or higher and ensure certificates are properly validated. Hazelcast also supports integration with Java's JSSE (Java Secure Socket Extension) for standardized TLS configuration. More information on configuring TLS/SSL for Hazelcast available at: tls-ssl

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-InsufficientKeySizeRsa

Summary:

Inadequate encryption strength

Severity: Medium

CWE: CWE-326

Description:

The application uses KeyPairGenerator.getInstance("RSA") or RSAKeyGenParameterSpec with a key size smaller than 2048 bits, typically 1024 bits or less. RSA keys below 2048 bits are vulnerable to factorization attacks using modern computing resources. NIST deprecated 1024-bit RSA keys in December 2010, and advances in computational power and factorization algorithms continue to make smaller RSA keys increasingly vulnerable. RSA key strength degrades over time as computing power increases, making insufficient key sizes a critical security vulnerability.

Remediation:

Consider migrating to KeyPairGenerator.getInstance("Ed25519") which provides modern elliptic curve cryptography with approximately 128-bit security strength, smaller key sizes, and faster operations compared to RSA. Ed25519 automatically uses secure parameters and doesn't require manual key size configuration, reducing the risk of misconfiguration. If RSA is required for compatibility, use keyPairGenerator.initialize(2048) or higher (3072-bit or 4096-bit keys for higher security margins) when initializing the KeyPairGenerator. For new applications, Ed25519 is strongly recommended as it provides better performance and security with simpler implementation. More information on Ed25519 at http://ed25519.cr.yp.to/ and Java cryptography at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-NullCipher

Summary:

Use of a broken or risky cryptographic algorithm

Severity: Medium

CWE: CWE-327

Description:

The application creates a new javax.crypto.NullCipher() instance, which provides no encryption whatsoever. NullCipher implements the Cipher interface but performs identity transformation, meaning any data passed to its doFinal() or update() methods is returned unchanged as plaintext. This completely defeats the purpose of encryption and leaves sensitive data exposed. NullCipher is intended only for testing or as a placeholder during development, and should never be present in production code that handles sensitive information.

Remediation:

Consider replacing NullCipher with Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding") which provides strong authenticated encryption with built-in message integrity. ChaCha20-Poly1305 is recommended for modern Java applications as it offers excellent security and performance characteristics. Initialize the cipher with a 256-bit secret key and unique 12-byte nonces generated using SecureRandom.getInstance("DRBG") with appropriate DrbgParameters. For applications requiring AES compatibility, use Cipher.getInstance("AES/GCM/NoPadding") with at least 256-bit keys. Ensure proper key management practices are implemented, including secure key generation, storage, and rotation. More information on Java cryptography available at: java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-RsaNoPadding

Summary:

Use of RSA algorithm without OAEP

Severity: Medium

CWE: CWE-780

Description:

The application uses javax.crypto.Cipher.getInstance() with RSA encryption configured without padding (e.g., "RSA/ECB/NoPadding"), which does not incorporate Optimal Asymmetric Encryption Padding (OAEP). Without proper padding, RSA becomes vulnerable to chosen plaintext attacks where an attacker can manipulate encrypted messages to gain information about the plaintext. This vulnerability is particularly dangerous because textbook RSA encryption is deterministic, meaning the same plaintext always produces the same ciphertext, which can leak information through pattern analysis.

Remediation:

Consider using RSA with OAEP padding by specifying "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" when calling Cipher.getInstance(). OAEP padding adds randomness to the encryption process, ensuring that identical plaintexts produce different ciphertexts and preventing chosen plaintext attacks. For compatibility with older systems that may not support SHA-256, you can use "RSA/ECB/OAEPWithSHA-1AndMGF1Padding", though SHA-256 is recommended for new applications. Be aware that RSA encryption is computationally expensive and should typically only be used to encrypt symmetric keys rather than large amounts of data directly. For more information on OAEP, see https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding and the Java Cryptography Architecture guide at https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-WeakMessageDigest

Summary:

Use of a broken or risky cryptographic algorithm (SHA1/MD5)

Severity: Medium

CWE: CWE-327

Description:

The application uses java.security.MessageDigest.getInstance() or java.security.Signature.getInstance() with weak cryptographic algorithms such as MD2, MD4, MD5, or SHA-1. These hash algorithms are cryptographically broken and vulnerable to collision attacks, where two different inputs can produce the same hash output. MD5 collisions have been practical since 2004, and SHA-1 collisions were demonstrated in 2017 with the SHAttered attack. For password storage specifically, these fast hash functions are additionally vulnerable to brute-force attacks even without collisions, making them unsuitable for protecting user credentials.

Remediation:

For general-purpose hashing and data integrity verification, consider migrating to SHA-256 or SHA-384 by calling MessageDigest.getInstance("SHA-256") or MessageDigest.getInstance("SHA-384"). These algorithms are part of the SHA-2 family and remain secure against collision attacks. For password storage specifically, standard cryptographic hashes are insufficient - instead use purpose-built password hashing algorithms like Argon2id, bcrypt, or PBKDF2 which include salting and key stretching to resist brute-force attacks. Java provides PBKDF2 natively through SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"), while Argon2id and bcrypt require third-party libraries such as Bouncy Castle or Spring Security Crypto. For digital signatures, migrate from MD5withRSA or SHA1withRSA to SHA256withRSA or SHA384withRSA. See the OWASP Password Storage Cheat Sheet for detailed guidance: Password_Storage_Cheat_Sheet.html

OWASP:

  • A6:2017-Security Misconfiguration
  • A04:2021-Insecure Design

java_crypto_rule-WeakTLSProtocol-DefaultHttpClient

Summary:

Improper certificate validation

Severity: Medium

CWE: CWE-295

Description:

The application uses org.apache.http.impl.client.DefaultHttpClient, a deprecated class from Apache HttpComponents that does not verify hostnames during TLS connections by default. This vulnerability allows an attacker performing a man-in-the-middle attack to present a certificate for any domain, and the client will accept it without validation. Even if the attacker's certificate is valid for a different domain, the connection will proceed, enabling the interception of sensitive data or injection of malicious content. The DefaultHttpClient class was deprecated in HttpClient 4.3 (released in 2013) specifically due to these security concerns.

Remediation:

For applications running on Java 11 or later, consider migrating to the modern java.net.http.HttpClient API which was introduced in Java 9 and standardized in Java 11. This built-in HTTP client performs proper hostname verification and certificate validation by default without requiring additional configuration. Create instances using HttpClient.newHttpClient() or HttpClient.newBuilder() for custom configuration. If you must continue using Apache HttpComponents, migrate to the modern HttpClient 5.x library and use HttpClients.createDefault() or HttpClients.custom() which both enable proper hostname verification. For HttpClient 4.x, use HttpClientBuilder.create().build() instead of DefaultHttpClient. Be aware that any custom SSL configuration should explicitly maintain hostname verification - never disable it in production environments as this completely negates TLS security guarantees.

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-WeakTLSProtocol-SSLContext

Summary:

Improper certificate validation

Severity: Medium

CWE: CWE-295

Description:

The application initializes an SSL/TLS context using javax.net.ssl.SSLContext.getInstance() with insecure protocol versions such as "SSL", "SSLv2", or "SSLv3". These legacy protocols contain fundamental design flaws and known vulnerabilities including POODLE, BEAST, and padding oracle attacks. SSLv2 and SSLv3 do not properly validate certificates by default and use weak cipher suites that are trivially breakable with modern computing power. Additionally, these protocols are susceptible to downgrade attacks where an attacker can force the connection to use the weakest protocol version supported by both client and server, even if stronger versions are available.

Remediation:

Consider using SSLContext.getInstance("TLSv1.3") or SSLContext.getInstance("TLSv1.2") to explicitly require modern TLS versions. TLS 1.3 is recommended as it removes support for legacy cipher suites, simplifies the handshake process, and encrypts more of the handshake data. If you need to support older clients, TLS 1.2 is acceptable but should be the minimum version allowed. You can also use SSLContext.getInstance("TLS") which will negotiate the highest protocol version available, though this is less explicit and may behave differently across Java versions. For datagram-based protocols, use "DTLSv1.2" or "DTLSv1.3" instead. After creating the SSLContext, you can further restrict enabled protocols using SSLEngine.setEnabledProtocols() or SSLSocket.setEnabledProtocols() to enforce your security policy. For more information, see the OWASP testing guide: 01-Testing_for_Weak_SSL_TLS_Ciphers_Insufficient_Transport_Layer_Protection

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_crypto_rule-WeakTLSProtocolVersion

Summary:

Inadequate encryption strength

Severity: Medium

CWE: CWE-326

Description:

The application enables insecure TLS protocol versions such as TLS 1.0 or TLS 1.1 through SSLContext.getInstance() or by calling setEnabledProtocols() on an SSLEngine or SSLSocket. TLS 1.0 and 1.1 contain numerous cryptographic weaknesses including vulnerability to BEAST attacks, weak cipher suites, and insufficient protection against downgrade attacks. These protocols were formally deprecated by major browser vendors in 2020 and are no longer compliant with PCI DSS requirements as of June 2018. Applications using these versions expose communications to man-in-the-middle attacks where adversaries can intercept the connection and force downgrade to weaker protocol versions or cipher suites. Note that while newer Java versions (Java 8u291+ and Java 11.0.11+) disable TLS 1.0 and 1.1 by default, relying on system defaults is insufficient for compliance when applications may be deployed across diverse environments with varying Java versions and configurations.

Remediation:

Consider explicitly configuring your SSLContext to use only TLS 1.2 and TLS 1.3 by calling SSLContext.getInstance("TLSv1.3") or creating a generic TLS context and then restricting enabled protocols with setEnabledProtocols(new String[] {"TLSv1.2", "TLSv1.3"}) on the SSLEngine or SSLSocket. TLS 1.3 is recommended as it offers improved security and performance over TLS 1.2, including forward secrecy by default and faster handshakes. If you must support older clients, TLS 1.2 should be the absolute minimum version allowed. For datagram protocols, use DTLSv1.2 or DTLSv1.3 equivalents. Explicitly defining the protocol configuration ensures consistent security posture across all deployment environments regardless of Java version or system defaults. After making this change, test thoroughly with all clients to ensure compatibility, as some legacy systems may not support modern TLS versions and will fail to connect. See the SSLContext documentation at https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/net/ssl/SSLContext.html and OWASP's MiTM attack guide at https://owasp.org/www-community/attacks/Manipulator-in-the-middle_attack

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_endpoint_rule-HostnameVerifier

Summary:

Improper certificate validation

Severity: Medium

CWE: CWE-295

Description:

The HostnameVerifier.verify() method has been implemented to always return true, which effectively disables hostname validation during TLS/SSL certificate verification. This implementation allows any hostname to be accepted, even if it does not match the certificate's Subject Alternative Names (SAN) or Common Name (CN) fields. This could allow an adversary positioned between the application and the target host to launch a Man-in-the-Middle (MITM) attack, intercepting potentially sensitive information or injecting malicious content into the communication stream.

Remediation:

Consider using the default HostnameVerifier provided by the Java runtime instead of implementing a custom one that bypasses validation. The default verifier can be obtained via HttpsURLConnection.getDefaultHostnameVerifier() and properly validates that the server's certificate hostname matches the requested hostname according to RFC 2818 standards. For applications using HttpsURLConnection, simply avoid calling setHostnameVerifier() or explicitly set it to the default: connection.setHostnameVerifier( HttpsURLConnection.getDefaultHostnameVerifier()). If you absolutely must implement custom hostname verification logic for specific business requirements, ensure the implementation performs proper wildcard matching and checks the certificate's SAN entries, throwing an exception when validation fails rather than returning true unconditionally. For more information on TLS security, see https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html

OWASP:

  • A6:2017-Security Misconfiguration
  • A05:2021-Security Misconfiguration

java_endpoint_rule-X509TrustManager

Summary:

Improper certificate validation

Severity: Medium

CWE: CWE-295

Description:

The custom implementation of X509TrustManager has empty implementations of checkClientTrusted() or checkServerTrusted() methods, or returns null from getAcceptedIssuers(). This effectively disables certificate chain validation, accepting all certificates regardless of their authenticity or trust chain. This implementation allows an adversary positioned between the application and the target host to present fraudulent certificates and launch Man-in-the-Middle (MITM) attacks, enabling interception of potentially sensitive information or injection of malicious content into the communication stream.

Remediation:

Consider using the default TrustManagerFactory provided by the Java runtime instead of implementing a custom X509TrustManager. The default trust manager can be obtained via TrustManagerFactory.getInstance(TrustManagerFactory. getDefaultAlgorithm()) and properly validates certificate chains against the system's trusted CA certificates. Initialize it with trustManagerFactory.init( (KeyStore) null) to use the default system keystore, then pass the resulting trust managers to SSLContext.init() when creating TLS connections. If you must implement custom certificate validation for specific requirements (such as certificate pinning), ensure that checkServerTrusted() and checkClientTrusted() methods perform actual validation and throw CertificateException when certificates are invalid rather than silently accepting all certificates. Recommended to extend the default trust manager and add additional checks rather than replacing validation entirely. For certificate pinning scenarios, consider using established libraries like OkHttp's CertificatePinner which provide safer abstractions. For more information, see https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html

OWASP:

  • A6:2017-Security Misconfiguration
  • A05:2021-Security Misconfiguration

java_inject_rule-HttpParameterPollution

Summary:

Improper neutralization of argument delimiters in a command ('Argument Injection')

Severity: Medium

CWE: CWE-88

Description:

The application uses Apache HttpClient classes such as org.apache.http.client.methods.HttpGet or org.apache.commons.httpclient.methods.GetMethod.setQueryString() with user-controlled input which enables HTTP Parameter Pollution (HPP) and potentially Server-Side Request Forgery (SSRF) attacks. When user input is incorporated into URL construction without proper encoding or validation, adversaries can inject encoded query string delimiters like &, =, or %26 to add or override URL parameters, manipulating the logic of backend requests. This vulnerability becomes particularly severe when it enables SSRF, allowing attackers to make requests to internal services, cloud metadata endpoints, or arbitrary external systems using the application server as a proxy.

Remediation:

Consider using a lookup table approach where user input is validated against a HashMap of permitted parameter values, then using only those validated values when constructing HTTP requests. Never allow user input to control the base URL or full URL path - always hardcode the destination host and path, using user input only for validated parameter values. When user input must be included in URLs, use java.net.URLEncoder.encode() with StandardCharsets.UTF_8 to properly escape all special characters before URL construction. For modern applications, consider using URI builder classes like URIBuilder from Apache HttpClient or Spring's UriComponentsBuilder which provide safer parameter handling with automatic encoding. Implement strict allowlist validation for any user-controlled input used in HTTP requests, and never trust user input to provide full URLs or hosts. For SSRF prevention, maintain an allowlist of permitted destination hosts and validate that all constructed URLs resolve to approved targets. Consider making outbound HTTP requests asynchronously in separate threads or using message queues to isolate them from the request handling context. More information at https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_inject_rule-LDAPInjection

Summary:

Improper neutralization of special elements used in an LDAP query ('LDAP Injection')

Severity: Medium

CWE: CWE-90

Description:

The application uses LDAP query methods such as InitialDirContext.search(), DirContext.lookup(), LdapContext.search(), LdapTemplate.search(), or LDAPConnection.search() with user-controlled input which enables LDAP injection attacks. LDAP injection exploits allow adversaries to manipulate LDAP filter syntax by injecting special characters like parentheses, asterisks, or null bytes, potentially bypassing authentication, accessing unauthorized directory entries, or extracting sensitive information. The vulnerability is particularly critical when constructing LDAP filters or distinguished names (DNs) using string concatenation with unsanitized user input, as this allows attackers to alter the logical structure of LDAP queries.

Remediation:

Consider using the four-argument InitialDirContext.search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) method which automatically encodes the filterArgs parameter to prevent injection. When using this method, use placeholders like {0}, {1} in the filter expression and pass user input via the filterArgs array rather than concatenating strings. For applications that cannot use the parameterized method, manually encode LDAP special characters: escape backslashes as \5c, null bytes as \00, parentheses as \28 and \29, and asterisks as \2a (note that backslash must be escaped first). Spring LDAP's LdapEncoder.nameEncode() and LdapEncoder.filterEncode() provide built-in encoding for DN and filter components respectively. Consider implementing an allowlist validation for LDAP attribute names and base DNs, and avoid constructing DNs from user input when possible. For UnboundID LDAP SDK, use Filter.create() with proper argument escaping or the Filter class builder methods which handle encoding automatically. More guidance available at https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_inject_rule-SpotbugsPathTraversalAbsolute

Summary:

Improper limitation of a pathname to a restricted directory ('Path Traversal')

Severity: Medium

CWE: CWE-22

Description:

The application uses file system APIs such as new File(), new FileReader(), new FileInputStream(), new FileOutputStream(), Files.newBufferedReader(), Paths.get(), or ClassLoader.getResourceAsStream() with user-controlled input which enables path traversal attacks. When user input is used to construct file paths without proper validation, adversaries can inject path traversal sequences like ../ or absolute paths to access files outside the intended directory, read sensitive configuration files, access other users' data, or overwrite critical system files. This vulnerability is particularly dangerous when processing user-uploaded filenames or when file paths are constructed from HTTP parameters, as attackers can traverse to arbitrary locations in the filesystem.

Remediation:

Consider generating random filenames using UUID.randomUUID() and storing the original user-provided filename separately in a database or metadata file, then using only the generated filename for file system operations. When user input must influence file paths, use Path.resolve() to construct the full path from a hardcoded base directory and the user input, then validate that fullPath.startsWith(basePath) to ensure the resolved path remains within the intended directory. For extracting just the filename from user input, use org.apache.commons.io.FilenameUtils.getName() which strips directory components and prevents traversal. Never use string concatenation to build file paths with user input. Consider using Path.normalize() to resolve .. sequences, but note this alone is insufficient - you must also validate the normalized path stays within bounds. For temporary file operations, use Files.createTempFile() with a prefix/suffix rather than user-controlled names. Implement strict allowlist validation if you must support user-specified filenames, permitting only alphanumeric characters and a limited set of safe characters. Consider using a chroot jail or containerization to limit filesystem access scope. More details at https://owasp.org/www-community/attacks/Path_Traversal

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_perm_rule-DangerousPermissions

Summary:

Incorrect permission assignment for critical resource

Severity: Medium

CWE: CWE-732

Description:

Detected dangerous permissions granted via PermissionCollection.add(). Granting RuntimePermission("createClassLoader") allows a compromised application to instantiate arbitrary class loaders and load malicious classes, bypassing security controls. Granting ReflectPermission("suppressAccessChecks") disables Java language access checks, allowing unrestricted access to private and protected members of any class through reflection.

Remediation:

Consider removing these highly privileged permissions from your security policy. If class loading or reflection access is required, implement fine-grained security controls using a custom SecurityManager and restrict permissions to specific trusted code paths. Recommended to use the principle of least privilege by granting only the minimum permissions necessary for legitimate functionality. Avoid adding these permissions to PermissionCollection unless absolutely required by your application's security architecture.

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_perm_rule-OverlyPermissiveFilePermissionInline

Summary:

Incorrect permission assignment for critical resource

Severity: Medium

CWE: CWE-732

Description:

Detected overly permissive file permissions set via Files.setPosixFilePermissions() with "others" having read, write, or execute access. This allows any user on the system to access the file, potentially exposing sensitive data or enabling unauthorized modifications. Granting world-readable or world-writable permissions violates the principle of least privilege and creates security vulnerabilities.

Remediation:

Consider restricting file permissions to only the file owner using PosixFilePermissions.fromString() with patterns like "rw-------" (read/write for owner only) or "r--------" (read-only for owner). Recommended to avoid granting any permissions to the "others" group (last three characters should be "---"). If group access is required, limit it to the minimum necessary (e.g., "rw-r-----" for group read access). Review your application's file access requirements and apply the most restrictive permissions that maintain functionality.

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_smtp_rule-InsecureSmtp

Summary:

Improper validation of certificate with host mismatch

Severity: Medium

CWE: CWE-297

Description:

The Apache Commons Email client does not enable SSL server identity verification by default when using SimpleEmail, MultiPartEmail, HtmlEmail, or ImageHtmlEmail classes. Without calling setSSLCheckServerIdentity(true), the application accepts any certificate presented by the SMTP server, allowing man-in-the-middle attackers to intercept or modify email communications containing potentially sensitive information.

Remediation:

Consider enabling SSL server identity verification to prevent man-in-the-middle attacks on SMTP connections. After calling setSSLOnConnect(true) on your Email instance, immediately call setSSLCheckServerIdentity(true) to ensure the server certificate matches the hostname. Recommended to use both methods together: email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true);. This validates that the SMTP server's certificate is trusted and matches the expected hostname, protecting against certificate substitution attacks.

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

java_ssrf_rule-SSRF

Summary:

Server-Side Request Forgery (SSRF)

Severity: Medium

CWE: CWE-918

Description:

This rule detected user-controlled input being used to construct Java network connections through java.net.URL, java.net.URI, or java.net.InetSocketAddress without proper validation. The patterns identify cases where non-literal values are passed to constructors like new URL(), new URI(), or new InetSocketAddress(), followed by methods such as connect(), openConnection(), openStream(), or getContent(). When user input controls URLs or hostnames in these network operations, Server-Side Request Forgery (SSRF) vulnerabilities arise that allow attackers to force the server to access internal resources, cloud metadata endpoints (169.254.169.254), administrative interfaces, or perform network scanning that bypasses firewall protections and network segmentation.

Remediation:

Consider implementing a strict URL allowlist that validates user input against approved domains before constructing URL or URI objects. Use Java's java.net.URI class to parse and validate the scheme, host, and port components, rejecting any URLs that don't match the allowlist. Implement DNS rebinding protection by resolving hostnames using InetAddress.getByName() and blocking connections to private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and cloud metadata addresses (169.254.169.254). For applications using Apache HttpClient, configure custom connection managers or socket factories that enforce IP address filtering at the network layer. Network-level defenses can include running the application with restricted user privileges or in isolated network segments with egress filtering rules. Consider using a server-side mapping approach where user input provides keys that map to pre-configured safe URLs rather than accepting arbitrary URLs. For more information see OWASP: Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html

OWASP:

  • A1:2017-Injection
  • A10:2021-Server-Side Request Forgery

java_strings_rule-FormatStringManipulation

Summary:

Use of externally-controlled format string

Severity: Medium

CWE: CWE-134

Description:

The application uses untrusted user input from HttpServletRequest.getParameter() to construct format strings passed to String.format(), Formatter.format(), PrintStream.printf(), or PrintStream.format(). This allows attackers to inject arbitrary format specifiers that can cause denial of service through exceptions, consume excessive resources through format bombs, or potentially leak sensitive information through carefully crafted format strings. Format string vulnerabilities occur when the format string itself (the first parameter) contains user-controlled data, not when user data is safely passed as format arguments.

Remediation:

Recommended to always use hardcoded format strings with user input passed only as format arguments, never concatenated into the format string itself. For example, use String.format("User provided: %s", userInput) instead of String.format("User provided: " + userInput, args). Consider using simple string concatenation or StringBuilder when format specifiers are not actually needed, as this eliminates the format string attack surface entirely. If dynamic string templates are required, consider using a safe templating library like Apache Commons Text's StringSubstitutor which does not interpret format specifiers. For logging scenarios, prefer using parameterized logging frameworks like SLF4J where placeholders are safe by design: logger.info("User action: {}", userInput).

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_xml_rule-SAMLIgnoreComments

Summary:

Weak authentication

Severity: Medium

CWE: CWE-1390

Description:

The application calls BasicParserPool.setIgnoreComments(false) when configuring OpenSAML XML parsing, which enables processing of XML comments within SAML attestations. SAML parses attestations as XML documents, and by processing XML comments, adversaries can insert XML comment tags to break up critical fields like usernames or assertions. This allows attackers to bypass authorization or authentication checks by manipulating how the SAML response is interpreted, potentially leading to authentication bypass vulnerabilities as demonstrated in CVE-2017-11427 and CVE-2018-0489.

Remediation:

Consider removing the explicit setIgnoreComments(false) call when configuring org.opensaml.xml.parse.BasicParserPool, as the default value of ignoreComments is true, which is the secure configuration. If you must explicitly configure comment handling, use setIgnoreComments(true) to ensure XML comments are stripped during parsing and cannot be used to manipulate SAML assertions. For comprehensive SAML security, also ensure you validate signatures before processing assertions, canonicalize XML before signature verification, and implement proper certificate validation. Additional guidance is available in the OWASP SAML Security Cheat Sheet at https://cheatsheetseries.owasp.org/cheatsheets/SAML_Security_Cheat_Sheet.html and details on this specific vulnerability at https://developer.okta.com/blog/2018/02/27/a-breakdown-of-the-new-saml-authentication-bypass-vulnerability

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_xml_rule-XsltTransform

Summary:

XML injection (aka Blind XPath injection)

Severity: Medium

CWE: CWE-91

Description:

The application performs XSLT transformation using TransformerFactory.newTransformer() or Transformer.transform() with potentially untrusted input sources. When adversaries can influence the loaded XSL stylesheet, they can exploit XSLT's extensive functionality to execute arbitrary code through extension functions, read local files via document() calls, or trigger External XML Entity (XXE) attacks that exfiltrate sensitive data to attacker-controlled servers. XSLT is a Turing-complete language with powerful capabilities including file system access and network operations, making user-controlled stylesheets particularly dangerous. Even seemingly benign transformations can be weaponized when attackers control the XSL template.

Remediation:

Consider migrating away from XSLT entirely if possible, using safer alternatives like template engines (Thymeleaf, Velocity) or modern XML processing libraries that don't execute code. If XSLT processing is absolutely necessary, never process user-supplied XSL stylesheets under any circumstances. For required XSLT operations, ensure you enable FEATURE_SECURE_PROCESSING by calling transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) before creating transformers, which restricts extension functions and limits resource access. Additionally, explicitly disable external entity resolution and DTD processing on your TransformerFactory by setting the ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET properties to empty strings. Store all XSL stylesheets as hardcoded application resources, never load them from user input or external sources, and validate that file paths cannot be manipulated through path traversal. More details on XML security are available at https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_xss_rule-WicketXSS

Summary:

Improper neutralization of input during web page generation ('Cross-site Scripting')

Severity: Medium

CWE: CWE-79

Description:

The application is disabling Apache Wicket's built-in HTML escaping by calling Component.setEscapeModelStrings(false) on Wicket components. This creates a Cross-Site Scripting (XSS) vulnerability when the component displays user-supplied data, as malicious JavaScript or HTML markup will be rendered directly in the browser without sanitization. Wicket's default auto-escaping protects against XSS by encoding HTML special characters, and disabling this protection removes a critical security control. This is particularly dangerous in Label components, dynamic panels, or any component that renders user input in web pages.

Remediation:

Consider keeping Wicket's default auto-escaping enabled by ensuring Component.setEscapeModelStrings(true) is used or relying on the default behavior which automatically escapes HTML. If you need to render rich HTML content from trusted sources, consider using Wicket's Label component with explicit model validation rather than disabling escaping globally. For user-generated content that must include formatting, use a whitelist-based HTML sanitizer library like OWASP Java HTML Sanitizer or Jsoup with a restrictive allowlist before passing content to Wicket components. Additionally, implement Content Security Policy (CSP) headers to provide defense-in-depth against XSS even if escaping is bypassed. See the Wicket Component API documentation at https://nightlies.apache.org/wicket/apidocs/9.x/org/apache/wicket/Component.html for proper usage of escaping features.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_xss_rule-XSSReqParamToServletWriter

Summary:

Improper neutralization of input during web page generation ('Cross-site Scripting')

Severity: Medium

CWE: CWE-79

Description:

The application is writing user-supplied data from HTTP request parameters directly to the HTTP response via HttpServletResponse.getWriter().write(), HttpServletResponse.getWriter().print(), or similar servlet writer methods. This creates a reflected Cross-Site Scripting (XSS) vulnerability where attackers can inject malicious JavaScript by crafting request parameters that are echoed back in the HTTP response without HTML encoding. This pattern detects taint flow from sources like HttpServletRequest.getParameter(), file inputs, database result sets, and other untrusted data sources to servlet output sinks. Without proper output encoding, malicious scripts embedded in request parameters will execute in victims' browsers, potentially leading to session hijacking, credential theft, or defacement attacks.

Remediation:

Consider using context-aware output encoding before writing to the servlet response. For HTML contexts, use org.apache.commons.text.StringEscapeUtils.escapeHtml4() or the OWASP Java Encoder's Encode.forHtml() to escape user input before passing it to the writer. If writing plain text responses, set the Content-Type to text/plain and character encoding to UTF-8 with response.setContentType("text/plain; charset=UTF-8") to prevent browsers from interpreting output as HTML. For modern applications, prefer using template engines like JSP, Thymeleaf, or FreeMarker which provide automatic context-aware escaping instead of manually writing to servlet output streams. For JavaScript, CSS, or URL contexts, use specialized encoding functions from OWASP Java Encoder (Encode.forJavaScript(), Encode.forCssString(), Encode.forUriComponent()). Implement Content Security Policy (CSP) headers as an additional defense layer.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_xxe_rule-XMLRdr

Summary:

Improper restriction of XML external entity reference ('XXE')

Severity: Medium

CWE: CWE-611

Description:

The application uses XMLReaderFactory.createXMLReader() to create an XML parser without disabling external entity processing, making it vulnerable to XML External Entity (XXE) attacks. When an XML parser processes untrusted XML input with external entity support enabled, attackers can exploit this to read arbitrary files from the server, perform Server-Side Request Forgery (SSRF) attacks to internal systems, exfiltrate sensitive data, or cause Denial of Service through billion laughs attacks. The XMLReaderFactory class has been deprecated and should be replaced with SAXParserFactory, which provides better security configuration options.

Remediation:

Migrate to SAXParserFactory instead of the deprecated XMLReaderFactory and configure it to disable DOCTYPE declarations entirely using setFeature("http://apache.org/xml/features/disallow-doctype-decl", true). This feature prevents XXE attacks, entity expansion attacks, and billion laughs DoS vulnerabilities by blocking all DTD processing. Alternatively, enable XMLConstants.FEATURE_SECURE_PROCESSING to apply multiple security restrictions. Example: SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); SAXParser parser = factory.newSAXParser(); parser.parse(inputStream, handler); Additional security guidance available at https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

rules_lgpl_java_webview_rule-ignore-ssl-certificate-errors

Summary:

Improper certificate validation"

Severity: Medium

CWE: CWE-295

Description:

The application's WebViewClient implementation calls SslErrorHandler.proceed() within the onReceivedSslError() callback, which bypasses SSL/TLS certificate validation. This allows the WebView to accept invalid, self-signed, expired, or attacker-controlled certificates, making the application vulnerable to Man-in-the-Middle (MitM) attacks where an attacker can intercept and manipulate all communication between the app and the server. Any sensitive data transmitted through the WebView, including credentials, session tokens, or personal information, can be compromised when SSL validation is bypassed.

Remediation:

Consider calling handler.cancel() instead of handler.proceed() in the onReceivedSslError() callback to reject connections with invalid certificates. The recommended approach is to override onReceivedSslError() and call handler.cancel() for all SSL errors (SSL_UNTRUSTED, SSL_EXPIRED, SSL_IDMISMATCH, SSL_NOTYETVALID, etc.), which prevents the WebView from loading content over insecure connections. For development environments that require testing with self-signed certificates, recommended to use proper certificate pinning or add development certificates to the Android trust store rather than disabling validation in production code. If your application must handle specific SSL error types differently, carefully validate each error case and document the business justification, ensuring that production builds never accept untrusted certificates.

OWASP:

  • A3:2017-Sensitive Data Exposure
  • A02:2021-Cryptographic Failures

rules_lgpl_java_webview_rule-webview-debugging

Summary:

Active debug code

Severity: Medium

CWE: CWE-489

Description:

The application calls WebView.setWebContentsDebuggingEnabled(true) which enables remote Chrome DevTools debugging for all WebView instances in the application. This feature allows anyone with physical access to the device or access to the debug bridge (ADB) to inspect, modify, and extract data from WebViews, including sensitive information such as session tokens, credentials, personal data, and business logic. An attacker with debugging access can execute arbitrary JavaScript, intercept network requests, dump local storage contents, and manipulate the DOM to bypass client-side security controls.

Remediation:

Recommended to call WebView.setWebContentsDebuggingEnabled(false) or completely remove the call to this method, as debugging is disabled by default on API level 19 (KitKat) and above. If debugging must be enabled for development builds, consider using BuildConfig flags to conditionally enable it only in debug builds: if (BuildConfig.DEBUG) { WebView.setWebContentsDebuggingEnabled(true); }. This ensures that production APKs released to end users never have WebView debugging enabled. For troubleshooting production issues, recommended to implement proper logging and crash reporting mechanisms rather than relying on remote debugging capabilities. Note that this setting applies globally to all WebView instances in the application process, so a single call affects the entire app's security posture.

OWASP:

  • A6:2017-Security Misconfiguration
  • A05:2021-Security Misconfiguration

rules_lgpl_java_webview_rule-webview-set-allow-file-access

Summary:

External control of file name or path

Severity: Medium

CWE: CWE-73

Description:

The application calls WebSettings.setAllowFileAccess(true) which enables the WebView to load content from file:// URLs. When file access is enabled, any JavaScript code running in the WebView can potentially access local files on the device's filesystem, including files in the app's private directory and external storage (depending on other settings). If an attacker can inject malicious JavaScript through XSS or load untrusted web content, they may be able to read sensitive files such as databases, shared preferences, cached credentials, or other app data using file:// URLs combined with XMLHttpRequest or fetch API calls.

Remediation:

Recommended to call webView.getSettings().setAllowFileAccess(false) to disable file:// URL access in the WebView. Note that starting from Android 11 (API level 30), file access is disabled by default, but it remains enabled by default on earlier Android versions. If your application must load local HTML content, consider packaging it in the assets directory and using file:///android_asset/ URLs, which provide controlled access to bundled resources without enabling arbitrary filesystem access. For user-generated or downloaded content, recommended to use ContentProvider with content:// URIs or load content via HTTPS from a trusted server. Additionally, ensure that setAllowFileAccessFromFileURLs(false) and setAllowUniversalAccessFromFileURLs(false) are set to prevent file:// URLs from accessing other local files or making cross-origin requests, as these settings provide defense in depth even when file access is enabled.

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

scala_xml_rule-XsltTransform

Summary:

XML injection (aka Blind XPath injection)

Severity: Medium

CWE: CWE-91

Description:

Using TransformerFactory.newTransformer() or Transformer.transform() with XSLT stylesheets from untrusted sources can lead to remote code execution vulnerabilities. XSLT processors support extension functions and external resource loading that attackers can exploit to execute arbitrary code, read sensitive files, or perform server-side request forgery attacks. When the stylesheet source or content is controlled by user input through string concatenation or external file paths, attackers can inject malicious XSLT directives to compromise the application.

Remediation:

Consider implementing strict input validation and avoiding dynamic construction of XSLT stylesheet paths from user input. Recommended to use a whitelist approach where only predefined, trusted stylesheet files can be loaded from a secure directory. When creating the TransformerFactory, disable external entity processing and extension functions by setting XMLConstants.FEATURE_SECURE_PROCESSING to true and using TransformerFactory.setFeature() to disable dangerous features. For applications requiring dynamic transformations, consider using template engines like FreeMarker or Thymeleaf that provide better security controls. If XSLT must be used with user-provided content, implement content security policies, run transformations in sandboxed environments with restricted permissions, and validate all output before using it in security-sensitive contexts.


Summary:

Sensitive cookie in HTTPS session without 'Secure' attribute

Severity: Low

CWE: CWE-614

Description:

The application creates a javax.servlet.http.Cookie object without calling setSecure(true) before adding it to the HttpServletResponse. The Secure attribute when set to true protects the cookie value from being transmitted over clear text communication paths such as HTTP, ensuring the cookie will only be sent over HTTPS. Without this protection, session cookies and other sensitive cookie data could be intercepted by attackers performing network-level eavesdropping attacks.

Remediation:

Consider calling setSecure(true) on all Cookie objects before adding them to the response via addCookie(). This ensures cookies are only transmitted over encrypted HTTPS connections. For example: Cookie cookie = new Cookie("session", value); cookie.setSecure(true); response.addCookie(cookie);. In addition to the Secure flag, session cookies should also be configured with setHttpOnly(true) to prevent JavaScript access and consider using SameSite attributes to mitigate CSRF attacks. For modern Spring Boot applications, you can configure these globally via server.servlet.session.cookie.secure=true in application properties. More details at https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/http/cookie#setSecure-boolean-

OWASP:

  • A6:2017-Security Misconfiguration
  • A05:2021-Security Misconfiguration

java_cors_rule-PermissiveCORSInjection

Summary:

Permissive cross-domain policy with untrusted domains

Severity: Low

CWE: CWE-942

Description:

The application allows user-supplied input to control the value of the Access-Control-Allow-Origin response header via HttpServletResponse.setHeader or HttpServletResponse.addHeader. This header is part of the Cross-Origin Resource Sharing (CORS) specification that determines which external domains can access resources on this server. By allowing user input to specify trusted domains, an adversary could exploit this weakness to force clients to send credentials (such as session identifiers or cookies) to the adversary's server. This vulnerability becomes exploitable when combined with other weaknesses such as Cross-Site Scripting (XSS), enabling attackers to bypass same-origin policy protections and steal sensitive data.

Remediation:

Consider avoiding the use of user-supplied input when setting the Access-Control-Allow-Origin header value in HttpServletResponse.setHeader or HttpServletResponse.addHeader. Recommended to maintain a hardcoded allowlist of trusted domains and use a lookup mechanism to validate and select the appropriate domain. This approach ensures that only explicitly approved domains can be set in the CORS header, preventing attackers from injecting malicious origins. Consider implementing domain validation by maintaining a Map or Set of allowed domains and using the user input only as a key to look up the trusted value, rather than directly inserting it into the header.

Example of implementing a safe allowlist-based CORS header configuration:

// Define allowed domains in constructor or from a trusted configuration source
Map<String, String> allowedDomains = new HashMap();
allowedDomains.put("sub1", "sub1.example.com");
allowedDomains.put("sub2", "sub2.example.com");

// Use user input only as a lookup key, with a safe default fallback
String headerValue = allowedDomains.getOrDefault(
  request.getParameter("allowedDomain"),
  allowedDomains.get("sub1")
);

// Set the header with a validated, trusted domain value
response.addHeader("Access-Control-Allow-Origin", headerValue);

For more information on secure CORS configuration, see: Access-Control-Allow-Origin

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_smtp_rule-SmtpClient

Summary:

Improper neutralization of special elements used in a command

Severity: Low

CWE: CWE-77

Description:

The application calls MimeMessage methods (setSubject, addHeader, setDescription, or setDisposition) with user-controlled data that may contain CRLF sequences (\r\n). SMTP is a text-based protocol that uses headers to control email routing and metadata. An attacker can inject CRLF sequences to add arbitrary email headers (such as CC, BCC, or additional recipients), causing messages to be sent to unintended recipients or bypassing security controls.

Remediation:

Consider sanitizing all user-controlled input before passing it to MimeMessage methods to prevent email header injection attacks. Recommended to remove or encode CRLF sequences (\r and \n characters) from any untrusted data used in setSubject(), addHeader(), setDescription(), or setDisposition(). You can use StringEscapeUtils.escapeJava() from Apache Commons Text, or implement validation that rejects inputs containing these characters. This prevents attackers from injecting additional email headers that could redirect messages.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_unsafe_rule-ExternalConfigControl

Summary:

External control of system or configuration setting

Severity: Low

CWE: CWE-15

Description:

The application uses user-supplied input in java.sql.Connection.setCatalog() calls, allowing adversaries to supply a different database catalog for the connection lifetime. External control of system settings can disrupt service or cause unexpected and potentially malicious application behavior.

Remediation:

Consider using hardcoded database catalog names instead of accepting user input for setCatalog() calls. Recommended to define allowed catalog names in application configuration and validate against a whitelist before use. Never pass user-supplied input directly from HttpServletRequest.getParameter() to Connection.setCatalog(). If dynamic catalog selection is required, use an enumeration or mapping table to translate user input to safe, predefined values.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_endpoint_rule-UnvalidatedRedirect

Summary:

URL redirection to untrusted site ('Open Redirect')

Severity: Info

CWE: CWE-601

Description:

The application uses HttpServletResponse.sendRedirect() or HttpServletResponse.addHeader("Location", ...) with user-supplied input from HttpServletRequest methods such as getParameter(), getHeader(), or getRequestURI() without proper validation. This creates an unvalidated redirect vulnerability where an attacker can craft malicious URLs that redirect users to arbitrary external sites. Such vulnerabilities are commonly exploited in phishing attacks, where victims believe they are navigating to a trusted domain but are instead redirected to an attacker-controlled site designed to steal credentials or deliver malware.

Remediation:

Consider implementing an allowlist approach where redirect URLs are validated against a predefined collection (such as List<String> or Set<String>) of safe destination paths before calling sendRedirect(). For example, maintain a list of approved redirect targets like /home, /dashboard, /user/profile and only redirect when safeUrls.contains(redirectUrl) returns true, otherwise redirect to a safe default page. Recommended to use relative paths (starting with /) rather than absolute URLs to prevent redirects to external domains entirely. If your application must support dynamic redirects, validate that the destination URL belongs to your application's domain by parsing the URL and checking the hostname matches your expected domain(s). For applications using Spring Security, consider leveraging RedirectStrategy with domain validation or using the @Valid annotation with custom validators. Avoid using request parameters directly in redirect operations without thorough validation and sanitization.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_file_rule-FileUploadFileName

Summary:

Improper limitation of a pathname to a restricted directory ('Path Traversal')

Severity: Info

CWE: CWE-22

Description:

The filename obtained from Part.getSubmittedFileName() or FileItem.getName() can be tampered with by the client, which could lead to path traversal vulnerabilities, unauthorized file access, or arbitrary file inclusion. Client-provided filenames are untrusted input and may contain malicious path characters (such as forward slashes /, backslashes \, or path traversal sequences ../ or ..\) that could allow attackers to write files outside the intended directory or access restricted files.

Remediation:

Consider conducting rigorous validation of filenames provided by clients to ensure they adhere to a predefined structure, are devoid of potentially dangerous characters, and correspond to authorized files only. Recommended strategies include: (1) Sanitize filenames by creating a function to remove or replace unauthorized characters, including path traversal sequences (../ or ..\). For example, use Paths.get(fileName).getFileName() to strip directory components. (2) Implement allowlist validation, allowing only filenames that match a specific pattern such as [a-zA-Z0-9._-]+. (3) Consider generating unique filenames server-side using UUID.randomUUID() rather than relying on client-provided names for storing files. (4) Verify file paths using Path.resolve() and ensure files are being saved in the correct intended directory to prevent redirection to unauthorized directories.

Example remediation:

public class FileUploadHandler {
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
          throws ServletException, IOException {

        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();

        // Removes any path information from the filename
        String sanitizedFileName = sanitizeFileName(fileName);
        if (!isFileNameAllowed(sanitizedFileName)) {
            throw new SecurityException("Invalid file name");
        }

        // Generate a unique file name for storage
        String storedFileName = UUID.randomUUID().toString() + ".txt";

        Path targetPath = Paths.get("uploads").resolve(storedFileName);
        Files.copy(filePart.getInputStream(), targetPath,
                   StandardCopyOption.REPLACE_EXISTING);
    }

    private String sanitizeFileName(String fileName) {
        return Paths.get(fileName).getFileName().toString();
    }

    private boolean isFileNameAllowed(String fileName) {
        return fileName.matches("[a-zA-Z0-9._-]+");
    }
}

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_file_rule-FilenameUtils

Summary:

Improper limitation of a pathname to a restricted directory ('Path Traversal')

Severity: Info

CWE: CWE-22

Description:

User-controlled input is being passed to Apache Commons IO FilenameUtils methods such as FilenameUtils.concat(), FilenameUtils.normalize(), or FilenameUtils.getFullPath() without proper validation. When untrusted data from sources like HttpServletRequest parameters is used to construct file paths, attackers can leverage path traversal sequences (e.g., ../ or ..\) to access or manipulate files outside the intended directory. This can lead to unauthorized file access, information disclosure, or arbitrary file operations on restricted filesystem locations.

Remediation:

Consider treating all user input as potentially malicious and implementing an "accept known good" input validation strategy. Recommended approaches include: (1) Use FilenameUtils.getName() to extract only the filename component, which strips any directory path information before using it with FilenameUtils.concat() to safely combine with a base directory. (2) Consider validating file paths using Path.resolve() combined with Path.startsWith() to verify that the resolved path remains within the intended base directory, throwing an exception if validation fails. (3) Implement allowlist validation to ensure filenames match expected patterns and contain only authorized characters. For example, if the application constructs paths like "images/userprofiles/" + username, a malicious input such as "../../../etc/passwd" could allow unauthorized access to sensitive files.

Example of limiting path traversal using getName():

protected void doPut(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String input = req.getHeader("input");

    // Extract only the filename, removing any path components
    input = FilenameUtils.getName(input);

    String safePath = FilenameUtils.concat(basePath, input);

    // Read the contents of the file
    File file = new File(safePath);
}

Example of path validation using resolve() and startsWith():

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String userInput = req.getParameter("filename");
    Path basePath = Paths.get("/var/www/uploads");

    Path resolvedPath = basePath.resolve(userInput).normalize();

    if (!resolvedPath.startsWith(basePath)) {
        throw new SecurityException("Path traversal attempt detected");
    }

    File file = resolvedPath.toFile();
}

OWASP:

  • A5:2017-Broken Access Control
  • A01:2021-Broken Access Control

java_inject_rule-ELInjection

Summary:

Improper neutralization of special elements used in an expression language statement ('Expression Language Injection')

Severity: Info

CWE: CWE-917

Description:

The application uses Expression Language (EL) methods such as ExpressionFactory.createValueExpression(), ExpressionFactory.createMethodExpression(), ELProcessor.eval(), ELProcessor.getValue(), or ELProcessor.setValue() with non-hardcoded input which enables EL injection attacks. When createValueExpression() creates a ValueExpression object, it gets evaluated upon calling getValue(), setValue(), or Lambda invoke() methods. Similarly, createMethodExpression() creates a MethodExpression that evaluates when invoke() or getMethodInfo() are called. These evaluation methods can allow adversaries to execute arbitrary Java code including OS commands when user-controlled expressions are processed. EL injection is particularly dangerous because attackers can access the Java runtime environment and execute system commands through reflection.

Remediation:

Consider using an allowlist-based approach where user input is validated against a predefined set of permitted values using Set.contains() or a lookup table before any EL processing occurs. Never pass user-supplied strings directly to EL evaluation methods. When dynamic behavior is required, use ELProcessor.defineBean() to bind pre-validated data objects to the EL context, then reference these beans in hardcoded EL expressions rather than constructing expressions from user input. For displaying user data in JSP or JSF views, use standard JSTL tags like <c:out> which automatically escape output, or set beans via managed bean properties rather than evaluating user-provided expression strings. If you must support some dynamic configuration, implement a strict parser that only allows accessing specific bean properties with no method invocation capabilities. Ensure your application uses the latest version of the EL implementation to benefit from security patches and enhanced sandboxing features.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_strings_rule-BadHexConversion

Summary:

Incorrect type conversion or cast

Severity: Info

CWE: CWE-704

Description:

The application is using Integer.toHexString() to convert digest byte arrays from MessageDigest.digest() into hexadecimal strings, which can produce incorrect results when byte values have leading zeros. The Integer.toHexString() method omits leading zeros for byte values less than 0x10, resulting in single-character hex representations instead of the required two-character format. This leads to malformed hash strings that cannot be correctly compared or validated, potentially causing security vulnerabilities in authentication, integrity checking, or signature verification systems.

Remediation:

Consider migrating to java.util.HexFormat introduced in Java 17, which provides a reliable and efficient method for hex encoding with proper zero-padding. For applications running on Java versions prior to 17, recommended alternatives include javax.xml.bind.DatatypeConverter.printHexBinary() or Apache Commons Codec's Hex.encodeHexString(). The HexFormat.of().formatHex(byteArray) approach is preferred for modern applications as it handles all edge cases correctly and produces lowercase hex strings by default. When using DatatypeConverter, be aware it produces uppercase hex strings and was deprecated in Java 9 though remains available in Java 11. For maximum compatibility across Java versions, Apache Commons Codec provides consistent behavior and is widely tested in production environments.

OWASP:

  • A6:2017-Security Misconfiguration
  • A05:2021-Security Misconfiguration

java_strings_rule-ModifyAfterValidation

Summary:

Collapse of data into unsafe value

Severity: Info

CWE: CWE-182

Description:

The application validates a string using Pattern.matcher() and then modifies it using replace(), replaceAll(), replaceFirst(), or concat() after validation. This creates a time-of-check/time-of-use vulnerability where attackers can craft input that passes validation but becomes malicious after modification. For example, validating against ../ and then removing it allows an attacker to submit ..../ which becomes ../ after removal, bypassing the security check. This pattern violates secure coding principle IDS11-J from Carnegie Mellon's CERT guidelines and can lead to path traversal, injection attacks, or other security bypasses depending on the validation context.

Remediation:

Consider always performing string modifications such as replaceAll(), replace(), replaceFirst(), or concat() before applying validation with Pattern.matcher(). The correct sequence is: (1) normalize/sanitize the input, (2) validate the result, (3) use the validated string without further modification. Recommended to use replaceAll() instead of replace() when removing patterns, as single-pass replacement can leave residual malicious content. For path traversal prevention specifically, avoid string manipulation entirely and instead use Path.normalize() followed by validation that the normalized path remains within allowed boundaries using Path.startsWith(). For most security-critical contexts, consider rejecting inputs containing suspicious characters rather than attempting to sanitize them. When modification is necessary, consider using encoding functions like URLEncoder.encode() or context-appropriate escaping instead of removal, as encoding preserves the intent while preventing interpretation. See https://wiki.sei.cmu.edu/confluence/display/java/IDS11-J for detailed guidance.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection

java_strings_rule-NormalizeAfterValidation

Summary:

Incorrect behavior order: validate before canonicalize

Severity: Info

CWE: CWE-180

Description:

The application performs validation using Pattern.matcher() and then calls Normalizer.normalize() after validation has occurred. This creates a security vulnerability where attackers can use Unicode equivalents or compatibility characters to bypass validation. For example, the Unicode character U+FE64 (﹤) normalizes to '<' under NFKC normalization, allowing an attacker to bypass angle bracket validation and inject HTML or XML tags. This violates secure coding principle IDS01-J from Carnegie Mellon's CERT guidelines and can lead to cross-site scripting, injection attacks, or security control bypasses depending on how the validated string is subsequently used.

Remediation:

Recommended to always perform Normalizer.normalize() before validation using Pattern.matcher() or any other validation logic. The correct sequence is: (1) normalize the input using NFKC or NFC form, (2) validate the normalized result, (3) use the validated string. Consider using Normalizer.Form.NFKC for compatibility normalization which converts compatibility characters like full-width and half-width variants to their canonical forms, though be aware this is more aggressive than Normalizer.Form.NFC. For security-critical contexts such as HTML output or SQL queries, consider using context-appropriate encoding functions from libraries like OWASP Java Encoder after normalization rather than relying solely on character validation. Be aware that some Unicode characters have no normalized equivalent and require explicit handling in your validation logic. See https://wiki.sei.cmu.edu/confluence/display/java/IDS01-J for detailed guidance and additional examples of Unicode-based validation bypasses.

OWASP:

  • A1:2017-Injection
  • A03:2021-Injection