Kiuwan logo

Java code security: Vulnerabilities, scanning, and best practices

Java-code-security-Vulnerabilities-scanning-and-best-practices-blog-image

Java applications face two distinct sources of security risk: vulnerabilities in proprietary code and vulnerabilities in third-party dependencies.

The Datadog State of DevSecOps 2026 report found known exploitable vulnerabilities in 59% of the Java services included in its analysis—the highest rate among the languages it evaluated. The report also found that Java dependencies were a median of 492 days behind the latest release in their current major version.

Those findings should not be interpreted to mean that Java itself is inherently insecure. Datadog’s analysis focused on vulnerabilities in third-party libraries used by services participating in its Software Composition Analysis program. The results instead demonstrate the security burden created by large dependency trees, delayed updates, and widely deployed Java frameworks.

Dependencies are only one part of Java code security. Vulnerabilities such as SQL injection, insecure deserialization, cross-site scripting (XSS), and missing authorization controls can originate in proprietary application code and may never appear in a CVE feed.

Teams need static application security testing (SAST) for proprietary code and software composition analysis (SCA) for open-source components. They also need secure coding practices that reduce the number of vulnerabilities introduced in the first place.

Key takeaways

  • Java code security includes both proprietary application code and third-party dependencies.
  • Datadog found known exploitable dependency vulnerabilities in 59% of the Java services in its 2026 analysis.
  • Java dependencies in the same study were a median of 492 days behind the latest release in their current major version.
  • SAST identifies potentially vulnerable patterns and data flows in proprietary code, while SCA identifies known risks in direct and transitive dependencies.
  • Parameterized queries, restricted deserialization, context-appropriate output encoding, vetted cryptography, and consistent authorization checks can reduce common Java security risks.
  • Scanner accuracy, remediation guidance, IDE feedback, and risk-based CI/CD gates all affect whether developers act on security findings.

Why Java services have significant dependency exposure

Large and mature dependency trees

Java has a long history in enterprise software. Many applications rely on extensive Maven or Gradle dependency trees that include application frameworks, web servers, logging libraries, serialization tools, and other foundational components.

Each direct dependency may bring in multiple transitive dependencies. A development team may never explicitly select those indirect packages, but vulnerabilities in them can still affect the application.

The Datadog study found that 59% of the Java services in its sample contained at least one known exploitable dependency vulnerability. According to the report’s methodology, the analysis covered third-party libraries used by applications participating in Datadog’s SCA program, with vulnerability data collected from sources including the CISA Known Exploited Vulnerabilities catalog, NIST, ExploitDB, and GitHub Advisories.

Delayed dependency updates

Datadog also found that the median dependency across all evaluated ecosystems was 278 days behind the latest release in its current major version. Java had a longer median lag of 492 days.

A dependency being behind the latest release does not automatically mean it is vulnerable. However, large update gaps can make security remediation more difficult when a vulnerability is disclosed. Teams may need to work through breaking changes, framework incompatibilities, or several intermediate updates before reaching a fixed version.

Regular, incremental dependency maintenance can make urgent security updates easier to apply than allowing several years of version drift to accumulate.

Two separate risk layers

Java security programs need to address two layers:

Attack surfaceWhat it includesPrimary analysis method
Proprietary codeJava application code written or maintained by the organizationSAST and secure code review
Dependency treeDirect and transitive Maven or Gradle componentsSCA and dependency analysis

SAST and SCA are complementary. One cannot substitute for the other because they examine different sources of risk.

Common Java application security risks

No fixed group of vulnerabilities accounts for every Java security failure. However, the following risks deserve consistent attention because they appear frequently in Java web and enterprise applications.

Security riskReferenceCommon Java patternPrimary analysis
SQL injectionCWE-89String concatenation in JDBC, HQL, or native ORM queriesSAST and code review
Insecure deserializationCWE-502Deserializing untrusted Java object streamsSAST, configuration review, and testing
Cross-site scriptingCWE-79Rendering untrusted data without context-appropriate encodingSAST and application testing
Missing authorizationCWE-862Sensitive operations without an enforced access-control decisionCode review, SAST, and authorization testing
Vulnerable dependenciesOWASP A03:2025Known vulnerabilities or malicious code in direct and transitive componentsSCA and supply-chain controls

