Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 134 ยท Testing and Tooling

Secure Kotlin Code

Write secure Kotlin: validate input at the boundary, avoid injection, handle secrets and passwords safely, compare in constant time and avoid dangerous Java deserialization.

Kotlin's type system removes whole families of bugs: null pointer errors are caught by the compiler, immutable val and read-only collections limit accidental changes, and when expressions force you to handle every case. But the compiler cannot see security problems. A perfectly typed function can still build a SQL query out of user text, print a password to a log file or read a malicious object from the network. Security is about trust: which data do you control, and which comes from outside?

This lesson covers the most common mistakes in server-side and Android Kotlin code: unvalidated input, injection, secrets in the wrong place, weak password handling, timing leaks and unsafe deserialization. The examples use the standard library and the JDK, so most of them run here. It is a first guide, not a complete security course. Always combine it with the guidance of your framework (see Spring Boot with Kotlin) and a review by someone who knows your system.

The idea: validate at the boundary

Everything that enters your program from outside is untrusted: HTTP parameters and bodies, headers, cookies, file contents, command-line arguments, environment variables, database values that users wrote earlier. Check it once, at the boundary, and convert it into a type that can only hold valid values. The rest of the program then works with trusted types.

flowchart LR
    A["Untrusted input<br/>(strings)"] --> B["Validate and parse"]
    B -->|"valid"| C["Domain types<br/>(Email, Age, UserId)"]
    B -->|"invalid"| D["Reject with error"]
    C --> E["Business logic"]

Validate once at the edge; inside, only valid domain types exist.

Kotlin makes this pleasant with value classes, init blocks and the require function:

Kotlin Making invalid states impossible

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notes on the code: toIntOrNull does not throw on bad numbers, ranges are checked after parsing, and the pattern has length limits on each part. Always limit the size of input; a regex or parser fed a huge string can become a denial-of-service problem. Prefer allow lists ("these characters are fine") over deny lists ("these characters are dangerous"), because attackers are good at finding the character you forgot. The private constructor makes Email.parse the only way to create an Email.

Injection: never build commands from text

Injection happens when user text is mixed with code in the same string: SQL, shell commands, HTML, LDAP filters, file paths. The program then cannot tell data from instructions. The Kotlin string template is convenient and therefore dangerous here:

Kotlin How string-built SQL changes meaning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The second line asks for every user, because the quote in the input ended the string literal. The cure is parameterized queries: the SQL text is fixed and the values travel separately, so the database never interprets them as code:

Kotlin
// read-only example: JDBC needs a database
connection.prepareStatement("SELECT id, name FROM users WHERE name = ?").use { stmt ->
    stmt.setString(1, name)          // the value is data, whatever characters it contains
    stmt.executeQuery().use { rows ->
        while (rows.next()) { println(rows.getString("name")) }
    }
}

Libraries such as Exposed and jOOQ use bound parameters by default, but they also have raw-SQL escape hatches; the rule is the same there. For other targets:

  • HTML: use a template engine that escapes by default, never build pages from raw strings (cross-site scripting).
  • Shell commands: avoid the shell. ProcessBuilder("git", "log", userBranch) passes arguments separately, while "sh -c \"git log $userBranch\"" does not.
  • File paths: normalize and check that the result stays inside the allowed folder (see below).
Kotlin Stopping path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The user-supplied .. parts walk out of the folder, but after normalize() the startsWith check catches them. Note that resolve with an absolute second path replaces the base, which is also caught. On a real file system, symbolic links need an extra check with toRealPath() (see Java NIO paths).

Secrets: keep them out of code, logs and strings

A secret is a password, API key, token or private key. Four rules cover most cases:

  1. Never put secrets in source code or Git. Read them from environment variables, a secrets manager or an encrypted configuration, and keep that file out of the repository.
  2. Never log them. A data class generates a toString() that prints every property, so one log.info("login: $request") can write passwords into log files. Override toString or wrap the secret in a type that hides itself.
  3. Do not put them in URLs. URLs end up in logs, browser history and referrer headers. Send tokens in headers or in the body.
  4. Keep them short-lived and rotate them. A leaked key that expires is a smaller problem.
Kotlin A secret type that hides itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Strings are immutable and may stay in memory until garbage collection, so on the JVM you cannot reliably erase a secret held in a String. Libraries use CharArray for passwords for that reason (it can be overwritten with fill('\u0000')), but this is defense in depth, not a replacement for the rules above.

