Practice library / More programming languages
Workbook · Hard · 8 hoursFree account
Secure Java Development
Secure Java coding patterns, OWASP Java guidance, and code review.
On this page 6 sections
Java runs many enterprise back ends, so Java flaws can be costly and widespread. The OWASP Cheat Sheet Series names the patterns that prevent the common classes, but the patterns only help if a developer can read code and spot a sink. This workbook teaches both sides. It covers SQL and command injection, XXE, path traversal, deserialization, access control, password storage and authenticated encryption, with vulnerable code, a fix and a test for each. It also wires static analysis, dependency scanning and security tests into the build so the fixes keep applying after you leave the file.
What You'll Learn
- Identify the trust boundaries of a Java application and the vulnerability classes at each one
- Prevent SQL injection, command injection, XXE and path traversal with safe API patterns
- Restrict and replace Java deserialization
- Implement deny-by-default access control, password hashing and authenticated encryption
- Review Java code with a checklist and find sinks with search tools
- Add static analysis, dependency scanning and security tests to a build
About This Workbook
This workbook teaches you to build security into Java code. For each flaw you see the vulnerable code, the fix and a test that proves the fix. The fixes follow the OWASP Cheat Sheet Series: Input Validation, SQL Injection Prevention, OS Command Injection Defense, XML External Entity Prevention, Deserialization, Authorization, Password Storage, Cryptographic Storage and Logging.
You need to read and write basic Java. If you do not, start with Java Fundamentals. For the theory of one flaw class in depth, see Insecure Deserialization.
All code in this workbook is short and generic. It is not code for a specific product or version. Run it only on your own machine or on a lab application that you own, for example OWASP WebGoat in a container. Never test an application that you are not authorised to test.
Each chapter has objectives, explanation, a worked example and practice questions. Plan about two hours per chapter.
Chapter 1 — Java Security Foundations
Objectives
- Draw the trust boundaries of an application
- Name the vulnerability classes that match each boundary
- Validate input with an allow-list and encode output for its context
- Handle errors and logs without leaking data
Explanation
A trust boundary is a line where data moves from a less trusted place to a more trusted place. Data from outside the line is untrusted until your code checks it. In a typical Java web service the lines are:
| Boundary | Untrusted input | Typical flaw |
|---|---|---|
| Browser to controller | Query, form, header, cookie, JSON body | Injection, XSS, broken access control |
| Controller to database | Values in a query | SQL injection |
| Application to operating system | File names, command arguments | Path traversal, command injection |
| Application to parser | XML, serialized objects, YAML | XXE, unsafe deserialization |
| Application to library | A dependency pulled from a repository | Known vulnerable component |
| Application to log | Any user text | Log injection, data leaks |
The OWASP Top 10 groups these flaws into categories, for example Broken Access Control, Cryptographic Failures, Injection, Vulnerable and Outdated Components and Security Logging and Monitoring Failures. This workbook follows the same groups.
The JVM gives you memory safety: you do not get buffer overflows in normal Java code. It does not give you logic safety. Many Java breaches come from logic flaws and unsafe use of a library.
Secure SDLC. The cheapest fix is the earliest one. Security work sits in every phase of the software development lifecycle:
- Design. Write down trust boundaries and what an attacker wants (threat modelling).
- Code. Use safe APIs and a checklist.
- Build. Run static analysis and a dependency scan on every commit.
- Test. Write security tests next to the unit tests.
- Release and operate. Log security events and patch dependencies on a schedule.
Validate input with an allow-list. An allow-list states what is valid and rejects everything else. A deny-list tries to name what is bad and always misses a case. Check type, length, range and format.
Encode output for its context. Validation is not a replacement for encoding. Data that is safe in a database can be dangerous in HTML. Use the OWASP Java Encoder library, class org.owasp.encoder.Encode, with the method that matches the context: Encode.forHtml, Encode.forHtmlAttribute, Encode.forJavaScript, Encode.forUriComponent. Template engines such as Thymeleaf encode by default when you use th:text.
Errors and logs. Show the user a short, generic error. Write the detail to the server log. Do not log passwords, tokens or full card numbers. Remove line breaks from user text before you log it, because an attacker can add a line break to forge a log line (log injection, CWE-117).
Worked example
A service returns a file from a folder of reports. The vulnerable version builds the path from user input.
// VULNERABLE: path traversal
@GetMapping("/report")
public byte[] report(@RequestParam String name) throws IOException {
return Files.readAllBytes(Path.of("/srv/reports/" + name));
}A request with name=../../etc/passwd reads a file outside /srv/reports. The .. parts move up the directory tree. The fix has two layers: an allow-list for the format, and a check that the final path stays inside the base folder.
private static final Path BASE = Path.of("/srv/reports").toAbsolutePath().normalize();
private static final Pattern NAME = Pattern.compile("[A-Za-z0-9_-]{1,64}\\.pdf");
@GetMapping("/report")
public byte[] report(@RequestParam String name) throws IOException {
if (!NAME.matcher(name).matches()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid report name");
}
Path file = BASE.resolve(name).normalize();
if (!file.startsWith(BASE)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid report name");
}
return Files.readAllBytes(file);
}The pattern rejects / and . in the name part, so .. cannot pass. The normalize() and startsWith(BASE) check is a second layer: it still protects you if someone later relaxes the pattern. Note that startsWith on Path objects compares whole path elements, so /srv/reports-old does not match /srv/reports. A startsWith on String would match it, which is a classic mistake.
Test the fix with a unit test. A security test states what must not happen.
@Test
void rejectsTraversal() {
assertThrows(ResponseStatusException.class,
() -> controller.report("../../etc/passwd"));
}Now the log side. This code lets a user forge log lines:
log.info("Login failed for user " + username);If username is bob\nINFO Login ok for admin, the log shows two lines. Remove the line breaks and use a parameter:
String safe = username.replaceAll("[\\r\\n]", "_");
log.warn("Login failed for user {}", safe);Use the same two questions for every input: where does it come from, and where does it go? The answer to the second question tells you which encoder or API is correct.
Practice questions
- List three trust boundaries in a web service that stores data in a database and calls a payment API.
- Why is an allow-list better than a deny-list that removes
../? - A comment is stored in the database as
<script>alert(1)</script>and shown in an HTML page. Which control stops it, and where do you apply it? - Why does the JVM not remove the need for input validation?
Answers
- Browser to controller, controller to database, and application to the payment API (the response of the API is also input). Others: application to log, application to dependencies.
- A deny-list that removes
../once turns....//into../. Encodings such as%2e%2e/or other separators add more cases. The allow-list accepts only a known good format, so unknown forms fail by default. - Output encoding for the HTML context, for example
Encode.forHtmlor a template engine that encodes by default. Apply it when you write the data into the page, not when you store it. - The JVM prevents memory errors only. Injection, path traversal, broken access control and unsafe deserialization are errors in program logic, and the JVM runs them without complaint.
Sign in to continue
4 more sections are for signed-in members. It is free: sign in with Google.