1. SQL injection in JDBC and ORM queries

SQL injection occurs when untrusted input changes the structure of a database query.

In Java Database Connectivity (JDBC), the vulnerability commonly appears when developers build queries through string concatenation and execute them with a raw Statement. Similar vulnerabilities can occur when HQL, JPQL, or native ORM queries are dynamically assembled from user-controlled values.

For example, this JDBC code is vulnerable:

String query =
    "SELECT id, email FROM users WHERE email = '" + email + "'";

Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(query);

A safer implementation uses PreparedStatement and binds the value separately:

PreparedStatement statement =
    connection.prepareStatement(
        "SELECT id, email FROM users WHERE email = ?"
    );

statement.setString(1, email);
ResultSet results = statement.executeQuery();

In Hibernate, use named parameters or other parameter-binding APIs rather than interpolating values into HQL or native SQL.

An ORM can reduce SQL injection risk when used correctly, but it does not automatically prevent injection. Raw queries and dynamically assembled query fragments can still be vulnerable.

The OWASP SQL Injection Prevention Cheat Sheet recommends prepared statements with parameterized queries as a primary defense.

2. Insecure deserialization of untrusted data

Java native serialization can reconstruct complex object graphs from byte streams. If an application deserializes attacker-controlled data, classes available on the classpath may be used in unexpected ways. Depending on the available classes and application behavior, this can lead to denial of service, data manipulation, or remote code execution.

Risk may appear in:

  • Applications accepting serialized Java objects from external sources
  • Remote Method Invocation endpoints
  • Messaging or caching systems
  • Legacy protocols
  • Libraries that expose native deserialization entry points

The safest approach is to avoid native Java serialization for untrusted input whenever possible. If an application must deserialize Java objects, use Java’s supported serialization-filtering mechanisms to restrict permitted classes, graph depth, references, array size, and stream size.

Alternative data formats such as JSON do not automatically remove deserialization risk. Libraries still need secure configuration, expected-type restrictions, input validation, and appropriate limits. Features that allow arbitrary polymorphic type creation should be reviewed carefully.

3. Cross-site scripting in Java templates

XSS occurs when an application renders untrusted data in a browser without encoding it for the correct output context.

In JSP, risk can arise from directly rendering untrusted values through expressions that do not apply appropriate encoding. In Thymeleaf, th:text escapes text by default, while th:utext deliberately renders unescaped HTML and should be used only with trusted or properly sanitized content.

Protection depends on the output context. HTML element content, attributes, URLs, JavaScript, and CSS require different encoding rules. A single generic escaping function is not sufficient for every context.

SAST can identify some flows from untrusted input to output sinks, while dynamic testing can confirm whether the application renders executable content.

The OWASP Cross-Site Scripting Prevention Cheat Sheet provides context-specific encoding guidance.

4. Missing or inconsistent authorization

Authentication confirms who a user is. Authorization determines what that user is permitted to do.

Java applications may enforce access controls at the controller or route level but fail to apply the same rules to service methods, background jobs, internal APIs, or alternate invocation paths. That inconsistency can allow an authenticated user or service to perform an action it should not be able to perform.

Spring Security supports request-level and method-level authorization. For sensitive business operations, method-security annotations such as @PreAuthorize can enforce an authorization decision when the method is invoked.

However, adding an annotation to every method is not a complete authorization design. Teams should:

  • Deny access by default
  • Centralize authorization policy where practical
  • Enforce object- and tenant-level access
  • Apply checks consistently across every invocation path
  • Test authorization using multiple roles and ownership conditions
  • Avoid relying on user-interface restrictions as security controls

The OWASP Authorization Cheat Sheet provides broader guidance for designing access controls.

5. Direct and transitive dependency risk

The OWASP Top 10:2025 lists Software Supply Chain Failures as A03. This category expands beyond known vulnerable components to include risks involving dependencies, build systems, distribution infrastructure, and other parts of the software supply chain.