Passwords and hashing

Never store a password, and never store a plain hash of it. A fast hash like SHA-256 can be tried billions of times per second. Use a slow, salted password hashing function: Argon2id, bcrypt, scrypt or at least PBKDF2 with a high iteration count. The JDK has PBKDF2; your framework (Spring Security) provides the stronger algorithms ready to use.

Two more mistakes to avoid are comparing secrets with == (which stops at the first different character and so leaks, through timing, how much was correct) and using kotlin.random.Random for tokens (it is not cryptographically secure). The JDK offers MessageDigest.isEqual and SecureRandom.

Kotlin PBKDF2 and constant-time comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output uses only lengths and booleans, so it is the same on every run, but the salt and hash themselves are random and different each time, as they should be. The salt is stored next to the hash; its job is to make every hash unique so that attackers cannot reuse precomputed tables.

Deserialization pitfalls

Turning bytes back into objects is one of the most dangerous operations in software. Java's built-in serialization (ObjectInputStream, Serializable) can instantiate almost any class on the classpath while reading, and attackers have built "gadget chains" from common libraries that run code during deserialization. The rules:

  • Never deserialize untrusted data with ObjectInputStream. Use a data format instead: JSON, Protobuf or CBOR with a library that maps to explicit classes, such as kotlinx.serialization.
  • Avoid polymorphic "any type" features. Jackson's default typing and similar options that read a class name from the input let the sender choose the class. Use sealed hierarchies or an allow list of subtypes.
  • If you must read Java serialization, install a filter that allows only the classes you expect:
Kotlin An ObjectInputFilter allow list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The pattern java.lang.*;java.util.*;!* says: allow these packages and reject everything else. The class from the input is rejected before any of its code can run. Even with a filter, prefer a plain data format.

Also remember: a data class that comes from a trusted JSON parser is still untrusted data. Parsing proves the shape is right, not that the values make sense. Validate ranges, lengths and relationships after parsing (see require).

More habits that help

  • Keep dependencies updated and scan them (Dependabot, OWASP Dependency-Check, ./gradlew dependencyUpdates). Many real attacks use known bugs in old libraries.
  • Use least privilege: database accounts with only the needed rights, containers that do not run as root.
  • Fail closed: when a check cannot be completed, deny access.
  • Do not leak details in errors. Return a short message to the client, and log the full exception on the server (see logging).
  • Prefer HTTPS everywhere, and do not disable certificate validation "to make the test work".
  • Treat logs as untrusted output: user text containing line breaks can fake log entries, so strip or encode control characters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main idea behind validating at the boundary?

    After a single check at the edge, the rest of the program uses domain types that make invalid states impossible.
  2. 2. Why does "SELECT * FROM users WHERE name = '$name'" allow SQL injection?

    Data and code share one string. A parameterized query keeps them separate, so the value is never interpreted as SQL.
  3. 3. Why is a data class risky for objects that hold passwords?

    A log line like "login: $request" would write the password into the log. Hide the secret in a type with its own toString.
  4. 4. What should you do instead of using Java's ObjectInputStream on data from the network?

    Java serialization can instantiate arbitrary classes while reading. Plain data formats only fill the classes you declare.
  5. 5. Why compare secrets with MessageDigest.isEqual instead of ==?

    A normal comparison stops at the first difference, so timing can reveal how many leading bytes were right. A constant-time comparison avoids that.

Summary

  • Treat every input from outside as untrusted; validate and parse it once at the boundary into types that cannot hold invalid values.
  • Limit sizes, prefer allow lists and use require and toIntOrNull for checks.
  • Prevent injection by never building SQL, shell commands or HTML from raw strings; use parameters, argument lists and escaping templates.
  • Normalize file paths and check that they stay inside the allowed folder.
  • Keep secrets out of source code, logs and URLs; hide them from toString.
  • Store passwords only with a slow salted algorithm (Argon2id, bcrypt, scrypt or PBKDF2) and compare in constant time; use SecureRandom for tokens.
  • Do not deserialize untrusted data with Java serialization; use explicit data formats and allow lists.
  • Keep dependencies updated, use least privilege and fail closed.

Next: Code Style, ktlint and detekt