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)}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다