These are the notes for Cybersecurity Fundamentals (defensive), episode 56. Episode 55 showed that Java is a memory-safe language: no buffer overflows, no use-after-free. But Java applications are still attacked all the time, because the bugs move up a level: into how we build database queries, read objects and XML, generate random numbers, handle keys and choose libraries. This episode finds each trap in a small toy program and fixes it. Every term is defined the first time it appears; the Glossary collects them.
Scope. Defensive and educational only. Every program is a toy that works on its own data; no real system is touched, and no working exploit for real software is shown. Samples were run on 12 Nov 2026 in the SyntaxPilot compiler (OpenJDK 21). The JDBC demo needs a database driver, so it was run separately with OpenJDK 21 and the sqlite-jdbc 3.44.1 driver; its output is real.
The six traps
| Trap | Fix |
|---|---|
| SQL built by gluing in user input | PreparedStatement, JPA named parameters, Bean Validation |
| Objects rebuilt from untrusted bytes | JEP 290 serialization filters, or JSON |
| XML that reads server files (XXE) | disallow-doctype-decl on DocumentBuilderFactory |
| Predictable random numbers | SecureRandom |
| Home-made crypto, keys in code | the Java Cryptography Architecture, KeyStore, Spring Security |
| Bugs inside libraries (Log4Shell) | upgrade, Maven/Gradle dependency lists, OWASP Dependency-Check |
Problem 1: queries built from input (SQL injection)
Real-life example: a bank that lets customers write the whole cheque sentence themselves will soon see "...and pay me 1 lakh" added. A printed form with fixed boxes only lets you fill the boxes.
- SQL is the language used to ask a database for data (
SELECT name FROM users WHERE ...). - String concatenation means gluing strings together with
+. Gluing user input into SQL text lets the input change the command. - SQL injection: user input is treated as part of the SQL code instead of as data.
Demo 1: the glued-together query
// Login check that glues user input into SQL text.
public class Main {
static String buildQuery(String user, String pass) {
return "SELECT * FROM users WHERE name = '" + user
+ "' AND pass = '" + pass + "'";
}
public static void main(String[] args) {
System.out.println(buildQuery("asha", "chai123"));
// an attacker types this as the password:
System.out.println(buildQuery("asha", "x' OR '1'='1"));
}
}
Real output:
SELECT * FROM users WHERE name = 'asha' AND pass = 'chai123'
SELECT * FROM users WHERE name = 'asha' AND pass = 'x' OR '1'='1'
The attacker's quote closed our text early, and OR '1'='1' (always true) became real SQL. The password check is gone.
Demo 2: PreparedStatement against a real database
- JDBC (Java Database Connectivity) is Java's standard API for talking to databases.
- A
PreparedStatementsends the SQL with?placeholders first; values are bound separately withsetString,setInt, ... The database fixes the shape of the query before any input arrives, so input can only ever be data.
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
Connection db = DriverManager.getConnection("jdbc:sqlite::memory:");
Statement st = db.createStatement();
st.execute("CREATE TABLE users(name TEXT, pass TEXT)");
st.execute("INSERT INTO users VALUES('asha','chai123')");
String typed = "x' OR '1'='1"; // attacker's password
// UNSAFE: input glued into the SQL text
ResultSet r1 = st.executeQuery("SELECT name FROM users WHERE name='asha' AND pass='" + typed + "'");
System.out.println("concatenated: " + (r1.next() ? "LOGGED IN as " + r1.getString(1) : "rejected"));
// SAFE: the SQL is fixed; the input is sent separately as data
PreparedStatement ps = db.prepareStatement("SELECT name FROM users WHERE name=? AND pass=?");
ps.setString(1, "asha");
ps.setString(2, typed);
ResultSet r2 = ps.executeQuery();
System.out.println("prepared: " + (r2.next() ? "LOGGED IN as " + r2.getString(1) : "rejected"));
}
}
Run with java -cp .:sqlite-jdbc.jar:slf4j-api.jar:slf4j-nop.jar Main. Real output:
concatenated: LOGGED IN as asha
prepared: rejected
Don't try to "clean" input by removing quotes: there are other tricks and encodings. Separate code from data instead.
JPA, Hibernate and Bean Validation
- JPA (Jakarta Persistence API) is Java's standard for mapping Java objects to database rows. Hibernate is the most widely used JPA implementation.
- JPQL is JPA's query language. Gluing input into a JPQL or Hibernate query string is injectable exactly like SQL.
- Use named parameters:
"SELECT u FROM User u WHERE u.name = :name"withquery.setParameter("name", name), or the Criteria API. - Bean Validation (Jakarta Validation; Hibernate Validator is the reference implementation) puts rules on fields as annotations:
@NotNull,@Size(max = 40),@Email,@Pattern(...). Input that breaks a rule is rejected at the door, before it reaches the database. - Two layers: validate at the door, parameterise at the database.
Problem 2: objects read from bytes (deserialization)
Real-life example: a flat-pack parcel that assembles whatever is inside, versus a guard with a list who only lets chairs through.
- Serialization: turning an object into bytes, to save or send it (
ObjectOutputStream.writeObject). - Deserialization: rebuilding the object from bytes (
ObjectInputStream.readObject). - The danger:
readObjectcreates whatever class the bytes name. If an attacker controls the bytes, they choose which classes are built, and some library classes do risky work while being rebuilt ("gadget" classes). Insecure deserialization has led to serious real-world remote code execution. - JEP 290, "Filter Incoming Serialization Data", delivered in JDK 9: a filter is called before each object is created and returns
ALLOWED,REJECTEDorUNDECIDED. - Filter patterns are separated by
;: a class name allows it,pkg.*matches a package,pkg.**a package and its subpackages, a leading!rejects, and limits likemaxdepth=,maxrefs=,maxbytes=,maxarray=cap the stream. - Set a filter per stream with
ObjectInputStream.setObjectInputFilter(...), or for the whole JVM with thejdk.serialFiltersystem or security property.
Demo 3: a JEP 290 allow-list
import java.io.*;
public class Main {
record Order(String item, int qty) implements Serializable {}
record Gadget(String cmd) implements Serializable {} // unexpected
static byte[] save(Object o) throws IOException {
var b = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(b)) { out.writeObject(o); }
return b.toByteArray();
}
static Object load(byte[] data) throws Exception {
var in = new ObjectInputStream(new ByteArrayInputStream(data));
// JEP 290 filter: allow ONLY Main$Order, reject everything else
in.setObjectInputFilter(
ObjectInputFilter.Config.createFilter("Main$Order;!*"));
return in.readObject();
}
public static void main(String[] args) throws Exception {
System.out.println("loaded: " + load(save(new Order("chai", 2))));
try {
load(save(new Gadget("anything")));
} catch (InvalidClassException e) {
System.out.println("blocked: " + e.getMessage());
}
}
}
Real output:
loaded: Order[item=chai, qty=2]
blocked: filter status: REJECTED
(Main$Order is the binary name of the nested record Order inside Main.) Better still: don't use Java serialization for data from outside; use JSON with a fixed schema. JEP 415 (JDK 17) adds context-specific filter factories.
Problem 3: XML that reads your files (XXE)
- XML is a text format for data with tags (
<order><item>chai</item></order>). - A DOCTYPE (document type declaration) at the top can define entities: shortcuts like
&x;that the parser replaces with text. - An external entity points to a file or URL (
<!ENTITY x SYSTEM "file:secret.txt">), and the parser fetches it. - XXE (XML External Entity injection): if XML comes from a user, they can make the server read its own files (or contact other servers).
- OWASP's advice: "Disable document type definitions (DTDs) whenever possible." For Java DOM:
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Demo 4: XXE with DocumentBuilderFactory
import java.io.*;
import java.nio.file.*;
import javax.xml.parsers.*;
public class Main {
static String FEATURE =
"http://apache.org/xml/features/disallow-doctype-decl";
public static void main(String[] args) throws Exception {
Files.writeString(Path.of("secret.txt"), "DB_PASSWORD=chai123");
// XML sent by a user. Its DOCTYPE defines an "entity" = a file!
String xml = "<!DOCTYPE order [<!ENTITY x SYSTEM"
+ " \"file:secret.txt\">]>"
+ "<order><item>&x;</item></order>";
var f = DocumentBuilderFactory.newInstance(); // defaults
var doc = f.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()));
System.out.println("default parser, item = "
+ doc.getDocumentElement().getTextContent());
var safe = DocumentBuilderFactory.newInstance();
safe.setFeature(FEATURE, true); // no DOCTYPE
try {
safe.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()));
} catch (org.xml.sax.SAXParseException e) {
System.out.println("safe parser refused: " + e.getMessage());
}
}
}
Real output (the [Fatal Error] line is printed by the parser on stderr):
default parser, item = DB_PASSWORD=chai123
[Fatal Error] :1:10: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
safe parser refused: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
The same care applies to SAXParserFactory, XMLInputFactory (StAX: set XMLInputFactory.SUPPORT_DTD to false) and TransformerFactory (set XMLConstants.ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET to ""). See the OWASP XXE Prevention Cheat Sheet for each parser.
Problem 4: random that isn't random (SecureRandom)
Real-life example: a deck stacked in a known order (know the first card, know them all) versus a truly shuffled deck.
java.util.Randomis a pseudo-random number generator (PRNG): a formula that starts from a number called a seed. Same seed, same sequence; a few outputs can reveal the internal state. Fine for games and simulations.java.security.SecureRandomis a cryptographically secure generator, fed by the operating system's secure randomness. Use it for OTPs, session tokens, reset links, keys and salts.- OTP: one-time password, e.g. the 6-digit code sent by SMS.
Demo 5: predicting an OTP
import java.security.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// java.util.Random: same seed -> same "random" OTPs.
Random a = new Random(2026), b = new Random(2026);
int otpA = 100000 + a.nextInt(900000);
int otpB = 100000 + b.nextInt(900000);
System.out.println("Random a OTP: " + otpA);
System.out.println("Random b OTP: " + otpB + " <- predicted!");
// SecureRandom: from the OS's secure source. Unpredictable.
SecureRandom sr = new SecureRandom();
int otpS = 100000 + sr.nextInt(900000);
System.out.println("SecureRandom OTP: " + otpS);
byte[] token = new byte[16];
sr.nextBytes(token);
String hex = HexFormat.of().formatHex(token);
System.out.println("session token: " + hex);
System.out.println("algorithm: " + sr.getAlgorithm());
}
}
Real output (the last three lines change every run):
Random a OTP: 203799
Random b OTP: 203799 <- predicted!
SecureRandom OTP: 150374
session token: c74282692e06d31e06471ed37db3ca8a
algorithm: NativePRNG
Never use Random, Math.random() or ThreadLocalRandom for secrets.
Problem 5: crypto, keys and the web layer
The Java Cryptography Architecture (JCA)
- The JCA is Java's built-in cryptography framework. You never implement an algorithm yourself; you ask for one by name (
MessageDigest.getInstance("SHA-256"),Cipher.getInstance("AES/GCM/NoPadding")), and a provider (a library of implementations, such asSUN) supplies it. - A hash (episode on hashing) turns data into a fixed-size fingerprint; SHA-256 makes 256-bit fingerprints.
- A KeyStore is a password-protected container for keys and certificates. PKCS12 (
.p12) is the standard file format. Keep the KeyStore file and its password outside the source code (environment variables or a secret manager).
Demo 6: JCA and KeyStore
import java.security.*;
import java.util.HexFormat;
import javax.crypto.*;
public class Main {
public static void main(String[] args) throws Exception {
// JCA: ask for an ALGORITHM by name; a provider supplies it.
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] h = sha.digest("2 chai mugs".getBytes());
String hex = HexFormat.of().formatHex(h);
System.out.println("SHA-256: " + hex.substring(0, 32) + "...");
System.out.println("provider: " + sha.getProvider().getName());
// A key lives in a KeyStore (a password-locked key safe).
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null);
char[] pw = System.getenv()
.getOrDefault("KS_PASS", "demo").toCharArray();
ks.setEntry("orders-key", new KeyStore.SecretKeyEntry(key),
new KeyStore.PasswordProtection(pw));
Key back = ks.getKey("orders-key", pw);
System.out.println("stored and loaded: " + back.getAlgorithm()
+ ", " + back.getEncoded().length * 8 + "-bit key");
}
}
Real output:
SHA-256: 941938c4a7dc8c3a1b6ba5de1eae2321...
provider: SUN
stored and loaded: AES, 256-bit key
Rules: standard, strong algorithms only (SHA-256, AES-GCM, RSA/ECDSA with modern sizes); never invent your own; never hard-code keys or passwords; for passwords use a slow salted hash (bcrypt, PBKDF2, Argon2), not plain SHA-256.
Spring Security basics
- Spring (Spring Framework, Spring Boot) is the most widely used Java web framework.
- Spring Security puts a chain of filters in front of every HTTP request, like guards at each door.
- It handles authentication (who are you?) and authorization (are you allowed to do this?), adds CSRF protection (cross-site request forgery: a trick that makes a logged-in user's browser send a request they didn't intend) and secure response headers by default.
- For passwords it provides
BCryptPasswordEncoder: bcrypt is a slow, salted password hash. - Lesson: use the framework's tested security; don't hand-roll login code.
Problem 6: the bug in a library (Log4Shell)
- Log4j (Apache Log4j 2) is a very popular Java logging library: it writes down what a program did (
log.info("user: " + name)). - Log4j had message lookups: text like
${something}inside a logged message was replaced with a value. - One lookup type,
${jndi:...}, used JNDI (the Java Naming and Directory Interface, a Java API for finding resources on other servers), which could load a Java class from a remote server and run it. - So any text an app logged (a user name, an HTTP header, a chat message) could make the server run an attacker's code. This is remote code execution (RCE).
| Fact | Value |
|---|---|
| Name / ID | Log4Shell, CVE-2021-44228 |
| Severity | CVSS 10 (critical, the maximum) |
| Made public | 9 December 2021 |
| Affected | Log4j 2.0-beta9 to 2.14.1 |
| Fixes | 2.15.0 not vulnerable by default; 2.16.0 removed message lookups; 2.17.0 fixed a follow-up DoS (CVE-2021-45105); 2.17.1 fixed CVE-2021-44832. All versions from 2.17.1 are free of Log4Shell |
The hardest part for companies was finding every copy of Log4j, often hidden as a dependency of a dependency.
Maven, Gradle and OWASP Dependency-Check
- Maven and Gradle are Java build tools. You list a library and they download it plus everything it needs.
- Direct dependencies are the ones you list; transitive dependencies are dependencies of dependencies.
- See the whole tree:
mvn dependency:treeorgradle dependencies. - Software composition analysis (SCA) checks your dependencies against known vulnerabilities.
- OWASP Dependency-Check is "a Software Composition Analysis (SCA) tool suite that identifies project dependencies" and "checks if there are any known, publicly disclosed, vulnerabilities". It runs as a command-line tool, a Maven plugin, a Gradle plugin or an Ant task, and in CI systems like Jenkins. Configure it to fail the build on high-severity findings.
- Habits: pin exact versions, update often, scan every build, keep an SBOM (software bill of materials: the list of everything you ship).
The whole chain
- Input glued into SQL →
PreparedStatementwith?, JPA:nameparameters. - Bad input → Bean Validation annotations at the door.
readObjectbuilds anything → a JEP 290 allow-list filter, or JSON.- XML reads files →
disallow-doctype-decl. - Predictable
Random→SecureRandom; crypto through the JCA, keys in aKeyStore; Spring Security for the web layer. - Bugs in libraries → upgrade (Log4j 2.17.1+), know your tree, OWASP Dependency-Check on every build.
Common mistakes (and the fix)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
"... pass='" + pass + "'" |
concatenated: LOGGED IN as asha |
input became SQL | PreparedStatement with ? and setString |
"... WHERE u.name = '" + n + "'" in JPQL |
same injection in JPA/Hibernate | glued query string | :name + setParameter |
new ObjectInputStream(in).readObject() on outside data |
any named class is created | no filter | setObjectInputFilter("MyClass;!*"), or JSON |
DocumentBuilderFactory.newInstance() on user XML |
default parser, item = DB_PASSWORD=chai123 |
DOCTYPE allowed | setFeature(".../disallow-doctype-decl", true) |
wrong feature name or setting it after newDocumentBuilder() |
no error, still vulnerable | the feature never applied | set features on the factory before creating the builder; test with an XXE toy |
new Random().nextInt(900000) for an OTP |
Random b OTP: 203799 <- predicted! |
seeded formula | new SecureRandom() |
byte[] key = "mysecretkey12345".getBytes(); |
key visible in git and in the jar | hard-coded secret | generate keys; store in a KeyStore / secret manager |
| Log4j 2.14.1 in the dependency tree | CVE-2021-44228 in a scan | known-vulnerable library | upgrade to 2.17.1+, scan every build |
Mini project: harden a toy order service
Write a small console app that (1) reads an order as XML from standard input, (2) validates the item name (letters only, at most 20 characters) and the quantity (1-10), (3) stores it in SQLite with a PreparedStatement, and (4) prints an order ID made with SecureRandom. Then try to break it with: an XXE DOCTYPE, x' OR '1'='1 as the item, quantity -5, and a 500-character item. Every attempt must be refused with a clear message.
Practice
1. Rewrite buildQuery as a method that uses a PreparedStatement.
Solution
static boolean login(Connection db, String user, String pass) throws SQLException {
try (PreparedStatement ps = db.prepareStatement(
"SELECT 1 FROM users WHERE name = ? AND pass = ?")) {
ps.setString(1, user);
ps.setString(2, pass);
try (ResultSet r = ps.executeQuery()) { return r.next(); }
}
}
(In a real app, store a bcrypt hash and compare with BCryptPasswordEncoder.matches, never plain passwords.)
2. Change the serialization filter so that Order and java.lang.String are allowed, the stream depth is at most 5, and everything else is rejected.
Solution
ObjectInputFilter.Config.createFilter("maxdepth=5;Main$Order;java.lang.String;!*")
Limits are checked first; class patterns are matched left to right; !* rejects the rest.
3. Make the XXE toy safe without disallowing DOCTYPE completely (for an app that needs DTDs).
Solution
var f = DocumentBuilderFactory.newInstance();
f.setFeature("http://xml.org/sax/features/external-general-entities", false);
f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
f.setXIncludeAware(false);
f.setExpandEntityReferences(false);
Disallowing DOCTYPE is still the simplest and safest choice when you can.
4. Why can't you make Random safe by seeding it with System.currentTimeMillis()?
Solution
The time is guessable (an attacker knows roughly when the token was made, to the second or millisecond), so they can try every seed in that window. And Random's outputs can reveal its internal state. Only a cryptographically secure generator (SecureRandom) is suitable.
5. Your scan says log4j-core 2.14.1 is in your app, but your pom.xml doesn't list Log4j. How did it get there and how do you fix it?
Solution
It is a transitive dependency of another library. Find which one with mvn dependency:tree, then upgrade that library, or override the version in <dependencyManagement> to 2.17.1 or later, and re-scan.
Quick quiz
// name and pass come from a login form
A: "SELECT * FROM users WHERE name='" + name + "'"
B: "...WHERE name='" + name.replace("'", "") + "'"
C: prepareStatement("...WHERE name=? AND pass=?")
D: "...WHERE name='" + name.toUpperCase() + "'"
Which login query is safe?
Answer
C. Only the PreparedStatement keeps the SQL fixed and sends name and pass separately as data. A glues input in; B tries to filter quotes (fragile: other tricks and encodings exist); D changes letters but still glues input into the SQL.
Interview questions
- Why does a PreparedStatement prevent SQL injection? The query's structure is sent and parsed before the values; bound values are always treated as data, never parsed as SQL.
- Is JPA/Hibernate automatically safe from injection? No. Its query methods are safe only with parameters; building JPQL/HQL strings with
+is injectable. - What is insecure deserialization, and what did JEP 290 add? Rebuilding objects from untrusted bytes lets the attacker choose which classes are instantiated; JEP 290 (JDK 9) added filters that allow or reject classes and limit depth/size before each object is created.
- What is XXE and how do you prevent it in Java? XML external entities make the parser read files or URLs; prevent it by disabling DOCTYPE (
disallow-doctype-decl) or external entities on every parser factory. - Random vs SecureRandom?
Randomis a seeded, predictable PRNG for simulations;SecureRandomis cryptographically secure, for tokens and keys. - What is a provider in the JCA? A pluggable library that implements algorithms requested by name (e.g.
SUN,SunJCE, Bouncy Castle). - Explain Log4Shell in two sentences. Log4j 2 expanded
${jndi:...}lookups found in logged text, which could fetch and run a remote Java class, so logging attacker-controlled text led to remote code execution (CVE-2021-44228, CVSS 10). The fix was upgrading (2.17.1+), and the lesson is to know and scan your dependencies. - What is a transitive dependency and why does it matter for security? A library your library depends on; you ship its vulnerabilities even though you never chose it, so scanning must cover the whole tree.
Glossary
| Term | Meaning |
|---|---|
| memory-safe language | a language that prevents buffer overflows and use-after-free in normal code (Java is one) |
| SQL | the language used to query and change data in a relational database |
| string concatenation | gluing strings together, e.g. with + |
| SQL injection | user input treated as SQL code, changing the query's meaning |
| JDBC | Java Database Connectivity: Java's standard database API |
PreparedStatement |
a JDBC query with ? placeholders; values are bound separately as data |
| JPA | Jakarta Persistence API: Java's standard for mapping objects to database rows |
| Hibernate | the most widely used JPA implementation (ORM) |
| ORM | object-relational mapper: maps classes to tables |
| JPQL / HQL | JPA's / Hibernate's query languages |
| named parameter | a placeholder like :name filled with setParameter |
| Bean Validation | Jakarta Validation: rules as annotations (@NotNull, @Size, @Email) |
| serialization | turning an object into bytes |
| deserialization | rebuilding an object from bytes (readObject) |
| insecure deserialization | deserializing untrusted bytes, letting an attacker choose what gets built |
| gadget class | an existing class that does risky work while being deserialized |
| JEP 290 | the JDK 9 feature "Filter Incoming Serialization Data" |
ObjectInputFilter |
the interface/filters that allow or reject classes during deserialization |
jdk.serialFilter |
the system/security property that sets a JVM-wide serialization filter |
| allow-list | a list of what is permitted; everything else is refused |
| XML | a tag-based text format for data |
| DOCTYPE / DTD | a declaration at the top of XML that can define entities and structure |
| entity | an XML shortcut (&x;) replaced by defined text |
| external entity | an entity whose text is fetched from a file or URL |
| XXE | XML External Entity injection: user XML makes the parser read files or URLs |
DocumentBuilderFactory |
Java's factory for DOM XML parsers |
disallow-doctype-decl |
parser feature that rejects any DOCTYPE, blocking XXE |
| PRNG | pseudo-random number generator: a formula producing number sequences from a seed |
| seed | the starting number of a PRNG; same seed, same sequence |
SecureRandom |
Java's cryptographically secure random generator |
| OTP | one-time password, e.g. a 6-digit SMS code |
| session token | a random value that identifies a logged-in session |
| JCA | Java Cryptography Architecture: request algorithms by name from providers |
| provider | a library that implements JCA algorithms (SUN, SunJCE, ...) |
| hash / SHA-256 | a fixed-size fingerprint of data; SHA-256 gives 256 bits |
| AES | the standard symmetric encryption algorithm |
| KeyStore | a password-protected container for keys and certificates |
| PKCS12 | the standard KeyStore file format (.p12) |
| Spring / Spring Security | the popular Java web framework / its security module (filter chain) |
| authentication / authorization | proving who you are / checking what you may do |
| CSRF | cross-site request forgery: tricking a logged-in browser into sending a request |
| bcrypt | a slow, salted password-hashing algorithm |
| Log4j | Apache's popular Java logging library |
| lookup (Log4j) | ${...} text in a log message that Log4j replaced with a value |
| JNDI | Java Naming and Directory Interface: an API for finding resources, including on other servers |
| Log4Shell | CVE-2021-44228: remote code execution via JNDI lookups in Log4j 2 |
| RCE | remote code execution: an attacker makes a server run their code |
| CVSS | Common Vulnerability Scoring System: severity from 0 to 10 |
| Maven / Gradle | Java build tools that download and manage libraries |
| transitive dependency | a dependency of a dependency |
| SCA | software composition analysis: checking dependencies for known vulnerabilities |
| OWASP Dependency-Check | OWASP's free SCA tool (CLI, Maven/Gradle plugins, Ant) |
| SBOM | software bill of materials: the list of components you ship |
Summary
- Java is memory-safe, but injection, deserialization, XML parsing, randomness, key handling and libraries are where Java apps break.
- PreparedStatement and JPA named parameters stop SQL injection; Bean Validation checks input at the door.
- JEP 290 filters allow-list what
readObjectmay build; prefer JSON for outside data. disallow-doctype-declstops XXE.SecureRandomfor every secret; the JCA for crypto; keys in a KeyStore; Spring Security for the web layer.- Log4Shell showed that you ship your libraries' bugs: know your dependency tree (Maven/Gradle) and scan it with OWASP Dependency-Check on every build.
- Next episode: secure coding in Python.
Sources (fetched 12 Nov 2026)
- OpenJDK, JEP 290: Filter Incoming Serialization Data: https://openjdk.org/jeps/290
- OWASP XML External Entity Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
- IBM, "What is Log4Shell?": https://www.ibm.com/think/topics/log4shell
- Malwarebytes, "Log4j zero-day 'Log4Shell' arrives just in time to ruin your weekend" (9-10 Dec 2021): https://www.malwarebytes.com/blog/exploits-and-vulnerabilities/2021/12/log4j-zero-day-log4shell-arrives-just-in-time-to-ruin-your-weekend/
- OWASP Dependency-Check: https://owasp.org/www-project-dependency-check/