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 생성
Datadog의 무료 IDE Plugins를 사용하거나 Code Security 스캔을 CI 파이프라인에 추가