SAASMENT

Security skill · Find and fix

Secure review: Java.

Review Java and JVM code (Spring Boot, Jakarta EE, Kotlin services, batch jobs) for language-specific security flaws such as native deserialization, XML external entity processing, expression-language and template injection, mass assignment through data binding, SQL and JPQL string building, weak method-level security, unsafe logging, and vulnerable libraries, then fix and verify with tests. Use when auditing or reviewing a Java codebase or pull request.

Download .zipInstall via MCPFind and fixMIT
  • Code review

Facts

Category
Find and fix
License
MIT
Tags
  • Code review
Version
1.0.0
Last updated
2026-12-02
Folder
secure-review-java/
MCP resource
skill://secure-review-java/SKILL.md
Files
  • SKILL.md
  • LICENSE
  • references/java-patterns.md
Standards

Original Saasment content. Saasment is in early access; this skill does not require joining it.

Install via MCP or as files

Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:

{
  "name": "get_skill",
  "arguments": {
    "slug": "secure-review-java"
  }
}

Or download the .zip and unpack it into your agent's skills directory:

Terminal, from your project root (user-level: ~/.cursor/skills)

mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/secure-review-java/download.zip -o /tmp/secure-review-java.zip
unzip -o /tmp/secure-review-java.zip -d .cursor/skills
# result: .cursor/skills/secure-review-java/SKILL.md

Review SKILL.md before enabling a skill. Skills are instructions your agent will follow.

SKILL.md

---
name: secure-review-java
description: Review Java and JVM code (Spring Boot, Jakarta EE, Kotlin services, batch jobs) for language-specific security flaws such as native deserialization, XML external entity processing, expression-language and template injection, mass assignment through data binding, SQL and JPQL string building, weak method-level security, unsafe logging, and vulnerable libraries, then fix and verify with tests. Use when auditing or reviewing a Java codebase or pull request.
license: MIT
metadata:
  author: Saasment
  version: "1.0.0"
  category: both
  tags: "code-review"
---

# Secure review: Java (find and fix)

License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/secure-review-java

Java applications are usually large and framework driven, so risk concentrates in a few places: object deserialization, XML parsers with default settings, expression languages that evaluate strings, data binding that copies request fields onto entities, query strings assembled by concatenation, and security annotations that are present but not enforced. Long dependency trees add libraries with their own advisories. This skill covers the Java-specific pass; run it together with `secure-code-review-checklist`.

## When to use

- You audit a Spring, Jakarta EE, Quarkus, Micronaut, or plain Java or Kotlin service.
- A pull request adds controllers, parsers, serialization, security configuration, or new dependencies.
- A scanner reported Java findings that need triage.

## Safe by default

- Review only code you own or are authorized to review. Run probes only in a local or test environment with synthetic data.
- Do not deserialize data from an untrusted source to confirm a finding. Confirm by tracing the call path and by using a harmless, self-created test object in a test environment.
- Do not run build plugins or scripts from an unfamiliar repository on a machine with credentials. Read `pom.xml`, Gradle files, and wrapper scripts first.
- Keep probes harmless: unique marker strings and temporary files only.

## Procedure

1. **Inventory.** Record Java version, build tool, framework and version, security configuration (Spring Security filter chains, method security, servlet filters), serialization libraries, and XML or template engines in use.
2. **Search the risky APIs** (patterns in `references/java-patterns.md`):
   - Native deserialization: `ObjectInputStream`, `readObject`, `XMLDecoder`, `XStream` with permissive settings, Jackson default typing, Kryo without registration, JNDI lookups with user input (see `input-validation-deserialization-review`).
   - XML: `DocumentBuilderFactory`, `SAXParserFactory`, `XMLInputFactory`, `TransformerFactory`, and `SchemaFactory` without external entity and DTD processing disabled.
   - Expression and template injection: Spring Expression Language, OGNL, MVEL, JSP EL, and template engines evaluating strings that include user input.
   - SQL and JPQL: string concatenation or `String.format` in queries, `createNativeQuery` and `@Query` with concatenation (see `sql-injection-find-and-fix`).
   - Processes and files: `Runtime.exec`, `ProcessBuilder` with a shell, `new File(base, userInput)`, zip entry names used as paths.
   - Outbound requests: `URL.openConnection`, `RestTemplate`, `WebClient`, or `HttpClient` with user-influenced URLs (see `ssrf-find-and-fix`).
