This rule highlights the importance of avoiding the construction of file paths from untrusted data, such as user input. This is a critical security practice because malicious users can exploit such vulnerabilities to traverse directories (also known as path traversal attacks), gaining unauthorized access to files outside of the intended directory.
The rule helps prevent potential data breaches, unauthorized access to sensitive information, and system compromise. It enforces the principle of least privilege, ensuring that an application only accesses the resources it needs to function properly.
To adhere to this rule, always sanitize and validate user input before using it to construct file paths. For instance, use canonicalization to resolve any ‘..’ sequences in the path, and ensure the resulting path is within the intended directory. Avoid direct concatenation of user input into file paths. Instead, consider using a safer method, such as File(baseDir, fileName), which implicitly handles path normalization. You can also use an allowlist of allowed paths or a blocklist of disallowed paths to control access.
Non-Compliant Code Examples
// Non-compliant: Unsafe file path handling
classFileService{privatevalbaseDir="/app/files/"funreadUserFile(request:ApplicationCall){// WARNING: Direct use of user input in file paths
valuserPath=request.parameters["path"]valfile=File(userPath)// Unsafe direct use of user input
file.readText()}}
Compliant Code Examples
classSecureFileService{privatevalbaseDir="/app/files/"suspendfungetFile(call:ApplicationCall){valfileName=call.parameters["fileName"]?:throwBadRequestException("Missing fileName")// Normalize and validate path
valnormalizedPath=File(fileName).normalize().toString()if(normalizedPath.contains("..")){throwSecurityException("Path traversal attempted")}valsafePath=baseDir+normalizedPath.replace("../","")valabsolutePath=File(safePath).canonicalPath// Verify file is within allowed directory
if(!absolutePath.startsWith(File(baseDir).canonicalPath)){throwSecurityException("Access denied to path outside base directory")}valfile=File(absolutePath)if(file.exists()){call.respondFile(file)}else{call.respond(HttpStatusCode.NotFound)}}}// Usage in a route
get("/download/{fileName}"){secureFileService.getFile(call)}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines