Semgrep scala rules¶
scala_password_rule-ConstantDBPassword¶
Summary:
Use of Hard-coded Password
Severity: Critical
CWE: CWE-259
Description:
A hard-coded password was detected in a call to
java.sql.DriverManager.getConnection(). Hard-coding database credentials
directly in source code creates a significant security vulnerability, as the
password becomes accessible to anyone with access to the codebase, version
control history, or compiled binaries. This practice makes credential
rotation extremely difficult and prevents proper access auditing, potentially
allowing unauthorized database access to persist undetected even after a
security breach.
Remediation:
Consider loading database credentials from secure external sources rather than hard-coding them in your application. Recommended approaches include using environment variables, configuration files excluded from version control, or preferably a Key Management System (KMS). A KMS provides centralized secret management with access auditing, automatic rotation capabilities, and fine-grained access controls. When credentials are stored in a KMS, you can easily rotate them in the event of a breach and maintain a complete audit trail of who accessed which secrets and when. For Google Cloud Platform, consider using Cloud Key Management (https://cloud.google.com/kms/docs). For Amazon Web Services, AWS Secrets Manager or AWS Systems Manager Parameter Store integrate seamlessly with KMS (https://aws.amazon.com/kms/). For on-premise deployments or cloud-agnostic solutions, consider HashiCorp Vault (https://www.vaultproject.io/). Most modern application frameworks provide built-in support for retrieving credentials from these services at runtime.
scala_password_rule-EmptyDBPassword¶
Summary:
Use of Hard-coded Password
Severity: Critical
CWE: CWE-259
Description:
An empty password was detected in a call to
java.sql.DriverManager.getConnection(). Connecting to a database without
authentication allows unrestricted access to anyone who can reach the
database server, exposing sensitive data to unauthorized viewing,
modification, or deletion. This configuration bypasses all access controls
and audit mechanisms, making it impossible to track who accessed what data or
to restrict operations based on user privileges. Empty passwords in database
connections represent a critical security vulnerability that can lead to
complete data compromise.
Remediation:
Consider configuring your database server to require authentication and enforce access controls based on user privileges. Consult your database server's documentation for instructions on enabling authentication and creating user accounts with appropriate permissions. Once authentication is enabled, load credentials from secure external sources rather than hard-coding them in your application. Recommended approaches include using environment variables, configuration files excluded from version control, or preferably a Key Management System (KMS). A KMS provides centralized secret management with access auditing, automatic rotation capabilities, and fine-grained access controls. For Google Cloud Platform, consider using Cloud Key Management (https://cloud.google.com/kms/docs). For Amazon Web Services, AWS Secrets Manager or AWS Systems Manager Parameter Store integrate seamlessly with KMS (https://aws.amazon.com/kms/). For on-premise deployments or cloud-agnostic solutions, consider HashiCorp Vault (https://www.vaultproject.io/). Additionally, implement network-level security controls to restrict database access to authorized application servers only.
scala_cookie_rule-HttpResponseSplitting¶
Summary:
Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
Severity: High
CWE: CWE-113
Description:
The application creates a javax.servlet.http.Cookie with data from
HttpServletRequest.getParameter() or calls Cookie.setValue() with untrusted request
parameters without proper sanitization of CRLF characters. When user-supplied data containing
carriage return (CR) and line feed (LF) sequences is placed into cookie values, attackers can
inject additional HTTP headers or split the response into multiple responses. This enables
HTTP response splitting attacks where an attacker controls subsequent response headers,
potentially leading to cache poisoning, XSS attacks, or session fixation by injecting
malicious Set-Cookie headers.
Remediation:
Always sanitize user input before using it in cookie values by removing or replacing CRLF
sequences using replaceAll("[\r\n]", "") or URL encoding with java.net.URLEncoder.encode()
specifying UTF-8 charset. Consider using the OWASP Java Encoder library with
Encode.forUriComponent() which properly handles special characters including CRLF. For Play
Framework applications, rely on the framework's built-in encoding and validation mechanisms.
Validate that cookie values conform to expected formats using allowlists rather than denylists
to prevent bypass attempts. Consider using framework-provided session mechanisms instead of
directly setting cookies from request parameters, as frameworks typically include built-in
protections against header injection attacks.
scala_cookie_rule-RequestParamToHeader¶
Summary:
Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
Severity: High
CWE: CWE-113
Description:
The application writes untrusted data from HttpServletRequest.getParameter() directly to HTTP
headers using HttpServletResponse.setHeader() or HttpServletResponse.addHeader() without
proper CRLF sanitization. When user-supplied input containing carriage return and line feed
characters is placed into HTTP headers, attackers can inject additional headers or create
multiple HTTP responses from a single request. This HTTP response splitting vulnerability
enables cache poisoning, session fixation through malicious Set-Cookie headers, XSS attacks via
injected content, and redirection to malicious sites through injected Location headers.
Remediation:
Never use request parameters directly in HTTP headers without thorough validation and
sanitization. Remove all CRLF characters using replaceAll("[\r\n]", "") or use URL encoding
with java.net.URLEncoder.encode(value, "UTF-8") before setting header values. Consider using
the OWASP Java Encoder library with Encode.forUriComponent() for comprehensive protection.
Implement strict allowlist validation to accept only expected characters rather than trying to
block malicious patterns. For Play Framework applications, use the framework's typed header
APIs which provide built-in protection against header injection. Avoid using user input in
security-sensitive headers like Location, Set-Cookie, or Content-Type whenever possible. If
redirection based on user input is necessary, validate URLs against a allowlist of permitted
destinations.
scala_inject_rule-CustomInjectionSQLString¶
Summary:
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
Severity: High
CWE: CWE-89
Description:
The application constructs SQL query strings using string concatenation, String.format(),
StringBuilder.append(), or .concat() operations where SQL keywords (SELECT, INSERT,
CREATE, UPDATE, ALTER, DELETE, DROP) are combined with user-controlled input from String
parameters. This pattern indicates SQL injection vulnerability where attackers can inject
malicious SQL fragments to manipulate query semantics, extract unauthorized data, modify
database contents, or escalate privileges. The high severity reflects direct SQL statement
construction with externally-controlled input.
Remediation:
Consider replacing all SQL string construction with parameterized queries using
java.sql.PreparedStatement where user input is bound through setString(), setInt(), and
similar methods that automatically handle escaping. Recommended to adopt Scala-specific
database libraries like Slick (for compile-time type safety) or Doobie (for functional
programming with proper query parameterization). For Play Framework, use Anorm with SQL
string interpolation that provides parameter binding (SQL"SELECT * FROM users WHERE id =
$userId"). Never build SQL through concatenation, even with StringBuilder - always use
parameterized interfaces. If dynamic SQL construction is absolutely required (e.g., dynamic
table names), validate input against strict whitelists of allowed identifiers and use
database-specific identifier quoting functions.
scala_inject_rule-ELInjection¶
Summary:
Improper Control of Generation of Code ('Code Injection')
Severity: High
CWE: CWE-94
Description:
The application uses javax.el.createValueExpression() or createMethodExpression() to
construct Expression Language (EL) expressions with dynamic values from String parameters,
which enables code injection attacks. When untrusted user input is used to build EL
expressions without validation, attackers can inject malicious EL syntax to access sensitive
objects in the EL context, invoke arbitrary methods, read or modify application state, and
potentially achieve remote code execution through Java reflection capabilities available in
the EL environment.
Remediation:
Consider avoiding dynamic EL expression construction entirely - use static expressions with parameterized values passed through the EL context instead. Recommended to pass user data as EL context variables (using ELContext.getVariableMapper()) rather than concatenating them into expression strings, which ensures data is treated as values not code. If dynamic expressions are unavoidable, implement strict whitelist validation that only allows expected property names or method identifiers. For JSP/JSF applications, consider using parameterized includes or controller-side logic instead of dynamic EL generation. Be aware that EL expressions have access to powerful Java objects and reflection capabilities, so limiting the available objects in the EL context can provide defense in depth against injection attacks.
scala_inject_rule-PathTraversalOut¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: High
CWE: CWE-22
Description:
The application opens files for writing using java.io.FileWriter or java.io.FileOutputStream
with file paths constructed from String parameters or command-line arguments from
Array[String] function parameters. When unfiltered parameters control file paths, attackers
can inject path traversal sequences (../, ../../) or absolute paths to write files to arbitrary
filesystem locations outside intended directories. This enables attackers to overwrite critical
system files, application configuration, or executable code, potentially achieving remote code
execution or denial of service. The high severity reflects the write capability that can
directly compromise system integrity.
Remediation:
Consider using org.apache.commons.io.FilenameUtils.getName() to extract only the filename
component, preventing any directory traversal. Recommended to validate file paths using
File.getCanonicalPath() and verify the resolved path starts with an allowed base directory
before any write operations. Can use java.nio.file.Path.normalize() to collapse traversal
sequences, then check that the normalized path is a descendant of the intended directory
using startsWith(). Implement strict whitelist validation for allowed filenames and reject
any paths containing directory separators or traversal patterns. For upload scenarios,
generate random filenames server-side and store the mapping to user-provided names separately.
Set appropriate filesystem permissions on upload directories to limit potential damage from
traversal attacks.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_ldap_rule-EntryPoisoning¶
Summary:
Improperly implemented security check for standard
Severity: High
CWE: CWE-358
Description:
Detected LDAP SearchControls configuration with returningObjFlag set to
true, which enables automatic deserialization of Java objects from LDAP
entries. This can lead to LDAP entry poisoning attacks where malicious LDAP
entries containing serialized objects trigger arbitrary code execution when
retrieved by the application.
Remediation:
Consider setting the returningObjFlag parameter to false in the
SearchControls constructor to prevent automatic object deserialization from
LDAP entries. Recommended to use new SearchControls(scope, countLimit,
timeLimit, attributes, false, deref) instead. If object retrieval is
required, consider implementing explicit type validation and using a
safe deserialization mechanism with strict allowlisting of permitted classes.
scala_password_rule-HardcodePassword¶
Summary:
Use of Hard-coded Password
Severity: High
CWE: CWE-259
Description:
A hard-coded password was detected in security-sensitive API calls such as
KeyStore.load(), PBEKeySpec(), KeyManagerFactory.init(),
PasswordCallback.setPassword(), DriverManager.getConnection(), or
CSRFHandler.create(). Hard-coding credentials directly in source code
creates a significant security vulnerability, as passwords become accessible
to anyone with access to the codebase, version control history, or compiled
binaries. This practice makes credential rotation extremely difficult and
prevents proper access auditing, potentially allowing unauthorized access to
persist undetected even after a security breach. When passwords are embedded
in code, they often remain unchanged for extended periods and may be
inadvertently exposed through code sharing, repository leaks, or
decompilation of binaries.
Remediation:
Consider loading passwords and sensitive credentials from secure external sources rather than hard-coding them in your application. Recommended approaches include using environment variables, configuration files excluded from version control, or preferably a Key Management System (KMS). A KMS provides centralized secret management with access auditing, automatic rotation capabilities, and fine-grained access controls. When credentials are stored in a KMS, you can easily rotate them in the event of a breach and maintain a complete audit trail of who accessed which secrets and when. For Google Cloud Platform, consider using Cloud Key Management (https://cloud.google.com/kms/docs). For Amazon Web Services, AWS Secrets Manager or AWS Systems Manager Parameter Store integrate seamlessly with KMS (https://aws.amazon.com/kms/). For on-premise deployments or cloud-agnostic solutions, consider HashiCorp Vault (https://www.vaultproject.io/). Most modern application frameworks provide built-in support for retrieving credentials from these services at runtime. For keystore and encryption passwords, consider using operating system credential stores or hardware security modules (HSMs) for additional protection.
scala_perm_rule-OverlyPermissiveFilePermissionInline¶
Summary:
Incorrect Permission Assignment for Critical Resource
Severity: High
CWE: CWE-732
Description:
Setting overly permissive file permissions via
java.nio.file.Files.setPosixFilePermissions() with permission strings
from PosixFilePermissions.fromString() that grant read, write, or execute
permissions to "others" (world-readable/writable) exposes sensitive files
to unauthorized access. When the permission string contains any permission
flags in the last three characters (e.g., "rwxrwxrwx" or "rw-rw-rw-"),
it allows any user on the system to access the file, potentially leading
to information disclosure, data tampering, or privilege escalation.
Remediation:
Consider restricting file permissions to only the owner and group that
require access, removing all permissions for "others". Recommended to use
permission strings like "rw-------" (0600) for sensitive files that only
the owner should access, or "rw-r-----" (0640) for files that need group
read access. When setting permissions with PosixFilePermissions.fromString(),
ensure the last three characters are "---" to deny all access to others.
For executable files, consider "rwx------" (0700) or "rwxr-x---" (0750)
instead of world-executable permissions. Review your application's file
creation logic and establish a secure default permission policy. Consider
using file system ACLs (Access Control Lists) for more granular permission
control when needed. Always validate that sensitive files like configuration
files, private keys, and credential stores have restrictive permissions
immediately after creation.
scala_smtp_rule-InsecureSmtp¶
Summary:
Improper Validation of Certificate with Host Mismatch
Severity: High
CWE: CWE-297
Description:
Apache Commons Email is configured with SSL enabled but without server identity verification. This allows man-in-the-middle attacks where an attacker can intercept SMTP traffic, potentially capturing sensitive email content and authentication credentials despite the SSL connection.
Remediation:
When using Apache Commons Email classes like SimpleEmail, HtmlEmail, or
MultiPartEmail with SSL, always enable server identity verification by calling
setSSLCheckServerIdentity(true) after setSSLOnConnect(true). This ensures
the SSL certificate's hostname matches the server you're connecting to, preventing
man-in-the-middle attacks. Without this check, SSL provides encryption but not
authentication, leaving connections vulnerable to interception.
OWASP:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
scala_smtp_rule-SmtpClient¶
Summary:
Improper Neutralization of Special Elements used in a Command
Severity: High
CWE: CWE-77
Description:
Detected potential SMTP header injection vulnerability when using MimeMessage
methods such as setSubject(), addHeader(), setDescription(), and
setDisposition() with non-literal values. If user input is placed in email
headers without proper sanitization, attackers can inject CR/LF characters to
insert arbitrary headers or manipulate email routing and content.
Remediation:
Consider using safe email libraries such as Apache Commons Email or
Simple Java Mail, which automatically sanitize header values and prevent
injection attacks. Recommended to validate and strip CR (\r) and LF (\n)
characters from any user-controlled data before including it in email
headers. If using MimeMessage directly, consider implementing strict input
validation using allowlist patterns for permitted characters in each header.
scala_unsafe_rule-ExternalConfigControl¶
Summary:
External Control of System or Configuration Setting
Severity: High
CWE: CWE-15
Description:
External control of database catalog configuration was detected. User-supplied input from
HttpServletRequest.getParameter() flows directly to Connection.setCatalog() without
validation. This allows attackers to manipulate database configuration settings, potentially
causing the application to connect to unauthorized database catalogs, disrupt service by
providing nonexistent catalog names, or access sensitive data from unintended database
schemas.
Remediation:
Consider implementing strict validation and allow-listing of catalog names before
using them in Connection.setCatalog(). Recommended to define a fixed set of
permitted catalog names in configuration and validate user input against this
list. Consider using an enumeration or sealed trait to represent valid catalog
options, ensuring only predefined values can be used. Avoid passing user-supplied
parameters directly to database configuration methods. If dynamic catalog selection
is required, implement a mapping layer that translates sanitized user input to
internal catalog identifiers. Consider logging catalog access attempts for security
monitoring and auditing purposes.
scala_xml_rule-XmlDecoder¶
Summary:
Deserialization of Untrusted Data
Severity: High
CWE: CWE-502
Description:
Using java.beans.XMLDecoder with the readObject() method to deserialize XML from
untrusted sources creates a critical remote code execution vulnerability. XMLDecoder
executes arbitrary Java code embedded in XML during deserialization, allowing attackers
to instantiate malicious classes, invoke methods, and gain full control of the application.
This vulnerability is particularly dangerous because XMLDecoder was designed for trusted
bean persistence, not for processing untrusted input.
Remediation:
Consider migrating to safe serialization formats like JSON with libraries such as
Jackson, Gson, or kotlinx.serialization for Scala applications. These libraries provide
type-safe deserialization without arbitrary code execution risks. If XML serialization
is required, recommended to use JAXB with strict schema validation or XStream configured
with security framework enabled and explicit type allowlists via XStream.allowTypes().
For configuration files, consider using structured formats like YAML with SnakeYAML in
safe mode, or HOCON for Scala applications. Never deserialize XML from untrusted sources
without strict validation, and implement defense-in-depth by running deserialization in
sandboxed environments with restricted classloading capabilities.
scala_crypto_rule-BlowfishKeySize¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses javax.crypto.KeyGenerator.getInstance("Blowfish") with a key size
smaller than 128 bits, making the ciphertext vulnerable to brute force attacks. While Blowfish
supports variable key sizes from 32 to 448 bits, modern cryptographic standards require a
minimum of 128 bits of entropy to provide adequate security against current computational
capabilities. Using insufficient key sizes significantly reduces the time and resources needed
for an attacker to successfully perform brute force key recovery attacks.
Remediation:
Consider migrating from Blowfish to AES (Advanced Encryption Standard) with 256-bit keys
using javax.crypto.KeyGenerator.getInstance("AES") and initializing with
keyGen.init(256). AES is the current NIST-recommended standard and provides better
performance and security characteristics than Blowfish for modern applications. If Blowfish
must be used for legacy compatibility, ensure key sizes are at least 128 bits, though
256-448 bits is recommended. For Scala applications, consider using higher-level
cryptography libraries like Tsec or the Java Cryptography Architecture (JCA) with type-safe
wrappers to prevent configuration errors.
scala_crypto_rule-CipherDESInsecure¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses javax.crypto.Cipher.getInstance("DES/...") which implements the Data
Encryption Standard, a cryptographically broken cipher that is no longer considered secure for
modern applications. DES uses a 56-bit key size which is far too small by current standards
and can be brute-forced in hours using readily available computing resources. The algorithm's
small block size of 64 bits also makes it vulnerable to birthday attacks when encrypting large
amounts of data.
Remediation:
Migrate to AES (Advanced Encryption Standard) which is the current NIST-recommended
symmetric encryption algorithm. Replace javax.crypto.Cipher.getInstance("DES/...") with
javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") for authenticated encryption that
provides both confidentiality and integrity protection. Use 256-bit AES keys generated with
javax.crypto.KeyGenerator.getInstance("AES") initialized to 256 bits. For Scala
applications, consider using the Tsec library which provides type-safe cryptographic
primitives and makes it easier to use secure defaults. Ensure proper IV (Initialization
Vector) generation using java.security.SecureRandom for each encryption operation.
scala_crypto_rule-CipherDESedeInsecure¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses javax.crypto.Cipher.getInstance("DESede/...") which implements Triple
DES (3DES), a legacy encryption algorithm that is deprecated and no longer recommended for
modern applications. While Triple DES applies DES three times to increase security, it still
suffers from a 64-bit block size making it vulnerable to birthday attacks after processing
approximately 32GB of data with the same key. NIST has officially deprecated 3DES as of 2023
and recommends transitioning to AES for all new applications and existing systems.
Remediation:
Migrate to AES-256-GCM (Galois/Counter Mode) which provides authenticated encryption with
associated data (AEAD). Replace javax.crypto.Cipher.getInstance("DESede/...") with
javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") and use 256-bit keys for maximum
security. AES-GCM provides both encryption and authentication in a single operation,
eliminating the need for separate HMAC operations. For Scala projects, consider using Tsec
or BouncyCastle libraries which provide idiomatic Scala APIs for cryptographic operations.
When migrating legacy systems, ensure you have a transition plan for re-encrypting existing
3DES-encrypted data, as cipher outputs are not compatible between algorithms.
scala_crypto_rule-CipherECBMode¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses javax.crypto.Cipher.getInstance() with ECB (Electronic Code Book) mode
such as "AES/ECB/..." or "DES/ECB/...", which does not provide semantic security. ECB mode
encrypts identical plaintext blocks into identical ciphertext blocks, revealing patterns in
the encrypted data that can leak information about the underlying plaintext. This deterministic
behavior allows attackers to detect repeated data, perform block substitution attacks, and
potentially reconstruct portions of the plaintext without breaking the underlying cipher.
Remediation:
Replace ECB mode with an authenticated encryption mode like GCM (Galois/Counter Mode) using
javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") which provides both confidentiality
and integrity protection. GCM mode uses a unique IV (Initialization Vector) for each
encryption operation, ensuring that identical plaintexts produce different ciphertexts.
Generate a cryptographically secure random 12-byte IV using java.security.SecureRandom
for each encryption and store it alongside the ciphertext. For Scala applications, libraries
like Tsec provide functional wrappers around JCA that enforce secure defaults and make it
harder to misconfigure cipher modes. If GCM is not available, CBC mode with HMAC
verification is an acceptable alternative, though it requires careful implementation.
scala_crypto_rule-CipherIntegrity¶
Summary:
Missing Support for Integrity Check
Severity: Medium
CWE: CWE-353
Description:
The application uses javax.crypto.Cipher.getInstance() with cipher modes like CBC, CTR, OFB,
or ECB that provide only encryption without authentication. These modes produce ciphertext
that is susceptible to alteration by an adversary, as they provide no way to detect tampering
or modification of the encrypted data. An attacker who can intercept and modify ciphertext can
perform bit-flipping attacks in CTR or OFB modes, or padding oracle attacks in CBC mode,
potentially leading to arbitrary plaintext manipulation or complete decryption without
knowledge of the key.
Remediation:
Migrate to authenticated encryption modes that provide both confidentiality and integrity in
a single operation. Use javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") for
authenticated encryption with associated data (AEAD), which automatically authenticates the
ciphertext and prevents tampering. If GCM is not available, use CBC mode with a separate
HMAC-SHA256 operation following the Encrypt-then-MAC pattern, though this requires careful
implementation to avoid timing vulnerabilities. For Scala applications, the Tsec library
provides type-safe AEAD constructions that make it easier to use authenticated encryption
correctly. Always verify the authentication tag before attempting to decrypt data to prevent
processing of tampered ciphertexts.
scala_crypto_rule-CipherPaddingOracle¶
Summary:
Incorrect Behavior Order
Severity: Medium
CWE: CWE-696
Description:
The application uses javax.crypto.Cipher.getInstance() with CBC mode and PKCS5Padding (e.g.,
"AES/CBC/PKCS5Padding"), which is susceptible to padding oracle attacks. An adversary can
potentially decrypt ciphertext without knowing the key if the application reveals timing
differences, distinct error messages, or behavioral differences between valid and invalid
padding during decryption. These oracle attacks have been successfully exploited in numerous
real-world systems, allowing complete plaintext recovery through careful manipulation of
ciphertext blocks and observation of decryption error responses.
Remediation:
Replace CBC mode with authenticated encryption using
javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") which eliminates padding entirely by
using stream cipher modes and provides built-in authentication. GCM mode authenticates the
ciphertext before decryption, preventing padding oracle attacks and other manipulation
attempts. If CBC mode must be used for legacy compatibility, implement the Encrypt-then-MAC
pattern with HMAC-SHA256 and verify the MAC in constant time before attempting decryption.
For Scala applications, use libraries like Tsec that provide secure-by-default AEAD
implementations and help avoid common cryptographic pitfalls. Never expose different error
messages or timing behaviors for padding validation failures versus other decryption errors.
scala_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, which is
extremely error-prone and dangerous. Cryptographic hash functions require careful mathematical
construction to ensure properties like collision resistance, preimage resistance, and avalanche
effect. Even minor implementation errors in custom hash functions can lead to catastrophic
security failures that may not be immediately apparent but can be exploited by sophisticated
attackers. Custom cryptographic implementations lack the extensive peer review and
cryptanalysis that standard algorithms have undergone.
Remediation:
Remove custom MessageDigest implementations and use standard cryptographic hash functions
from the Java Cryptography Architecture. Use java.security.MessageDigest.getInstance() with
NIST-approved algorithms like "SHA-256", "SHA-384", or "SHA-512" depending on your security
requirements. For most applications, SHA-256 provides an excellent balance of security and
performance. For Scala applications, consider using higher-level libraries like Tsec that
provide type-safe wrappers around JCA hash functions and make it easier to follow
cryptographic best practices. If you need application-specific hash behavior, use HMAC with
a standard hash function rather than implementing custom cryptography, as HMAC provides
keyed hashing with proven security properties.
scala_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 symmetric encryption, which is deprecated and provides
inadequate security. Hazelcast's symmetric encryption typically uses weak ciphers like DES or
Blowfish by default and does not provide authentication or integrity protection for network
traffic. Without authentication, the cluster is vulnerable to man-in-the-middle attacks where
an attacker can intercept, modify, or inject messages between cluster nodes. Hazelcast has
deprecated this feature in favor of TLS/SSL-based encryption which provides stronger security
guarantees.
Remediation:
Replace SymmetricEncryptionConfig with TLS/SSL configuration using Hazelcast's SSLConfig
which provides mutual authentication and modern cipher suites. Configure TLS for Hazelcast
member-to-member and client-to-member communications using
networkConfig.setSSLConfig(sslConfig) with appropriate key stores and trust stores. Use
TLS 1.2 or higher with strong cipher suites that provide forward secrecy such as those using
ECDHE key exchange and AES-GCM for encryption. For Scala applications, wrap Hazelcast
configuration in type-safe configuration objects to prevent misconfiguration. Additionally,
enable mutual TLS authentication to ensure that only authorized nodes can join the cluster.
Refer to Hazelcast's official documentation for TLS configuration best practices and ensure
proper certificate management including rotation and revocation.
scala_crypto_rule-InsufficientKeySizeRsa¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses KeyPairGenerator.getInstance() or RSAKeyGenParameterSpec to generate
RSA or DSA keys with a key size smaller than 2048 bits. Insufficient key sizes make asymmetric
cryptographic operations vulnerable to factorization attacks, where an attacker with sufficient
computational resources can break the private key and compromise all security guarantees. NIST
recommends minimum key sizes of 2048 bits for RSA and DSA, with 3072 bits or higher preferred
for long-term security beyond 2030. Keys smaller than 2048 bits can potentially be broken using
modern computational resources including cloud computing and specialized hardware.
Remediation:
Generate RSA keys with a minimum size of 2048 bits by calling keyPairGen.initialize(2048)
or using new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4). For applications
requiring long-term security or high-value asset protection, use 3072-bit or 4096-bit keys.
Alternatively, consider migrating to Elliptic Curve Cryptography (ECC) using ECDSA with
curve P-256 or higher, which provides equivalent security to 3072-bit RSA with significantly
smaller key sizes and better performance. For Scala applications, consider using higher-level
libraries like Tsec that provide type-safe APIs for key generation with secure defaults.
When generating new keys, use a cryptographically secure random number generator with
java.security.SecureRandom to ensure key unpredictability.
scala_crypto_rule-NullCipher¶
Summary:
Use of a Broken or Risky Cryptographic Algorithm
Severity: Medium
CWE: CWE-327
Description:
The application uses new javax.crypto.NullCipher() which is a special cipher implementation
that performs no encryption, returning ciphertext identical to the supplied plaintext. While
NullCipher may be appropriate in narrow testing contexts or as a placeholder during
development, its accidental use in production code introduces a critical confidentiality risk
where sensitive data is transmitted or stored without any cryptographic protection. The danger
is particularly acute because NullCipher implements the standard Cipher interface, making it
easy to inadvertently use in place of real encryption without triggering obvious errors.
Remediation:
Replace NullCipher with actual encryption using
javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") for authenticated encryption that
provides both confidentiality and integrity protection. If NullCipher is being used as a
testing mock, use proper mocking frameworks like ScalaTest or Mockito to stub cipher
behavior rather than using NullCipher in test code, as this reduces the risk of NullCipher
accidentally leaking into production. For Scala applications, consider using libraries like
Tsec that provide type-safe cipher abstractions and make it impossible to accidentally use
no-op implementations in production code. Implement configuration validation that explicitly
rejects null or no-op cipher configurations when the application starts, ensuring that
encryption is properly configured before processing sensitive data.
scala_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 but specifies
"NoPadding" mode, which makes the encryption deterministic and vulnerable to several attacks.
RSA without padding is vulnerable to chosen ciphertext attacks where an attacker can craft
specific inputs to extract information about the plaintext or private key. Without OAEP
(Optimal Asymmetric Encryption Padding), RSA encryption is malleable, meaning attackers can
modify ciphertexts in predictable ways, and it leaks information when the same plaintext is
encrypted multiple times. Modern cryptographic standards require RSA to be used with OAEP
padding to provide semantic security and protection against adaptive chosen-ciphertext attacks.
Remediation:
Replace RSA NoPadding with OAEP by using
javax.crypto.Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding") which provides
semantic security and protection against adaptive chosen-ciphertext attacks. OAEP padding
adds randomness to each encryption operation, ensuring that encrypting the same plaintext
multiple times produces different ciphertexts. For even better security, use OAEP with
SHA-256 or SHA-512 hash functions rather than the older SHA-1. For Scala applications,
consider using libraries like Tsec or BouncyCastle that provide idiomatic APIs for RSA
encryption with secure defaults. Note that RSA is best suited for encrypting small amounts
of data like symmetric keys; for bulk data encryption, use RSA to encrypt an AES key and
then use AES-GCM to encrypt the actual data (hybrid encryption pattern).
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
scala_crypto_rule-WeakMessageDigest¶
Summary:
Inadequate Encryption Strength
Severity: Medium
CWE: CWE-326
Description:
The application uses MessageDigest.getInstance() or Signature.getInstance() with
cryptographically weak hash algorithms including MD5, MD4, MD2, or SHA-1. These algorithms are
cryptographically broken and vulnerable to collision attacks where an attacker can craft two
different inputs that produce the same hash output. Collision attacks against MD5 have been
practical since 2004, and SHA-1 collision attacks were demonstrated in 2017 with the
SHAttered attack. Using these weak hash functions undermines any security guarantees for
digital signatures, integrity verification, password storage, or certificate validation.
Remediation:
Migrate to SHA-256 or stronger hash functions from the SHA-2 or SHA-3 families. Replace weak
algorithms with MessageDigest.getInstance("SHA-256") for most applications, or use
"SHA-384" or "SHA-512" for higher security requirements. For digital signatures, use
Signature.getInstance("SHA256withRSA") or Signature.getInstance("SHA256withECDSA")
instead of SHA-1-based signature algorithms. For password hashing, use purpose-built
algorithms like bcrypt, scrypt, or Argon2 rather than general-purpose hash functions. For
Scala applications, consider using libraries like Tsec that provide type-safe cryptographic
primitives with secure defaults and prevent accidental use of weak algorithms. When migrating
from MD5 or SHA-1, ensure you have a transition plan for verifying legacy hashes while
generating new hashes with stronger algorithms.
scala_crypto_rule-WeakTLSProtocol¶
Summary:
Improper Certificate Validation
Severity: Medium
CWE: CWE-295
Description:
The application uses javax.net.ssl.SSLContext.getInstance("SSL") or instantiates
DefaultHttpClient(), both of which use deprecated and insecure SSL/TLS protocol versions.
The generic "SSL" protocol identifier allows negotiation down to SSLv2 and SSLv3, which have
known critical vulnerabilities including POODLE, BEAST, and CRIME attacks that allow attackers
to decrypt encrypted traffic. These legacy protocols lack modern security features like forward
secrecy and authenticated encryption, and have been officially deprecated by the IETF. Using
these configurations exposes application traffic to man-in-the-middle attacks and protocol
downgrade attacks.
Remediation:
Replace SSLContext.getInstance("SSL") with SSLContext.getInstance("TLSv1.2") or
SSLContext.getInstance("TLSv1.3") to use modern, secure TLS protocol versions. For maximum
compatibility while maintaining security, use "TLSv1.2" which is widely supported and does
not have known critical vulnerabilities. For DefaultHttpClient, migrate to Apache HttpClient
4.5+ using HttpClients.createDefault() which uses TLS 1.2+ by default. For Scala
applications, consider using modern HTTP libraries like http4s, sttp, or Akka HTTP which
provide secure TLS defaults and type-safe configuration. Additionally, configure your SSL
context to use strong cipher suites that provide forward secrecy by prioritizing ECDHE key
exchange algorithms. Ensure proper certificate validation is enabled and avoid disabling
hostname verification or trusting all certificates, even in development environments.
scala_endpoint_rule-JaxRsEndpoint¶
Summary:
Use of less trusted source
Severity: Medium
CWE: CWE-348
Description:
This method is annotated with JAX-RS (JSR-311) annotations like @javax.ws.rs.Path, making it an HTTP REST endpoint that accepts external input. REST endpoints decorated with JAX-RS annotations expose the application to untrusted user-supplied data, which can introduce various security vulnerabilities if not properly validated and secured. The endpoint parameters should be treated as untrusted sources requiring security analysis for authentication, authorization, input validation, SSL/TLS enforcement, and CSRF protection for state-changing operations.
Remediation:
Consider implementing a comprehensive security strategy for JAX-RS endpoints in your Scala application. Recommended to enforce authentication using JAX-RS filters or security annotations like @RolesAllowed to verify user identity before processing requests. Implement authorization checks to ensure authenticated users have appropriate permissions for the requested operation. Validate all input parameters using Bean Validation (JSR-380) annotations such as @NotNull, @Pattern, or custom validators to prevent injection attacks. Use HTTPS exclusively by configuring your application server to redirect HTTP traffic or reject non-TLS connections. For endpoints that modify state (POST, PUT, DELETE methods), implement CSRF protection using synchronizer tokens or double-submit cookie patterns. Consider using JAX-RS ContainerRequestFilter for centralized security enforcement across multiple endpoints.
scala_file_rule-FilenameUtils¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Medium
CWE: CWE-22
Description:
Path traversal vulnerability detected using FilenameUtils methods. Functions like
FilenameUtils.normalize(), getName(), getBaseName(), getExtension(), and
isExtension() are being used on potentially user-controlled file paths. Without
proper validation, attackers can use path traversal sequences like ../ to access
files outside the intended directory, potentially reading sensitive configuration
files, credentials, or source code.
Remediation:
Consider validating file paths against an allowlist of permitted files or
directories before using FilenameUtils methods. Recommended to check that the
resolved path starts with the intended base directory after normalization.
Explicitly reject paths containing .. sequences or other traversal attempts.
Use java.nio.file.Paths.get().normalize().startsWith() to verify the final
path remains within allowed boundaries. Avoid directly using user input in file
operations without validation.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_inject_rule-LDAPInjection¶
Summary:
Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')
Severity: Medium
CWE: CWE-90
Description:
The application constructs LDAP queries using user-controlled String parameters passed to
javax.naming.directory.DirContext, javax.naming.Context, javax.naming.ldap.LdapContext,
com.unboundid.ldap.sdk.LDAPConnection, or Spring LDAP's LdapTemplate methods including
lookup(), search(), and list(), as well as Properties.put() for LDAP connection
properties. Unlike SQL, LDAP lacks prepared statement interfaces, making it vulnerable to
injection attacks where special characters (parentheses, asterisks, backslashes) can modify
query logic to bypass authentication, extract unauthorized data, or escalate privileges.
Remediation:
Consider implementing strict input validation that whitelists only alphanumeric characters
and expected patterns before including data in LDAP queries. Recommended to escape LDAP
special characters including parentheses (), asterisks *, backslashes \, null bytes, and
angle brackets using proper encoding functions. For Java applications, use OWASP ESAPI's
Encoder.encodeForLDAP() or manually escape special characters according to RFC 4515 for
filter strings and RFC 4514 for Distinguished Names. For Spring LDAP applications, use
LdapEncoder.nameEncode() and LdapEncoder.filterEncode() to properly escape inputs.
Consider using parameterized filters with Spring LDAP's LdapQueryBuilder which provides
safer query construction with automatic escaping of user-supplied values.
scala_inject_rule-OgnlInjection¶
Summary:
Expression injection (OGNL)
Severity: Medium
CWE: CWE-917
Description:
The application uses Apache Struts/XWork2 OGNL (Object-Graph Navigation Language) expression
evaluation APIs including TextParseUtil, OgnlTextParser, OgnlReflectionProvider,
OgnlUtil, StrutsUtil, and ValueStack with user-controlled String or Map parameters from
method arguments. These APIs dynamically evaluate OGNL expressions which can access Java
objects, invoke methods, and manipulate application state. When untrusted input is passed to
these expression evaluation methods, attackers can inject malicious OGNL syntax to achieve
remote code execution, access sensitive data, or bypass security controls through Java
reflection capabilities.
Remediation:
Consider avoiding dynamic OGNL expression evaluation entirely with user input - use static
expressions and pass data through the ValueStack context as objects rather than in
expression strings. Recommended to upgrade to Struts 2.5.x or later which includes improved
security controls and expression evaluation restrictions. For applications that must
evaluate dynamic expressions, implement strict whitelist validation allowing only expected
property names without special OGNL operators or method calls. Can use Struts security
configuration options like struts.ognl.excludedClasses and
struts.ognl.excludedPackageNames to limit accessible classes and packages. Consider
migrating away from OGNL-based architectures to safer alternatives like Spring MVC with
SpEL (which has better sandboxing) or REST APIs with JSON data binding that avoid code
evaluation entirely.
scala_inject_rule-PathTraversalIn¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Medium
CWE: CWE-22
Description:
The application opens files for reading using Java file APIs (java.io.File, FileInputStream,
FileReader, RandomAccessFile, java.nio.file.Paths.get(), Files.createTempFile()) and
Scala file APIs (scala.io.Source.fromFile(), Source.fromString()) with filenames
constructed from String parameters or command-line arguments. When unfiltered parameters are
passed to these file APIs, attackers can inject path traversal sequences (../, ../../, absolute
paths) to read files from arbitrary filesystem locations outside intended directories,
potentially exposing sensitive data like configuration files, credentials, or application
source code.
Remediation:
Consider using org.apache.commons.io.FilenameUtils.getName() to extract only the filename
component, stripping any directory path information including traversal sequences. Recommended
to validate that file paths resolve to expected directories using File.getCanonicalPath()
and comparing against an allowed base directory prefix. Can use java.nio.file.Path.normalize()
combined with startsWith() checks to ensure resolved paths remain within allowed
directories. Implement whitelist validation for allowed filenames or patterns, and reject
paths containing directory separators (/, ) or traversal sequences (..). For Scala
applications, consider using safer file access patterns with explicit directory boundaries
and validated filename components rather than accepting arbitrary path strings from users.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_inject_rule-SqlInjection¶
Summary:
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
Severity: Medium
CWE: CWE-89
Description:
The application constructs SQL queries with dynamic values passed to JDO (PersistenceManager.newQuery(),
Query.setFilter()), Hibernate (Session.createQuery(), Session.createSQLQuery(),
Restrictions.sqlRestriction()), JDBC (Statement.executeQuery(), Statement.execute(),
Statement.executeUpdate(), Connection.prepareStatement()), Spring JDBC (JdbcTemplate,
JdbcOperations methods), JPA (EntityManager.createQuery(), createNativeQuery()), Vert.x
SQL Client, Apache Turbine/Torque, and Anorm (anorm.SQL()) without using string literals.
When queries are constructed dynamically with variables instead of bind parameters, attackers
can inject malicious SQL to manipulate query logic, extract sensitive data, modify records, or
execute administrative operations.
Remediation:
Consider using parameterized queries with bind variables where values are passed separately
from the SQL command structure - for JDBC use PreparedStatement with setString(),
setInt() methods rather than string concatenation. Recommended to use type-safe Scala
database libraries like Slick (compile-time query validation), Doobie (functional query
composition), or ScalikeJDBC (interpolation-based parameterization) which prevent SQL
injection by design. For Play Framework applications, use Anorm's parameter interpolation
with SQL"SELECT * FROM users WHERE id = $userId" syntax which binds parameters safely. For
Spring applications, use JdbcTemplate with parameterized methods that accept bind parameters
as separate arguments. For Hibernate, use named parameters (:paramName) or positional
parameters (?) with Query.setParameter(). Never concatenate or interpolate user data
directly into query strings - always use the framework's parameterization mechanisms.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
scala_perm_rule-OverlyPermissiveFilePermissionObj¶
Summary:
Incorrect Permission Assignment for Critical Resource
Severity: Medium
CWE: CWE-732
Description:
Adding OTHERS_READ, OTHERS_WRITE, or OTHERS_EXECUTE permissions from
PosixFilePermission enum to a permission set used with
java.nio.file.Files.setPosixFilePermissions() creates world-accessible
files. These OTHERS_* permissions grant access to any user on the system,
not just the file owner or group members. This can expose sensitive data
to unauthorized users, allow tampering with critical files, or enable
execution of malicious code by unprivileged users, leading to information
disclosure, data integrity violations, or privilege escalation attacks.
Remediation:
Consider using only OWNER_ and GROUP_ permissions when building
permission sets for sensitive files. Recommended to exclude all OTHERS_
permissions (OTHERS_READ, OTHERS_WRITE, OTHERS_EXECUTE) from your
PosixFilePermission sets. When creating permission sets, use combinations
like Set(OWNER_READ, OWNER_WRITE) for owner-only access, or add
GROUP_READ for group access as needed. For directories that must be
traversable, consider GROUP_EXECUTE instead of OTHERS_EXECUTE. Review
your file permission requirements and apply the principle of least
privilege by granting access only to users who absolutely need it.
Consider implementing permission checks in your code to verify that files
created by your application never have OTHERS_ permissions set. For
temporary files, use Files.createTempFile() with appropriate file
attributes rather than manually setting permissions after creation.
scala_script_rule-SpelView¶
Summary:
Improper Control of Generation of Code ('Code Injection')
Severity: Medium
CWE: CWE-94
Description:
Detected Spring Expression Language (SpEL) injection vulnerability when using
SpelExpressionParser.parseExpression() with non-literal input. SpEL allows
execution of arbitrary code through expression evaluation, enabling attackers
to access system properties, invoke methods, and potentially achieve remote
code execution when user-controlled values are parsed as SpEL expressions.
Remediation:
Consider avoiding the use of dynamic SpEL expressions with user-controlled
input entirely, as SpEL provides extensive capabilities for arbitrary code
execution. Recommended to use static configuration or template-based
approaches instead. If dynamic expressions are required, consider
implementing strict allowlist validation that permits only specific
predefined expression patterns, and use SimpleEvaluationContext instead of
StandardEvaluationContext to restrict available functionality.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
scala_ssrf_rule-PlaySSRF¶
Summary:
Server-Side Request Forgery (SSRF)
Severity: Medium
CWE: CWE-918
Description:
This rule detected user-controlled input being passed to the Play Framework's
WSClient.url() method without proper validation. The pattern identifies cases
where non-literal string values are used to construct web service requests
through the Play WS (Web Services) client API. When user input controls the URL
parameter in ws.url() calls, Server-Side Request Forgery (SSRF)
vulnerabilities arise that allow attackers to force the Play application to
access internal resources, cloud metadata endpoints (169.254.169.254),
administrative interfaces, or perform unauthorized requests that bypass network
segmentation and firewall rules.
Remediation:
Consider implementing a strict URL allowlist that validates user input
against approved domains before passing URLs to WSClient.url(). Use Scala's
java.net.URI or Play's URL utilities 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 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 Play
applications, configure custom WSClientConfig with request filters or
interceptors that enforce URL validation at the HTTP client level.
Network-level defenses can include running the Play application in
containerized environments with egress filtering rules that prevent
connections to internal networks. Consider using a server-side mapping
approach where user input provides keys that map to pre-configured safe URLs
rather than accepting arbitrary URLs.
scala_strings_rule-BadHexConversion¶
Summary:
Incorrect Type Conversion or Cast
Severity: Medium
CWE: CWE-704
Description:
When converting a byte array from java.security.MessageDigest.digest() to a hexadecimal
string using Integer.toHexString() within a loop, byte values between 0x00 and 0x0F will
be incorrectly converted to single-character strings (e.g., "a" instead of "0a"), producing
invalid hash representations. This occurs because Integer.toHexString() does not zero-pad
the output, leading to truncated or malformed hash strings that will fail validation or
comparison checks in security-critical operations.
Remediation:
Consider using String.format("%02x", byteValue) or "%02x".format(byteValue) in Scala
to ensure each byte is consistently represented as a two-character hexadecimal string with
leading zero padding. Alternatively, for better performance and cleaner code, recommended
to use libraries like Apache Commons Codec's Hex.encodeHexString(byteArray) or Guava's
BaseEncoding.base16().lowerCase().encode(byteArray) which handle the conversion correctly
and efficiently. These library methods avoid manual iteration and padding logic, reducing
the risk of implementation errors in security-sensitive hash string generation.
scala_strings_rule-ImproperUnicode¶
Summary:
Improper Handling of Unicode Encoding
Severity: Medium
CWE: CWE-176
Description:
String transformations using String.toLowerCase() or String.toUpperCase() followed by
comparison methods like equals(), equalsIgnoreCase(), or indexOf(), as well as direct
use of java.text.Normalizer.normalize(), java.net.IDN.toASCII(), or URI.toASCIIString()
can lead to improper handling of Unicode encoding. Case transformations and normalization can
produce unexpected character mappings, particularly with Turkish locale where 'i' and 'I'
have different uppercase/lowercase mappings, or with Unicode normalization forms that can
combine or decompose characters in security-sensitive contexts like validation bypasses.
Remediation:
Consider using locale-aware comparison methods or explicitly specifying Locale.ROOT when
performing case transformations to avoid locale-specific character mapping issues. For
case-insensitive comparisons, recommended to use String.equalsIgnoreCase() directly
instead of transforming and comparing, or use Collator with appropriate strength settings
for more complex scenarios. When working with Unicode normalization for security validation,
ensure normalization is applied consistently before and after validation checks to prevent
bypasses through character composition tricks. For internationalized domain names, validate
that IDN.toASCII() output is used consistently throughout the security boundary, and be
aware of homograph attacks where visually similar characters from different scripts can be
used to create deceptive domain names.
scala_xml_rule-SAMLIgnoreComments¶
Summary:
Weak authentication
Severity: Medium
CWE: CWE-1390
Description:
Setting setIgnoreComments(false) on BasicParserPool when processing SAML assertions
causes the XML parser to preserve comments during canonicalization, which can lead to
authentication bypass vulnerabilities. Attackers can inject malicious content within XML
comments that gets processed during signature verification but interpreted differently
during actual authentication, allowing them to bypass security controls and impersonate
legitimate users.
Remediation:
Consider using setIgnoreComments(true) when configuring BasicParserPool for SAML
processing to ensure XML comments are stripped before signature verification. This is
the recommended secure default in OpenSAML implementations and prevents comment-based
signature wrapping attacks. When initializing the SAML parser pool, recommended to use
StaticBasicParserPool with explicit secure defaults including comment ignoring enabled,
or leverage the BasicParserPool.builder() pattern to ensure all security-relevant
settings are properly configured. Additionally, ensure your SAML implementation validates
signatures after canonicalization to prevent other forms of XML signature wrapping attacks.
scala_xpathi_rule-XpathInjection¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
Untrusted data is used in XPath expressions through XPath.compile() or
XPath.evaluate() without proper sanitization. This allows attackers to
manipulate XPath queries to access unauthorized XML data or bypass access
controls, potentially exposing sensitive information.
Remediation:
Avoid constructing XPath expressions directly from user input. Instead,
consider using parameterized XPath queries with XPathVariableResolver to
safely bind user-controlled values. This prevents attackers from injecting
malicious XPath syntax. If parameterization is not feasible, implement strict
input validation using allowlists for expected values and escape special
XPath characters before inclusion in queries.
scala_xss_rule-RequestWrapper¶
Summary:
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Severity: Medium
CWE: CWE-79
Description:
The application is implementing a custom XSS filtering function stripXSS() within a
custom HttpServletRequestWrapper class in Scala. Custom XSS filters are notoriously
difficult to implement correctly and often contain bypasses due to incomplete pattern
matching, encoding issues, or failure to account for all injection vectors. Attackers
frequently discover ways to circumvent homegrown sanitization through encoding tricks,
unusual character sets, browser-specific parsing behaviors, or DOM-based mutation.
Additionally, custom filters may interfere with legitimate data or create false positives,
while still missing real attacks due to the complexity of HTML and JavaScript parsing
contexts.
Remediation:
Consider removing custom XSS filtering logic and instead use context-aware output encoding
at the point where data is rendered in templates. For Scala applications, use OWASP Java
Encoder library's context-specific functions like Encode.forHtml(),
Encode.forJavaScript(), or Encode.forHtmlAttribute() when outputting user data. If
using Play Framework, rely on Twirl template auto-escaping which handles context correctly.
For rich content that requires HTML, use a whitelist-based sanitizer like OWASP Java HTML
Sanitizer with a strict allowlist of permitted tags and attributes. Input validation should
focus on business logic constraints, not security filtering. Implement Content Security
Policy (CSP) headers to provide defense-in-depth protection even if output encoding is
missed in some locations.
scala_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
setEscapeModelStrings(false) on Wicket Label components within Scala code. This creates
a Cross-Site Scripting (XSS) vulnerability when the Label 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 in Label components, and explicitly disabling this protection removes a critical
security control. This is particularly dangerous in Scala applications where type safety
might create a false sense of security, as the escaping bypass allows string injection
regardless of type checks.
Remediation:
Consider keeping Wicket's default auto-escaping enabled by ensuring
setEscapeModelStrings(true) is called or relying on Wicket's 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 Label 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 in Scala applications.
scala_xss_rule-XSSReqParamToServletWriter¶
Summary:
Improper Neutralization of Input During Web Page Generation
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() or .print() within Scala
servlet code. This creates a reflected Cross-Site Scripting (XSS) vulnerability where
attackers can inject malicious JavaScript by crafting request parameters obtained via
HttpServletRequest.getParameter() or getQueryString() that are echoed back in the HTTP
response without HTML encoding. 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 in Scala-based web applications.
Remediation:
Consider using the OWASP Java Encoder library's Encode.forHtml() function to escape
user input before writing to the servlet response in Scala code. If writing plain text
responses, set the Content-Type to text/plain with
response.setContentType("text/plain; charset=UTF-8") to prevent browsers from
interpreting output as HTML. For modern Scala web applications, prefer using frameworks
like Play Framework with Twirl templates or Scalatra with SSP/Scaml templates 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 against XSS attacks.
scala_xxe_rule-Document¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses DocumentBuilderFactory.newInstance() to create a DOM parser
without disabling external entity processing, making it vulnerable to XML External
Entity (XXE) attacks. When the DocumentBuilder processes untrusted XML input with
external entity support enabled, attackers can exploit this to read arbitrary files
from the filesystem, perform SSRF attacks against internal network resources,
exfiltrate sensitive data through out-of-band channels, or cause Denial of Service
through billion laughs and entity expansion attacks.
Remediation:
Configure the DocumentBuilderFactory to disable DOCTYPE declarations entirely by
calling setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
before creating the parser. This prevents all XXE vulnerabilities, entity expansion
attacks, and billion laughs DoS by blocking DTD processing completely. Alternatively,
enable XMLConstants.FEATURE_SECURE_PROCESSING for additional security restrictions.
Example: val factory = DocumentBuilderFactory.newInstance;
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
val builder = factory.newDocumentBuilder; builder.parse(inputStream); Additional
guidance at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
scala_xxe_rule-Trans¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses TransformerFactory.newTransformer() to create an XSLT
transformer without disabling external entity processing, making it vulnerable to XML
External Entity (XXE) attacks. When the Transformer processes untrusted XML or XSLT
input with external entity and DTD access enabled, attackers can exploit this to read
arbitrary files, perform SSRF attacks to internal systems, exfiltrate data through
external entity references, or cause Denial of Service through entity expansion and
billion laughs attacks.
Remediation:
Configure the transformer to disable external DTD and schema access by setting
setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "") and
setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "") on the TransformerFactory
before creating the transformer. Additionally, enable
setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) for comprehensive security
restrictions. This prevents XXE attacks, SSRF vulnerabilities, and DoS through entity
expansion. Example: val factory = TransformerFactory.newInstance;
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); val transformer =
factory.newTransformer; See
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
scala_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 the XMLReader processes untrusted XML input with external
entity support enabled, attackers can exploit this to read arbitrary files from the
filesystem, conduct SSRF attacks against internal network services, exfiltrate
sensitive data, or cause Denial of Service through entity expansion attacks. The
XMLReaderFactory class is deprecated and lacks modern security configuration options.
Remediation:
Migrate to SAXParserFactory instead of the deprecated XMLReaderFactory and
configure it to disable DOCTYPE declarations using
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true). This
prevents XXE attacks, entity expansion vulnerabilities, and billion laughs DoS by
completely blocking DTD processing. Alternatively, enable
XMLConstants.FEATURE_SECURE_PROCESSING for comprehensive security restrictions.
Example: val factory = SAXParserFactory.newInstance;
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); val
parser = factory.newSAXParser; parser.parse(inputStream, handler); See
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
scala_xxe_rule-XMLStreamRdr¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses XMLInputFactory.newFactory() and createXMLStreamReader() to
create a StAX XML parser without disabling external entity processing, making it
vulnerable to XML External Entity (XXE) attacks. When the XMLStreamReader processes
untrusted XML input with DTD support and external entities enabled, attackers can
exploit this to read arbitrary files, perform SSRF attacks to internal systems,
exfiltrate data through external DTD references, or cause Denial of Service through
billion laughs and quadratic blowup entity expansion attacks.
Remediation:
Configure the XMLInputFactory to disable both DTD support and external entities
before creating the stream reader by setting
setProperty(XMLInputFactory.SUPPORT_DTD, false) and
setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false). Disabling DTD
support prevents XXE attacks, entity expansion vulnerabilities, and billion laughs DoS
by blocking all DTD processing. Example: val factory = XMLInputFactory.newFactory;
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); val
reader = factory.createXMLStreamReader(inputStream); Additional guidance at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
scala_xxe_rule-XPathXXE¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses DocumentBuilderFactory.newInstance() and newDocumentBuilder()
to create a DOM parser for XPath evaluation without disabling external entity
processing, making it vulnerable to XML External Entity (XXE) attacks. When XPath
expressions are evaluated on DOM documents parsed from untrusted XML input with
external entity support enabled, attackers can exploit this to read arbitrary files,
perform SSRF attacks against internal systems, exfiltrate data, or cause Denial of
Service through entity expansion attacks.
Remediation:
Configure the DocumentBuilderFactory to disable both external DTD and schema access
before creating the document builder by calling
setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""),
setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""), and
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true). This
prevents XXE attacks, entity expansion vulnerabilities, and billion laughs DoS by
blocking all external entity processing and DTD declarations. Example: val factory =
DocumentBuilderFactory.newInstance; factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,
""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); val
builder = factory.newDocumentBuilder; val doc = builder.parse(inputStream); See
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
scala_cookie_rule-CookieHTTPOnly¶
Summary:
Sensitive Cookie Without 'HttpOnly' Flag
Severity: Low
CWE: CWE-1004
Description:
The application creates a javax.servlet.http.Cookie instance without calling
setHttpOnly(true) or explicitly sets it to false with setHttpOnly(false), which makes the
cookie accessible to client-side JavaScript code. This exposes sensitive cookie data to
Cross-Site Scripting (XSS) attacks, where malicious scripts injected into the page can read
session identifiers and other sensitive information. Without the HttpOnly flag, attackers who
successfully exploit XSS vulnerabilities can steal user sessions and impersonate legitimate
users.
Remediation:
Always call setHttpOnly(true) on javax.servlet.http.Cookie instances before adding them
to the response with addCookie(). This prevents client-side scripts from accessing the
cookie through document.cookie, significantly reducing the risk of session hijacking via
XSS attacks. For Play Framework applications, use the httpOnly = true parameter when
creating cookies with the Cookie() constructor or set it in application.conf with
play.http.session.httpOnly = true for session cookies. Consider also enabling the Secure
flag with setSecure(true) to ensure cookies are only transmitted over HTTPS, and implement
the SameSite attribute using cookie.setAttribute("SameSite", "Strict") to provide
additional CSRF protection.
scala_cookie_rule-CookieInsecure¶
Summary:
Information Exposure Through Persistent Cookies
Severity: Low
CWE: CWE-539
Description:
The application creates a javax.servlet.http.Cookie instance without calling
setSecure(true) or explicitly sets it to false with setSecure(false), which allows the
cookie to be transmitted over unencrypted HTTP connections. This exposes sensitive cookie data
to network-based attacks such as man-in-the-middle (MITM) interception, where attackers on the
same network can capture session tokens and other confidential information. Without the Secure
flag, any HTTP request to the domain will include the cookie in plaintext, making it vulnerable
to eavesdropping even if HTTPS is available.
Remediation:
Always call setSecure(true) on javax.servlet.http.Cookie instances to ensure cookies are
only transmitted over encrypted HTTPS connections. This protects sensitive data from network
interception and MITM attacks. For Play Framework applications, configure secure cookies
globally in application.conf with play.http.session.secure = true or use the secure =
true parameter in the Cookie() constructor. Consider also enabling HSTS (HTTP Strict
Transport Security) headers to force all connections to use HTTPS. Additionally, implement the
HttpOnly flag with setHttpOnly(true) and SameSite attribute using
cookie.setAttribute("SameSite", "Strict") for comprehensive cookie security.
scala_cors_rule-PermissiveCORSInjection¶
Summary:
Permissive Cross-domain Policy with Untrusted Domains
Severity: Low
CWE: CWE-942
Description:
User-controlled input is used to set the Access-Control-Allow-Origin CORS
header without validation. This allows attackers to bypass same-origin policy
protections, enabling malicious websites to make authenticated cross-origin
requests and steal sensitive data from your application.
Remediation:
Avoid setting the Access-Control-Allow-Origin header using untrusted input
directly from request parameters. Instead, maintain a static allowlist of
trusted domains and validate incoming origin requests against this list before
setting the header. If the origin matches an allowed domain, set the header to
that specific origin. Never reflect user input directly or use overly permissive
wildcards like "*" when credentials are involved.
scala_inject_rule-CustomInjection¶
Summary:
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
Severity: Low
CWE: CWE-89
Description:
The application uses java.sql.Statement.executeQuery() with SQL queries constructed through
string concatenation, string formatting with String.format(), or StringBuilder.toString(),
which makes the code susceptible to SQL injection attacks. When user-controlled variables are
concatenated directly into SQL query strings without parameterization, attackers can inject
malicious SQL fragments to manipulate query logic, extract sensitive data, modify or delete
records, or in some cases execute system commands through database-specific features.
Remediation:
Consider migrating to java.sql.PreparedStatement with parameterized queries using
placeholder syntax (?) where user input is bound as parameters rather than concatenated
into query strings. Recommended to use Scala database libraries like Slick or Doobie which
provide compile-time checked, type-safe query construction that prevents SQL injection by
design. For Play Framework applications, use Anorm with parameter interpolation or the
built-in database access APIs that enforce parameterization. Never construct SQL through
string concatenation or formatting - always use parameter binding where values are properly
escaped by the database driver. If dynamic query construction is unavoidable, validate
input against strict whitelists and use identifier quoting, but parameterized queries remain
the strongly preferred solution.
scala_ssrf_rule-SSRF¶
Summary:
Server-Side Request Forgery (SSRF)
Severity: Low
CWE: CWE-918
Description:
This rule detected user-controlled input being used to construct Scala 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 Scala'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 Scala applications using Akka HTTP or other HTTP clients, configure custom
connection pools or client settings that enforce IP address filtering at the
network layer. Network-level defenses can include running the application 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.
scala_unsafe_rule-InformationExposure¶
Summary:
Information Exposure Through an Error Message
Severity: Low
CWE: CWE-209
Description:
Information exposure through exception stack traces was detected. Calling
Exception.printStackTrace() outputs detailed debugging information including class names,
method names, line numbers, and file paths to standard error or other streams. This exposes
internal application structure, installation paths, and implementation details that attackers
can use to identify vulnerabilities, plan targeted attacks, or gain knowledge about the
system architecture. Stack traces may also inadvertently reveal sensitive data present in
exception messages or variable names.
Remediation:
Consider replacing printStackTrace() calls with proper logging mechanisms using
frameworks like Logback, SLF4J, or Scala Logging. Recommended to log exceptions
at appropriate levels (ERROR, WARN) with context information while excluding stack
traces from production output. Consider implementing structured logging that
captures exception details securely without exposing them to end users or untrusted
parties. In production environments, configure loggers to write full stack traces
to secure log files accessible only to authorized personnel, while presenting
generic error messages to users. Consider using error tracking services that
aggregate exceptions securely without exposing details through application output.
Recommended to implement separate error handling for development and production
environments using configuration-based approaches.
scala_cookie_rule-CookiePersistent¶
Summary:
Sensitive Cookie in HTTPS Session Without 'Secure' Attribute
Severity: Info
CWE: CWE-614
Description:
The application calls setMaxAge() on a Cookie instance with a value of 31,536,000 seconds
(one year) or greater, creating a long-lived persistent cookie that remains on the client
system for an extended period. Storing sensitive data in persistent cookies with such long
lifespans increases the window of opportunity for attackers to compromise the data through
various attack vectors including XSS, malware, or physical device access. The longer a cookie
persists, the higher the risk that it will be exposed through device theft, shared computer
usage, or cookie theft attacks.
Remediation:
Consider using session cookies (by omitting setMaxAge() or setting it to -1) for sensitive
data so they expire when the browser closes, or set significantly shorter expiration times
based on your security requirements. For authentication cookies, recommended max ages range
from 15-30 minutes for high-security applications to a few hours for standard applications.
Never store sensitive information like passwords, credit card numbers, or personal
identifiable information directly in cookies regardless of expiration time. Instead, store
only session identifiers in cookies and keep sensitive data server-side. For Play Framework,
configure session timeout in application.conf with play.http.session.maxAge to control
the default session duration.
scala_cookie_rule-CookieUsage¶
Summary:
Sensitive Cookie in HTTPS Session Without 'Secure' Attribute
Severity: Info
CWE: CWE-614
Description:
The application reads cookie data using methods like Cookie.getName(), Cookie.getValue(),
or Cookie.getPath() on HttpServletRequest.getCookies() results, which may expose sensitive
information if improperly stored in cookies. Custom cookies should never contain sensitive data
such as passwords, authentication tokens, personal identifiable information, or session state,
as cookies are stored client-side and vulnerable to theft through XSS attacks, malware, or
network interception. Reading and trusting cookie values without proper validation can lead to
security vulnerabilities if the cookie data has been tampered with by an attacker.
Remediation:
Store only session identifiers in cookies and keep all sensitive data server-side in the
session store or database. Use framework session management like HttpSession.setAttribute()
for storing user-specific data securely. For Play Framework applications, use the built-in
session API with encrypted session cookies via request.session to store minimal data. If you
must use custom cookies for non-sensitive preferences or UI state, ensure they are properly
validated and sanitized before use. Consider implementing signed or encrypted cookies using
Play's session.sign() or Spring Security's cookie utilities to detect tampering. Always
treat cookie data as untrusted user input and validate it against expected formats and values
before making security decisions.
scala_cookie_rule-RequestParamToCookie¶
Summary:
Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
Severity: Info
CWE: CWE-113
Description:
The application constructs a javax.servlet.http.Cookie using untrusted data from
HttpServletRequest.getParameter() or sets cookie values with Cookie.setValue() using
request parameters without proper CRLF sanitization. When user-controlled input containing
carriage return and line feed characters is used to create or modify cookies, attackers can
inject arbitrary HTTP headers through response splitting attacks. This vulnerability allows
attackers to perform cache poisoning, inject malicious cookies, redirect users to phishing
sites, or execute cross-site scripting attacks by controlling the HTTP response structure.
Remediation:
Never directly use request parameters to construct cookie values without strict validation and
sanitization. Remove all CRLF characters using replaceAll("[\r\n]", "") before setting
cookie values, or use URL encoding with java.net.URLEncoder.encode(value, "UTF-8") to
neutralize special characters. Consider using the OWASP Java Encoder library's
Encode.forUriComponent() method which provides comprehensive protection against injection
attacks. Validate input against a strict allowlist of expected characters rather than
attempting to filter malicious patterns. For Play Framework, leverage the framework's secure
session management instead of creating cookies from raw request parameters. Additionally,
implement Content Security Policy headers and use framework-provided CSRF protection to add
defense-in-depth.
scala_cookie_rule-TrustBoundaryViolation¶
Summary:
Trust Boundary Violation
Severity: Info
CWE: CWE-501
Description:
The application calls HttpServletRequest.setAttribute() or HttpSession.putValue() with
non-literal values, potentially mixing untrusted user input with trusted application data in
the same session or request scope. This creates a trust boundary violation where data crosses
from the untrusted client side to the trusted server side without proper validation or
distinction. When untrusted and trusted data are stored together in session attributes without
clear separation, developers may mistakenly trust unvalidated user input in security-critical
operations, leading to authorization bypass, privilege escalation, or injection vulnerabilities.
Remediation:
Always validate and sanitize user input before storing it in session or request attributes, and maintain clear separation between trusted and untrusted data. Use distinct naming conventions like prefixing untrusted data attributes with "user_" or "untrusted_" to make the trust boundary explicit. Consider creating separate data transfer objects (DTOs) for validated and unvalidated data rather than mixing them in the same session scope. For Play Framework applications, leverage the framework's form validation and data binding mechanisms to ensure data is validated before storage. Implement server-side validation for all user input using libraries like Hibernate Validator or custom validation logic. Never make security decisions based solely on session attributes that could have been derived from user input without re-validating the data at the point of use.
scala_cors_rule-PermissiveCORS¶
Summary:
Permissive Cross-domain Policy with Untrusted Domains
Severity: Info
CWE: CWE-942
Description:
Permissive Cross-Origin Resource Sharing (CORS) policy detected. The
Access-Control-Allow-Origin header is set to a wildcard (*), null, or reflects
untrusted user input. This allows malicious websites to make cross-origin requests to
this application using a victim's credentials, leading to data theft, spoofing, and
other attacks.
Remediation:
Consider using a static allowlist of trusted domains instead of wildcard (*),
null, or reflecting the request origin in the Access-Control-Allow-Origin
header. Recommended to validate the origin against a predefined set of allowed
domains (e.g., example.com, trusted.com) before setting the header. Never use
wildcard with credentials, as Access-Control-Allow-Credentials: true combined
with Access-Control-Allow-Origin: * is rejected by browsers.
scala_crypto_rule-DefaultHTTPClient¶
Summary:
Inadequate encryption strength
Severity: Info
CWE: CWE-326
Description:
The application uses new org.apache.http.impl.client.DefaultHttpClient() which is not
compatible with TLS 1.2 or higher by default. DefaultHttpClient is a deprecated class from
Apache HttpClient 4.x that uses outdated SSL/TLS configuration and does not support modern
secure transport protocols. Connections established with this client may fall back to TLS 1.0
or even SSLv3, which are known to have security vulnerabilities including POODLE and BEAST
attacks. Additionally, the Apache HttpComponents team has officially deprecated this class and
recommends migration to newer implementations.
Remediation:
Migrate to Apache HttpClient 4.5 or later using HttpClients.createDefault() or
HttpClients.custom() which supports TLS 1.2 and TLS 1.3 by default. For explicit TLS
configuration in Scala, use HttpClients.custom().setSSLContext(sslContext).build() with an
SSLContext configured for TLS 1.2 or higher. Alternatively, consider using modern HTTP
libraries designed for Scala such as sttp, http4s, or Akka HTTP, which provide type-safe
APIs and secure defaults for TLS configuration. When configuring TLS explicitly, ensure you
use SSLContext.getInstance("TLSv1.2") or SSLContext.getInstance("TLSv1.3") and avoid
legacy protocols like SSLv3, TLS 1.0, and TLS 1.1 which have known vulnerabilities.
scala_endpoint_rule-JaxWsEndpoint¶
Summary:
Use of less trusted source
Severity: Info
CWE: CWE-348
Description:
This method is annotated with @javax.jws.WebMethod, marking it as a SOAP web service endpoint (JSR-224) that processes external XML-based requests. SOAP endpoints decorated with JAX-WS annotations expose the application to untrusted user-supplied data in SOAP message payloads, which can introduce security vulnerabilities including XML injection, XXE (XML External Entity) attacks, and unauthorized access if not properly secured. The method parameters derived from SOAP messages should be treated as untrusted sources requiring thorough security validation.
Remediation:
Consider implementing WS-Security standards for JAX-WS SOAP endpoints to ensure proper authentication and authorization. Recommended to use WS-Security Username Token or SAML tokens for authentication rather than relying on transport-layer security alone. Configure your XML parser to disable DTD processing and external entity resolution to prevent XXE attacks by setting appropriate features on the SAXParserFactory or DocumentBuilderFactory. Validate all SOAP message content using XML Schema validation and additional business logic validation before processing. Use HTTPS/TLS exclusively for SOAP communication by configuring endpoint URLs with the https:// scheme and enforcing TLS 1.2 or higher. Consider implementing message- level encryption using WS-Security encryption for sensitive data in SOAP payloads. Apply rate limiting and message size restrictions to prevent denial-of-service attacks against SOAP endpoints.
OWASP:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
scala_endpoint_rule-UnencryptedSocket¶
Summary:
Cleartext transmission of sensitive information
Severity: Info
CWE: CWE-319
Description:
The application creates a socket connection using new java.net.Socket() which
establishes an unencrypted network connection that transmits data in cleartext. This
exposes all transmitted data including potentially sensitive information to
interception and eavesdropping through man-in-the-middle attacks. Unencrypted sockets
provide no confidentiality or integrity protection, allowing attackers with network
access to read or modify data in transit.
Remediation:
Consider using SSLSocket or SSLSocketFactory instead of plain java.net.Socket for network connections that transmit sensitive data. Recommended to create SSL/TLS sockets using SSLSocketFactory.getDefault().createSocket() which uses the default system SSL context with proper certificate validation. For custom SSL configurations, create an SSLContext with appropriate trust managers and use it to create SSLSocketFactory instances. Ensure proper certificate validation by using the default TrustManager implementation rather than creating custom trust managers that bypass validation. Configure the socket to use TLS 1.2 or TLS 1.3 exclusively by calling setEnabledProtocols() with appropriate protocol versions. For hostname verification in client connections, cast the socket to SSLSocket and verify the hostname matches the certificate after connection establishment. Consult the OWASP Transport Layer Protection Cheat Sheet for comprehensive guidance on secure socket implementation.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
scala_endpoint_rule-UnvalidatedRedirect¶
Summary:
URL Redirection to Untrusted Site ('Open Redirect')
Severity: Info
CWE: CWE-601
Description:
The application uses HttpServletResponse methods like sendRedirect(), addHeader(), encodeURL(), or encodeRedirectUrl() with user-supplied parameters that are not validated or restricted to safe values. These redirect and URL manipulation methods can introduce open redirect vulnerabilities when they process untrusted input, allowing attackers to craft URLs that redirect users to malicious external sites. Open redirects are commonly exploited in phishing campaigns where attackers leverage the trusted domain's reputation to deceive users into visiting attacker-controlled sites.
Remediation:
Consider implementing a whitelist-based validation approach for redirect URLs before passing them to HttpServletResponse redirect methods. Recommended to maintain a predefined list of allowed destination URLs or path prefixes and validate user input against this whitelist before performing redirects. For relative paths, ensure the redirect destination starts with "/" and does not contain "://" to prevent absolute URL redirects to external domains. Use URI parsing (java.net.URI) to extract and validate the hostname component, rejecting any redirect that points to an external domain unless explicitly whitelisted. Consider using indirect reference maps where user input specifies a key that maps to a predetermined safe URL rather than accepting full URLs directly. Avoid using user input in Location headers or redirect parameters without validation. For applications requiring flexible redirects, implement a redirect confirmation page that displays the destination and requires user acknowledgment before proceeding.
scala_endpoint_rule-WeakHostNameVerification¶
Summary:
Improper Certificate Validation
Severity: Info
CWE: CWE-295
Description:
The application implements a custom HostnameVerifier or X509TrustManager that accepts all certificates by returning true from verify() methods, leaving check methods empty, or returning null/empty arrays from getAcceptedIssuers(). These trust-all implementations completely disable SSL/TLS certificate validation, making the application vulnerable to man-in-the-middle attacks where attackers can intercept and decrypt HTTPS traffic by presenting any certificate. While often implemented to work around certificate reuse across multiple hosts or development environment issues, these implementations eliminate the security guarantees that TLS is designed to provide.
Remediation:
Consider using the default SSL/TLS certificate validation provided by the JVM rather than implementing custom HostnameVerifier or X509TrustManager classes. Recommended to remove trust-all implementations and rely on SSLContext.getDefault() which performs proper certificate chain validation and hostname verification. For legitimate cases requiring custom validation, implement proper certificate checking by validating the certificate chain, expiration dates, and hostname matching rather than accepting all certificates. If working with self-signed certificates in non- production environments, create a custom truststore containing only the specific trusted certificates and load it using KeyStore and TrustManagerFactory rather than disabling validation entirely. Use HttpsURLConnection.setDefaultHostnameVerifier() or HttpsURLConnection.setDefaultSSLSocketFactory() with properly configured SSL contexts for global HTTPS client configuration. For certificate reuse across multiple hostnames, configure Subject Alternative Names (SAN) in certificates rather than disabling hostname verification.
scala_file_rule-FileUploadFileName¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Info
CWE: CWE-22
Description:
Path traversal vulnerability in file upload handling detected using 'FileItem.getName()'. This method returns filenames directly from client requests, which can be manipulated to include path traversal sequences like '../' or absolute paths. Using unsanitized filenames can allow attackers to write files to arbitrary locations on the server filesystem, potentially overwriting critical files.
Remediation:
Consider extracting only the base filename without any path components from 'getName()' results. Recommended to strip all path separator characters like '/', '\', and '..' sequences before using the filename. Validate file extensions against a strict allowlist of permitted types. Generate random filenames instead of using client-provided names when possible, storing the original name separately in metadata.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_form_rule-FormValidate¶
Summary:
Improper validation of unsafe equivalence in input
Severity: Info
CWE: CWE-1289
Description:
Missing validation method in form class detected. This class extends ActionForm or
ValidatorForm but does not implement a validate() method, leaving user input
unchecked. Without proper validation, malicious input can bypass security controls
and lead to injection attacks, data corruption, or unauthorized operations. Form
validation provides essential defense-in-depth against various input-based threats.
Remediation:
Consider implementing a validate() method in form classes that extend
ActionForm or ValidatorForm to ensure proper input validation. Recommended to
validate all user-supplied data including length, format, type, and range
constraints before processing. Use allowlists for acceptable values when
possible, and sanitize inputs to prevent injection attacks. Validation should
occur server-side even if client-side checks exist.
scala_inject_rule-AWSQueryInjection¶
Summary:
Improper Neutralization of Special Elements in Data Query Logic
Severity: Info
CWE: CWE-943
Description:
The application uses com.amazonaws.services.simpledb.model.SelectRequest to construct
AWS SimpleDB queries with untrusted user input, which can allow an attacker to modify
query logic and view unauthorized records. This NoSQL injection vulnerability occurs when
user-controlled data is concatenated directly into SelectExpression strings without proper
validation or parameterization, enabling attackers to inject special characters and
manipulate the query structure to access sensitive data across domains.
Remediation:
Consider implementing strict input validation that whitelists only expected characters and patterns for query parameters. Recommended to use parameterized queries where possible, or escape special SimpleDB characters like single quotes, backticks, and operators that could alter query logic. For more robust protection, validate that user input matches expected formats (e.g., UUIDs, alphanumeric IDs) and reject any input containing SQL-like keywords or operators. Consider migrating to DynamoDB which provides better parameterized query support through its Query and Scan operations with proper attribute value binding.
scala_inject_rule-BeanPropertyInjection¶
Summary:
External Control of System or Configuration Setting
Severity: Info
CWE: CWE-15
Description:
The application uses org.apache.commons.beanutils.BeanUtils.populate() or
BeanUtilsBean.populate() with user-controlled Map data populated from
HttpServletRequest.getParameter() or HttpServletRequest.getParameterValues(), which
allows attackers to set arbitrary bean properties and compromise system integrity. Attackers
can leverage this to access dangerous properties like class.classLoader that allow
overriding system properties and potentially achieving arbitrary code execution through
classloader manipulation.
Remediation:
Consider implementing a whitelist-based approach where only explicitly allowed bean
property names can be set from user input. Recommended to avoid using BeanUtils.populate()
directly with request parameters, and instead manually map only the specific properties
your application needs. Can use a Data Transfer Object (DTO) pattern with explicit field
mappings rather than automatic population. For frameworks like Spring MVC, use
@InitBinder with WebDataBinder.setAllowedFields() to restrict which properties can be
bound from HTTP requests. Never allow user input to control property names - only property
values should come from users, and property names should be hardcoded in your application.
scala_inject_rule-CLRFInjectionLogs¶
Summary:
Improper Neutralization of CRLF Sequences ('CRLF Injection')
Severity: Info
CWE: CWE-93
Description:
The application logs user input from HttpServletRequest.getParameter() using logging
frameworks (Log4j, SLF4J, java.util.logging, Apache Commons Logging, TinyLog) without
neutralizing CRLF sequences, which allows attackers to forge log entries or inject malicious
content. Attackers can inject newline characters (\r\n) to create false log entries that
skew statistics, distract administrators, or implicate others in malicious acts. If log files
are processed automatically, attackers can corrupt file formats or inject commands that
exploit vulnerabilities in log processing utilities through command injection or XSS attacks.
Remediation:
Consider sanitizing all user input before logging by replacing or removing CRLF characters
(\r and \n). Recommended to use replaceAll("[\r\n]", "") or URL encoding functions like
java.net.URLEncoder.encode() or OWASP Encoder's forUriComponent() before passing data
to logging methods. For structured logging, can use parameterized logging with proper
escaping (e.g., SLF4J's parameterized messages) which helps separate log data from format
strings. Consider implementing a centralized input sanitization utility that normalizes all
user input before logging. Some logging frameworks like Logback offer built-in encoding
options that can automatically escape newlines in logged data.
scala_inject_rule-CommandInjection¶
Summary:
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
Severity: Info
CWE: CWE-78
Description:
The application uses Runtime.getRuntime().exec() or ProcessBuilder.command() to execute
system commands with user-controlled input passed through string parameters, concatenation,
or shell invocation patterns. When unfiltered input is passed to these APIs, especially when
using shell interpreters (sh, bash, ksh, csh, tcsh, zsh) or string formatting/concatenation,
attackers can inject shell metacharacters and operators to execute arbitrary commands. This
vulnerability allows complete system compromise as commands execute with the application's
privilege level.
Remediation:
Consider avoiding shell interpreters entirely by using ProcessBuilder with array arguments where each argument is a separate array element, preventing shell interpretation of metacharacters. Recommended to validate and whitelist user input against a strict set of allowed values (e.g., alphanumeric characters only) if it must be included in commands. For safer execution, use higher-level APIs like Apache Commons Exec with proper argument sanitization, or consider language-native libraries that avoid system calls (e.g., use Java NIO for file operations instead of system commands). If shell features are absolutely required, use parameterized execution frameworks that handle escaping automatically, and never allow user input to specify command names or paths - only constrained arguments for predetermined commands.
scala_inject_rule-FileDisclosure¶
Summary:
Files or Directories Accessible to External Parties
Severity: Info
CWE: CWE-552
Description:
The application constructs server-side redirect or forward paths using user input from
HttpServletRequest.getParameter() in Spring Framework's ModelAndView constructors or
setViewName(), Apache Struts' ActionForward constructors or setPath(), or Servlet's
RequestDispatcher.include()/forward() methods. This allows attackers to manipulate view
paths to download application binaries (including application classes, JAR files, or
configuration files) or view arbitrary files within protected directories through path
traversal or direct file access attacks.
Remediation:
Consider implementing a whitelist-based approach where user input is mapped to predefined view names through a lookup table or enumeration, never allowing direct path construction from user data. Recommended to use indirect references like view IDs that map to actual paths server-side (e.g., user provides "dashboard" which maps to "/WEB-INF/views/dashboard.jsp"). For Spring MVC, configure view resolvers with fixed prefixes and suffixes so user input only determines the view name, not the full path. For Struts, use struts-config.xml forward definitions rather than programmatic path setting. Validate that any user-controlled path components contain only alphanumeric characters and do not include path traversal sequences (../, ..\, etc.). Consider using framework-level view resolution mechanisms that restrict accessible paths to specific directories.
scala_inject_rule-HttpParameterPollution¶
Summary:
Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
Severity: Info
CWE: CWE-88
Description:
The application concatenates unvalidated user input from HttpServletRequest.getParameter()
into HTTP URLs used in Apache HttpClient's HttpGet or Apache Commons HttpClient's
GetMethod constructors and setQueryString(), which enables HTTP Parameter Pollution (HPP)
attacks. Attackers can inject encoded query string delimiters (&, =, ?) into parameter values
to override existing parameters, inject new parameters, or exploit variables outside direct
reach. Without proper URL encoding, attackers can compromise application logic to perform
client-side or server-side attacks by manipulating request parameters sent to backend systems.
Remediation:
Consider using java.net.URLEncoder.encode() with UTF-8 charset to properly encode all
user input before concatenating it into URLs or query strings. Recommended to use URL
builder utilities like Apache HttpClient's URIBuilder which handles parameter encoding
automatically through addParameter() methods. For more robust encoding, can use Guava's
UrlEscapers.urlPathSegmentEscaper().escape() which provides comprehensive escaping. Always
encode parameter names and values separately before concatenation - encoding the entire URL
after construction is insufficient. Consider validating that user input matches expected
patterns (alphanumeric, specific character sets) and rejecting inputs containing URL
metacharacters like &, =, ?, #, or %.
scala_inject_rule-SpotbugsPathTraversalAbsolute¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Info
CWE: CWE-22
Description:
The application constructs file paths from HttpServletRequest.getParameter() and uses them
in file operations including java.io.File, java.io.FileInputStream, java.io.FileReader,
java.io.FileWriter, java.io.FileOutputStream, java.io.RandomAccessFile,
javax.activation.FileDataSource, java.nio.file.Paths.get(), and temporary file creation
APIs. The application does not properly neutralize absolute path sequences (like "/etc/passwd"
or "C:\Windows\System32\config\sam") that bypass relative path restrictions. When users
provide absolute paths, they can access or modify files anywhere on the filesystem regardless
of intended directory restrictions.
Remediation:
Consider using org.apache.commons.io.FilenameUtils.getName() which extracts only the
filename component and strips all directory path information including absolute paths.
Recommended to reject any user input beginning with path separators (/, ) or Windows drive
letters (C:, D:) before processing. Can validate that constructed paths use File.isAbsolute()
and reject absolute paths, ensuring only relative paths within a designated base directory
are accepted. For robust protection, use File.getCanonicalPath() to resolve the full path
and verify it starts with your intended base directory using startsWith(). Consider using
indirect references where users provide IDs that map to filenames server-side, eliminating
direct path control. Configure file access with principle of least privilege - run
application with minimal filesystem permissions.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_inject_rule-SpotbugsPathTraversalRelative¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Info
CWE: CWE-22
Description:
The application constructs file paths by concatenating HttpServletRequest.getParameter() with
other strings using string concatenation operators, then uses these paths in file operations
including java.io.File, java.io.FileInputStream, java.io.FileReader, java.io.FileWriter,
java.io.FileOutputStream, java.io.RandomAccessFile, javax.activation.FileDataSource,
java.nio.file.Paths.get(), and temporary file creation. The application does not properly
neutralize relative path traversal sequences like "../" or "..\" that can resolve to locations
outside restricted directories. Attackers can traverse up directory hierarchies to access or
modify sensitive files, configuration data, or system files.
Remediation:
Consider using org.apache.commons.io.FilenameUtils.getName() which removes directory
components including parent directory references (..). Recommended to use
java.nio.file.Path.normalize() to collapse traversal sequences, then verify the normalized
path is still within the intended base directory using startsWith(). Can implement
validation that rejects any user input containing ".." sequences, path separators (/, ), or
other path metacharacters before concatenation. For stronger protection, use
File.getCanonicalPath() to fully resolve the path including symlinks and verify the result
is a descendant of your allowed directory. Consider using safer patterns like generating
random filenames server-side and maintaining a separate mapping to user-provided names,
eliminating user control over actual filesystem paths.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
scala_ldap_rule-AnonymousLDAP¶
Summary:
Improperly implemented security check for standard
Severity: Info
CWE: CWE-358
Description:
Setting 'Context.SECURITY_AUTHENTICATION' to "none" disables authentication for LDAP connections, allowing anonymous binds to the directory server. This exposes the LDAP server to unauthorized access and enables attackers to query, modify, or extract sensitive directory information without credentials. Anonymous LDAP authentication should never be used in production environments.
Remediation:
Never set 'Context.SECURITY_AUTHENTICATION' to "none" for LDAP connections. Recommended to use "simple" authentication with proper credentials (username and password) or stronger mechanisms like SASL for LDAP binds. Consider implementing certificate-based authentication or Kerberos for enhanced security. Always validate that LDAP connections are authenticated and use encrypted transports (LDAPS) to protect credentials in transit.
scala_perm_rule-DangerousPermissions¶
Summary:
Insecure inherited permissions
Severity: Info
CWE: CWE-277
Description:
Granting dangerous Java security permissions such as RuntimePermission
with createClassLoader or ReflectPermission with suppressAccessChecks
via PermissionCollection.add() can compromise application security.
The createClassLoader permission allows code to instantiate custom class
loaders that can bypass security restrictions, while suppressAccessChecks
disables Java's access control checks, enabling unauthorized access to
private fields and methods through reflection. These permissions can be
exploited to escalate privileges, access sensitive data, or execute
arbitrary code.
Remediation:
Consider using the principle of least privilege when configuring security
permissions. Recommended to grant only the minimum permissions necessary
for your application to function correctly. Instead of granting broad
permissions like createClassLoader or suppressAccessChecks, consider
using more specific and restricted permissions that limit the scope of
access. If reflection is required, consider using method handles or other
safer alternatives that don't require suppressing access checks. For
class loading, consider using the application's default class loader or
implementing a custom security policy that restricts which classes can be
loaded. Review your security policy file and ensure that dangerous
permissions are only granted to trusted code sources with appropriate code
signing and verification. Consider implementing runtime security monitoring
to detect and prevent privilege escalation attempts.
scala_script_rule-ScriptInjection¶
Summary:
Improper Control of Generation of Code ('Code Injection')
Severity: Info
CWE: CWE-94
Description:
User-controlled input is passed to 'ScriptEngine.eval()', allowing attackers to execute arbitrary code within the application context. This can potentially lead to complete system compromise, data exfiltration, or privilege escalation. Script injection vulnerabilities are particularly dangerous as they provide direct code execution capabilities.
Remediation:
Consider avoiding the use of dynamic script evaluation with user input entirely. Recommended to refactor code to use static method calls or predefined operations instead. If script evaluation is absolutely necessary, implement strict allowlist validation for function names and parameters. Never pass unsanitized user input to 'eval()' as this function executes arbitrary code with the application's privileges.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
scala_strings_rule-FormatStringManipulation¶
Summary:
Use of Externally-Controlled Format String
Severity: Info
CWE: CWE-134
Description:
Using untrusted input from javax.servlet.http.HttpServletRequest.getParameter() directly in
format string methods like String.format(), java.util.Formatter.format(), or
System.out.printf() allows attackers to control the format specifiers. Attackers can inject
malicious format strings such as %n (which writes data), %s (to leak unused arguments),
or invalid specifiers to cause uncaught exceptions that crash the application. This is
particularly dangerous when sensitive data is passed in the variadic arguments, as attackers
can manipulate the format string to reveal information that was not intended to be displayed.
Remediation:
Consider using parameterized logging or string concatenation instead of format strings
when incorporating user input into output. If format strings are necessary, recommended to
use a whitelist approach where only predefined, safe format templates are used and user
input is strictly limited to the data arguments (never the format string itself). For
logging scenarios, consider using SLF4J with parameterized messages like
logger.info("User action: {}", userInput) which safely handles the substitution. Always
validate and sanitize user input before use, and implement proper exception handling to
prevent application crashes from malformed format specifiers. If dynamic formatting is
absolutely required, consider implementing strict input validation that rejects any strings
containing format specifier characters like %.
scala_strings_rule-ModifyAfterValidation¶
Summary:
Collapse of data into unsafe value
Severity: Info
CWE: CWE-182
Description:
The code applies validation using a regex Pattern.matcher() on a string variable, then
subsequently modifies that same string using String.replace() or similar transformation
methods. This violates the principle of performing string modifications before validation,
as described in CERT guideline IDS11-J. Modifying strings after validation can invalidate
the security checks, allowing malicious input to bypass validation by introducing dangerous
characters or patterns through the transformation that were not present during the initial
validation check, potentially leading to injection attacks or other security vulnerabilities.
Remediation:
Consider performing all string transformations including replace(), replaceAll(),
toLowerCase(), toUpperCase(), and Unicode normalization operations before applying
validation checks with regex matchers or other validation logic. Recommended to establish
a canonical form of the input string first through all necessary transformations, then
validate the canonicalized string to ensure the validation accurately reflects the final
form that will be used. If modification after validation is unavoidable, re-validate the
string after transformation to ensure it still meets the security requirements. This
defense-in-depth approach prevents attackers from exploiting the gap between validation
and use by injecting malicious content through string transformation operations.
scala_strings_rule-NormalizeAfterValidation¶
Summary:
Collapse of data into unsafe value
Severity: Info
CWE: CWE-182
Description:
The code validates a string variable using Pattern.matcher() to check for dangerous
characters like '<' or '>', then subsequently normalizes the string using
java.text.Normalizer.normalize(). This violates CERT guideline IDS01-J which requires
normalizing strings before validation. Unicode normalization can combine or decompose
characters, potentially creating dangerous characters like '<' or '>' from character sequences
that appeared safe during validation. For example, the Unicode character U+FF1C (fullwidth
less-than) normalizes to '<', allowing attackers to bypass validation and inject HTML/XML
metacharacters that can lead to cross-site scripting or other injection vulnerabilities.
Remediation:
Consider applying java.text.Normalizer.normalize() with an appropriate normalization form
(typically NFC or NFKC) before performing validation checks to ensure the validation operates
on the canonical form of the string. Recommended to use NFKC (Normalization Form KC) for
security-sensitive validation as it performs both compatibility decomposition and canonical
composition, preventing Unicode-based validation bypasses. Always establish a consistent
normalization policy across your application where untrusted input is normalized immediately
upon receipt, then validated in its normalized form. Be aware that different normalization
forms (NFC, NFD, NFKC, NFKD) have different security implications - NFKC is generally
preferred for security boundaries as it handles the widest range of equivalent character
representations, preventing attackers from using obscure Unicode characters to bypass filters.
scala_templateinjection_rule-TemplateInjection¶
Summary:
Improper Control of Generation of Code ('Code Injection')
Severity: Info
CWE: CWE-94
Description:
Template injection vulnerability detected in template processing methods. User-
controlled input is being passed to template engines via Velocity.evaluate(),
getTemplate(), or process() without proper sanitization. If an attacker can
control template content or template names, they can execute arbitrary code on the
server, access sensitive data, or compromise the entire application. Template
engines should treat templates as executable code, not data.
Remediation:
Consider using hardcoded template names or paths instead of accepting user input for template selection. Recommended to use VelocityContext to safely pass data to templates rather than evaluating user-controlled template strings directly. If dynamic templates are required, implement strict allowlist validation for template names and ensure template content cannot be modified by users. Consider using a sandboxed template environment with restricted permissions.
scala_unsafe_rule-SensitiveDataExposure¶
Summary:
Exposure of sensitive system information to an unauthorized control sphere
Severity: Info
CWE: CWE-497
Description:
Sensitive configuration data exposure in Play Framework was detected. Configuration values
retrieved using Configuration.underlying.getString() are being returned directly in HTTP
responses via Ok(). This exposes internal system configuration including database
credentials, API keys, internal URLs, security settings, and other confidential parameters
to unauthorized users. Attackers can leverage this information to compromise the application,
access backend systems, or identify security weaknesses in the deployment environment.
Remediation:
Consider implementing strict access controls to prevent configuration data from being exposed in HTTP responses. Recommended to separate public-facing configuration values from sensitive internal settings, using different configuration namespaces or files. Avoid returning raw configuration values directly to users; instead, transform and sanitize data before inclusion in responses. Consider implementing an allow-list of safe configuration keys that can be exposed, rejecting requests for any unlisted parameters. Recommended to use Play Framework's configuration API methods that support default values and type safety, avoiding direct access to underlying Typesafe Config. Consider encrypting sensitive configuration values at rest and decrypting them only when needed internally, never in user-facing contexts. Implement comprehensive logging and monitoring of configuration access attempts to detect potential reconnaissance activities by attackers.
scala_xml_rule-ApacheXmlRpc¶
Summary:
Deserialization of Untrusted Data
Severity: Info
CWE: CWE-502
Description:
Calling setEnabledForExtensions(true) on XmlRpcServerConfigImpl() or
XmlRpcClientConfigImpl() in Apache XML-RPC enables dangerous serialization extensions
that allow arbitrary Java object deserialization. This creates a critical remote code
execution vulnerability when processing untrusted XML-RPC requests, as attackers can
craft malicious payloads to instantiate arbitrary classes and execute code on the server.
Remediation:
Consider keeping extensions disabled (the default behavior) by never calling
setEnabledForExtensions(true) on XML-RPC configuration objects. If extended data
types are required, recommended to use explicit type mapping with TypeFactory and
register only the specific types needed via TypeConverterFactory.createTypeConverter().
For applications requiring complex data structures, consider migrating to modern RPC
frameworks like gRPC or REST APIs with JSON, which provide better security controls
and type safety without deserialization risks. If XML-RPC must be used, implement
strict input validation and consider running the XML-RPC service in a sandboxed
environment with restricted permissions to limit the impact of potential exploits.
scala_xss_rule-MVCApi¶
Summary:
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Severity: Info
CWE: CWE-79
Description:
The application is returning user-supplied data from Scala Play Framework Action
parameters directly in an Ok() response without proper HTML encoding. This creates a
Cross-Site Scripting (XSS) vulnerability where attackers can inject malicious JavaScript
by crafting request parameters that are echoed back in the HTTP response. The rule detects
taint flow from Action function String parameters to Play's Ok() response constructor,
which will render the untrusted content without automatic escaping unless templates are
used. This is particularly dangerous in Scala applications where type safety might create
a false sense of security, as string concatenation and direct response construction bypass
Play's template auto-escaping mechanisms.
Remediation:
Consider using Play Framework's Twirl template engine which provides automatic HTML
escaping by default for all template variables. If you must construct responses directly
with Ok(), use org.owasp.encoder.Encode.forHtml() to escape user input before
including it in the response. For HTML responses, prefer returning Ok(views.html.mytemplate(data))
where Twirl will automatically escape variables. If you need to render raw HTML from
trusted sources, explicitly mark it as safe with Html() constructor, but never apply
this to user input. For JSON responses, use Play's built-in JSON library which handles
escaping automatically. Implement Content Security Policy (CSP) headers using Play's
filters to provide defense-in-depth protection against XSS attacks.
scala_xss_rule-XSSServlet¶
Summary:
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Severity: Info
CWE: CWE-79
Description:
The application is writing user-supplied data from HTTP request parameters directly to
the HTTP response via HttpServletResponse.getWriter().write() within Scala servlet code.
This creates a Cross-Site Scripting (XSS) vulnerability where attackers can inject malicious
JavaScript by crafting request parameters obtained via HttpServletRequest.getParameter()
that are echoed back without HTML encoding. The rule detects taint flow from servlet request
parameters to response writer methods, a classic reflected XSS pattern. Without proper
output encoding, malicious scripts will execute in victims' browsers, potentially leading
to session hijacking, credential theft, defacement, or other client-side attacks in
Scala-based servlet applications.
Remediation:
Consider using the OWASP Java Encoder library's Encode.forHtml() function to escape
user input before writing to the servlet response in Scala code. If writing plain text
responses, set the Content-Type to text/plain with
response.setContentType("text/plain; charset=UTF-8") to prevent browsers from
interpreting output as HTML. For modern Scala web applications, prefer using frameworks
like Play Framework with Twirl templates or Scalatra with SSP/Scaml templates 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 against XSS attacks.
scala_xxe_rule-SaxParserXXE¶
Summary:
Improper Restriction of XML External Entity Reference ('XXE')
Severity: Info
CWE: CWE-611
Description:
The application uses SAXParserFactory.newInstance() and newSAXParser() to create
an XML parser without disabling external entity processing, making it vulnerable to
XML External Entity (XXE) attacks. When the SAX parser processes untrusted XML input
without proper security features configured, attackers can exploit external entity
references to read arbitrary files, perform SSRF attacks against internal services,
exfiltrate data through out-of-band channels, or trigger Denial of Service through
entity expansion attacks like billion laughs.
Remediation:
Configure the SAXParserFactory to disable DOCTYPE declarations entirely by calling
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) before
creating the parser. This prevents all XXE vulnerabilities, entity expansion attacks,
and billion laughs DoS by blocking DTD processing completely. Alternatively, enable
XMLConstants.FEATURE_SECURE_PROCESSING for additional security restrictions.
Example: val factory = SAXParserFactory.newInstance;
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); val
parser = factory.newSAXParser; parser.parse(inputStream, handler); Additional guidance
at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java