It is an application security awareness category, not a compliance ranking.

A Java application may directly import one library that introduces several other packages transitively. If a vulnerability appears in an indirect component, developers may not recognize where it entered the application without a complete dependency graph.

Log4Shell, tracked as CVE-2021-44228, demonstrated how a vulnerability in a widely used Java library can affect many applications. In some environments, Log4j was a direct dependency; in others, it entered through another framework or component.

SCA should analyze direct and transitive dependencies, but detection is only the first step. Teams also need to determine whether the vulnerable code is reachable, whether the affected component is deployed, whether an exploit is available, and which upgrade path will remediate the issue safely.

How to build Java security scanning that developers use

A scanning program succeeds only when developers trust the findings and can act on them within their normal workflow.

Evaluate accuracy and coverage together

A scanner that generates excessive false positives can train developers to ignore alerts. However, a low false-positive rate is not useful if the tool misses important vulnerabilities.

Evaluate:

  • Confirmed true positives
  • Confirmed false positives
  • Important weaknesses missed by the scanner
  • Source-to-sink data-flow accuracy
  • Java framework coverage
  • Triage time
  • Remediation quality
  • Scan performance

The 2026 Sembi Software Quality Pulse Report draws on responses from 3,825 software quality and security professionals. Respondents estimated that, on average, only 51% of detected security issues were true positives. This finding reinforces the need to tune rules, establish triage workflows, and measure scanner performance on representative code.

In a previous analysis using the OWASP Benchmark, Kiuwan reported a 100% true-positive rate and a 16.7% false-positive rate in the controlled test suite. Because the OWASP Benchmark assessment uses code generated specifically for testing security tools, those figures should not be treated as a guarantee of performance on every production Java application. Teams should validate any tool against their own codebase and frameworks.

Provide feedback in the IDE and CI/CD pipeline

Integrated Development Environment (IDE) analysis can identify potential issues while the code is still fresh in the developer’s mind. Pipeline analysis then applies consistent checks before code is merged or released.

A layered approach may include:

  • IDE feedback during development
  • Pre-commit or pull-request analysis
  • CI/CD scans for every relevant change
  • Broader scheduled or release-level analysis
  • Continuous monitoring for newly disclosed dependency vulnerabilities

Kiuwan Code Security supports local and CI/CD analysis. Kiuwan also provides IDE integrations for Eclipse-based, JetBrains, Visual Studio, and VS Code environments, although available analyzer and viewer capabilities vary by IDE. Documented CI/CD options include plugins for Jenkins and Azure DevOps, GitLab CI integration through Kiuwan Local Analyzer, and command-line use with other CI/CD platforms.

Introduce risk-based quality gates

Do not immediately block an established Java application on every existing finding. That approach can overwhelm development teams and encourage bypasses.

A more practical rollout may begin with visibility and triage, then block newly introduced findings that exceed a defined threshold. As teams reduce the backlog and improve scanner configuration, they can expand enforcement.

Gate decisions should account for:

  • Whether the finding is new
  • Severity and exploitability
  • Application exposure
  • Affected data
  • Available mitigations
  • Confidence in the result
  • Remediation availability

Monitor dependencies continuously

A dependency may have no known vulnerability when an application is built but become vulnerable when a new advisory is published.

Kiuwan Insights provides SCA for third-party components, including direct and transitive dependencies. It also supports license analysis, ongoing component monitoring, and SBOM generation.

Kiuwan provides a one-click SBOM generation export. An SBOM records all the components identified for a particular application or build; it does not automatically confirm which artifact is running in every production environment.

Java code security best practices

The following practices address several common Java risks. None of them can eliminate an entire vulnerability class by itself, so they should be applied as part of a broader secure development program.

PracticePrimary risk addressedJava implementation
Parameterize database queriesSQL injectionPreparedStatement, named ORM parameters, or safe criteria APIs
Restrict deserializationInsecure deserializationAvoid native serialization or configure ObjectInputFilter
Encode output by contextCross-site scriptingFramework escaping and context-specific encoding
Use vetted cryptographyCryptographic failuresSecureRandom, approved authenticated encryption, and supported TLS configurations
Enforce authorization consistentlyMissing authorizationRequest-, method-, object-, and tenant-level checks

