---
title: Limit Upload File Size And Count
impact: MEDIUM
impactDescription: prevents Denial of Service (DoS) attacks via disk or memory exhaustion
tags: upload, file-size, dos, limits, security, kotlin
---

## Limit Upload File Size And Count

Allowing unlimited file uploads can quickly lead to server instability or crashes by exhausting disk space, memory, or CPU (during processing). All file upload endpoints must have strict limits on file size, number of files, and file types.

**Incorrect (no limits):**

```kotlin
// Ktor: No multi-part configuration
@PostMapping("/upload")
fun upload(@RequestParam("file") file: MultipartFile) {
    // No check on file.size or file.contentType
    save(file)
}
```

**Correct (explicit limits):**

```kotlin
// Ktor Configuration
install(ContentNegotiation) {
    // Limits can be enforced at the server level
}

// Spring Boot application.properties
// spring.servlet.multipart.max-file-size=5MB
// spring.servlet.multipart.max-request-size=10MB

// Manual validation in Controller
@PostMapping("/upload")
fun handleUpload(@RequestParam("files") files: Array<MultipartFile>): ResponseEntity<Any> {
    // 1. Limit File Count
    if (files.size > 5) {
        return ResponseEntity.badRequest().body("Max 5 files allowed")
    }

    files.forEach { file ->
        // 2. Limit File Size
        if (file.size > 5 * 1024 * 1024) { // 5MB
            return ResponseEntity.status(413).body("File ${file.originalFilename} is too large")
        }

        // 3. Limit Content Type
        val allowedTypes = listOf("image/jpeg", "image/png", "application/pdf")
        if (!allowedTypes.contains(file.contentType)) {
            return ResponseEntity.badRequest().body("Unsupported file type: ${file.contentType}")
        }
    }
    
    // Process files...
    return ResponseEntity.ok("Success")
}
```

**Attack Vectors Prevented:**
- **Disk Exhaustion:** Filling up server storage with massive files.
- **Memory Exhaustion:** Trying to buffer large files in RAM.
- **Zip Bomb:** Uploading small compressed files that expand to petabytes (if unzipping on server).
- **Remote Code Execution:** Restricted via file-type whitelisting (preventing `.php`, `.jsp`, `.sh` uploads).

**Tools:** Spring Multipart Config, Ktor MultiPartData, NGINX `client_max_body_size`, Manual Audit