3. **Check data binding.** Controller methods that bind request bodies or form fields directly to entities allow mass assignment of fields such as `role`, `tenantId`, or `price`. Use request DTOs with only the fields the caller may set (see `authz-idor-review`).
4. **Check authorization is enforced.** Confirm method-level annotations (`@PreAuthorize`, `@RolesAllowed`) are enabled by configuration, that URL rules end with `anyRequest().authenticated()` or equivalent, and that object-level checks exist for lookups by id.
5. **Check sessions, CSRF, and CORS.** CSRF protection is not disabled globally without a reason, cookies carry secure and HTTP-only flags, and CORS lists explicit origins.
6. **Check logging and errors.** User input in log messages can forge entries or reach logging features that evaluate lookups on older log libraries; stack traces and SQL errors should not appear in responses; secrets must not be logged.
7. **Check dependencies.** Run a dependency vulnerability scan (for example OWASP Dependency-Check or your build tool's audit task), review transitive versions of serialization, XML, and logging libraries, and keep the framework on a supported release (see `dependency-cve-triage-and-patch`).
8. **Fix and add tests.** Use DTOs, parameterized queries, hardened parser factories, deserialization allowlists or data-only formats, and method security. Add one test per fix.

## Verification

- Confirm XML hardening with a local test document that declares a harmless external entity pointing at a temporary file you created; assert that parsing throws or ignores the entity. Before the fix the file content appears in the parsed output; after the fix it does not.
- Confirm mass assignment with a test that posts an extra field (for example `role`) and asserts the stored entity ignores it.
- Confirm deserialization controls by asserting that a class outside the allowlist is rejected, using a harmless test class.
- Confirm method security with tests for an anonymous caller, a low-privilege caller, and an allowed caller on each protected method.
- Re-run the dependency scan, static analysis (for example SpotBugs with a security plugin), and the full test suite, and compare with the baseline.

## Reporting

Table: id, class and method, bug class, reachable by whom, fix, test. Note framework and library versions reviewed and unresolved dependency advisories.

## References

- OWASP Java Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Java_Security_Cheat_Sheet.html
- OWASP Deserialization Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html
- OWASP XML External Entity Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
- Java serialization filtering: https://docs.oracle.com/en/java/javase/17/core/serialization-filtering1.html
- Companion skills: `secure-code-review-checklist`, `input-validation-deserialization-review`, `authz-idor-review`.

Helper files

LICENSE
MIT License

Copyright (c) 2026 Saasment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
references/java-patterns.md
# Java risky patterns

License: MIT. Copyright (c) 2026 Saasment.

Search leads only. Confirm that untrusted data reaches each hit.

## Search commands

```bash
# Deserialization
rg -n 'ObjectInputStream|readObject\(|XMLDecoder|new XStream|enableDefaultTyping|activateDefaultTyping|InitialContext|\.lookup\(' --glob '*.{java,kt}'

# XML parsers
rg -n 'DocumentBuilderFactory|SAXParserFactory|XMLInputFactory|TransformerFactory|SchemaFactory' --glob '*.{java,kt}'

# Expressions and processes
rg -n 'SpelExpressionParser|parseExpression|Ognl|MVEL|Runtime\.getRuntime\(\)\.exec|ProcessBuilder' --glob '*.{java,kt}'

# Query building
rg -n 'createNativeQuery|createQuery\(.*\+|@Query\(.*\+|Statement\b.*executeQuery|String\.format\(.*(SELECT|select)' --glob '*.{java,kt}'

# Security configuration
rg -n 'csrf\(\)\.disable|csrf\.disable|permitAll\(\)|@EnableMethodSecurity|@EnableGlobalMethodSecurity|@PreAuthorize' --glob '*.{java,kt}'
```

## XML parser hardening

```java
// Risky: parser defaults can resolve external entities and DTDs
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

// Safer: disable DTDs entirely and enable secure processing
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
```

## Native deserialization

```java
// Risky: class chosen by the sender
Object value = new ObjectInputStream(request.getInputStream()).readObject();

// Safer: prefer a data-only format (JSON into a specific class). If native serialization
// must stay, install an allowlist filter that names the permitted classes and sizes.
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
    "com.example.model.*;java.base/*;!*");
ObjectInputStream in = new ObjectInputStream(stream);
in.setObjectInputFilter(filter);
```

## Mass assignment

```java
// Risky: the entity has role and tenantId, and the request can set them
@PostMapping("/users")
User create(@RequestBody User user) { return repo.save(user); }

// Safer: a DTO that lists only caller-settable fields
record CreateUserRequest(String name, String email) {}

@PostMapping("/users")
UserView create(@Valid @RequestBody CreateUserRequest req, Principal principal) {
    User user = new User(req.name(), req.email(), principal.tenantId());
    return UserView.of(repo.save(user));
}
```

## Queries

```java
// Risky
em.createQuery("select u from User u where u.email = '" + email + "'");

// Safer
em.createQuery("select u from User u where u.email = :email", User.class)
  .setParameter("email", email);
```

## Security configuration to confirm

| Area | Check |
| --- | --- |
| URL rules | the last rule denies or requires authentication for everything not listed |
| Method security | the enabling annotation is present, and tests cover denied callers |
| CSRF | enabled for browser sessions, disabled only for stateless token APIs with a recorded reason |
| Cookies | secure, HTTP-only, SameSite set |
| Actuator and management endpoints | not exposed publicly, or protected |
| Error pages | no stack traces or SQL details in responses |

Related

Companion skills

Questions

How do I install the Secure review: Java skill?

Download https://www.saasment.com/ai-security/skills/secure-review-java/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that secure-review-java/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug secure-review-java.

What license is the Secure review: Java skill under?

It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.

Is it safe to run this skill?

A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.

← All security skills

Try the platform.

Open the demo workspace with mock data. No login. Register from the banner when you want early access. No security team. No call.

Try the platform