1. Parameterize every database value

Use PreparedStatement for JDBC queries and named parameters for Hibernate or other persistence frameworks. Do not build database commands by concatenating user-controlled values.

Some dynamic elements, such as table names or sort directions, cannot be passed as normal parameters. Map those values to a fixed allow-list rather than inserting user input directly.

Input validation remains valuable, but it should support parameterization rather than replace it.

2. Avoid or strictly restrict native deserialization

Do not accept native Java serialized objects from untrusted sources unless the protocol is unavoidable and carefully controlled.

If native deserialization is required:

  • Configure ObjectInputFilter
  • Use strict allow-lists
  • Limit graph depth, references, arrays, and stream size
  • Keep the classpath free of unnecessary gadget-capable libraries
  • Authenticate the source and protect the integrity of serialized data
  • Test filter behavior against unexpected object graphs

Authentication and integrity controls do not replace strict filtering. For new external interfaces, prefer simpler formats with explicit data models and securely configured parsers.

3. Encode output for the correct context

Use framework-provided escaping by default and avoid APIs that deliberately render unescaped content unless the content is trusted or properly sanitized.

Apply the correct protection for:

  • HTML element content
  • HTML attributes
  • URLs
  • JavaScript
  • CSS

Content Security Policy can add another layer of protection, but it does not replace output encoding.

4. Use vetted cryptography and secure transport settings

Do not use Math.random() or java.util.Random for security-sensitive values. Java’s SecureRandom provides a cryptographically strong random-number generator for values such as session identifiers, keys, and nonces.

Avoid designing custom cryptographic protocols. Use vetted libraries and approved algorithms appropriate to your organization’s requirements.

For symmetric encryption, the OWASP Cryptographic Storage Cheat Sheet recommends AES with a key of at least 128 bits and an authenticated mode such as GCM. Key management, nonce uniqueness, access control, and rotation are as important as the algorithm.

Prefer TLS 1.3 where supported. If TLS 1.2 remains necessary for compatibility, configure strong authenticated-encryption cipher suites and disable TLS 1.0, TLS 1.1, and weak ciphers. Follow the OWASP Transport Layer Security Cheat Sheet.

5. Enforce least privilege and service-layer authorization

Use explicit access modifiers to improve encapsulation, but do not treat Java access modifiers as an authorization control. private, protected, and package-private visibility govern code access; they do not determine whether an authenticated user may perform a business action.

Enforce authorization at the appropriate application boundary. In Spring applications, this may include request-level rules and method-level checks such as @PreAuthorize for sensitive service operations.

Test more than role names. Authorization tests should cover record ownership, tenant boundaries, administrative operations, indirect object references, and alternate invocation paths.

How Kiuwan supports Java code security

Kiuwan addresses proprietary-code and dependency risk through two related products.

Kiuwan Code Security for SAST

Kiuwan Code Security analyzes proprietary Java source code for potential security vulnerabilities.

Documented capabilities include:

  • Support for more than 30 modern and legacy languages
  • IDE integrations, with capabilities varying by supported IDE and mode
  • CI/CD analysis
  • Code-level remediation guidance
  • Customizable rules
  • CWE and OWASP mappings
  • Configurable quality gates
  • Local source-code analysis through Kiuwan Local Analyzer

Kiuwan can identify potentially unsafe patterns and data flows, but findings still require developer review. Static analysis may also miss business-logic and runtime-dependent vulnerabilities, so it should be combined with code review, testing, and other security controls.

Kiuwan Insights for SCA

Kiuwan Insights analyzes open-source and third-party components.

It can help teams:

  • Identify direct and transitive dependencies
  • Detect known vulnerabilities
  • Review open-source licenses
  • Monitor components for newly disclosed vulnerabilities
  • Generate an SBOM
  • Export component information for security and compliance workflows

Using both products gives teams coverage for proprietary Java code and the Maven or Gradle dependency tree. However, SAST and SCA remain distinct forms of analysis, and teams should confirm product packaging, integrations, and policy-enforcement options during evaluation.

Deployment and compliance considerations

Kiuwan maps findings to frameworks and classifications including CWE, OWASP, PCI DSS, CERT, and SANS. These mappings can support security and audit workflows, but they do not, by themselves, guarantee compliance or audit acceptance.

Kiuwan Local Analyzer processes source code on the organization’s local infrastructure. In Kiuwan’s cloud configuration, the source code remains on the local machine while encrypted findings and metrics are uploaded to Kiuwan Cloud for reporting. Teams with strict data-residency requirements should confirm where source code, findings, and metadata will be stored under their selected deployment configuration.

Evaluate Java security on your own codebase

A Java security program needs visibility into both the application code your team writes and the components it imports.

Kiuwan Code Security provides SAST for proprietary Java code, while Kiuwan Insights provides SCA for direct and transitive dependencies. Together, they can support IDE feedback, CI/CD analysis, dependency monitoring, policy enforcement, and SBOM workflows.

Start a free 14-day Kiuwan trial to evaluate the findings against your own Java codebase and dependency tree.

For additional implementation guidance, download the Security Guide for Java Developers.


Frequently asked questions about Java code security

Is Java secure?

Java provides security features such as type safety, bytecode verification, memory management, access controls, and mature cryptography APIs. However, Java applications can still contain vulnerabilities in proprietary code, frameworks, configurations, and dependencies.

Datadog’s 59% figure reflects known exploitable vulnerabilities in third-party libraries used by the Java services in its study. It does not mean that 59% of the Java language itself is vulnerable.

What are common Java security vulnerabilities?

Common risks include injection, insecure deserialization, XSS, broken access control, cryptographic failures, security misconfiguration, and vulnerable or malicious dependencies.

The risks that matter most depend on the application’s architecture, frameworks, exposure, data, and threat model.

What are Java secure coding best practices?

Important practices include:

• Parameterizing database queries
• Avoiding or restricting native deserialization
• Applying context-specific output encoding
• Using vetted cryptographic libraries and SecureRandom
• Enforcing authorization consistently
• Keeping runtimes and dependencies current
• Reviewing code and running automated security testing

What is the difference between SAST and SCA for Java?

SAST analyzes proprietary source code for potentially vulnerable patterns and data flows. SCA identifies known risks and license obligations in open-source and third-party components, including transitive dependencies.

Java applications generally need both because application code and dependency trees introduce different risks.

Does Hibernate prevent SQL injection?

Hibernate provides safe parameter-binding APIs, but it does not prevent SQL injection when developers construct HQL or native SQL through string concatenation.

Use named parameters, setParameter, or suitable criteria APIs, and review every raw query carefully.

How do you prevent SQL injection in Java?

Use PreparedStatement with bound parameters in JDBC and parameter-binding APIs in persistence frameworks. Do not insert untrusted values directly into an SQL or HQL string.

Parameterized queries keep values separate from the command structure when implemented correctly.

What was Log4Shell, and why does it still matter?

Log4Shell was a critical vulnerability in Apache Log4j 2 disclosed in December 2021. It demonstrated how a vulnerability in a widely used component can affect applications whether the library is included directly or transitively.

The incident reinforces the need for complete dependency inventories, continuous monitoring, reliable upgrade processes, and visibility into deployed components.

How often should teams scan Java dependencies?

Scan dependencies during development and CI/CD, then continue monitoring previously analyzed components for new vulnerability disclosures.

A point-in-time scan cannot identify a vulnerability that has not yet been disclosed. Continuous monitoring allows teams to reassess an existing application when new information becomes available.

In This Article:

Request Your Free Kiuwan Demo Today!

Get Your FREE Demo of Kiuwan Application Security Today!

Identify and remediate vulnerabilities with fast and efficient scanning and reporting. We are compliant with all security standards and offer tailored packages to mitigate your cyber risk within the SDLC.

Related Posts

Java code security Vulnerabilities, scanning, and best practices
© 2026 Kiuwan. All Rights Reserved.