Back-end/Spring-핵심& webMVC

파일 다운로드, 파일 업로드 API 구현 시 보안 상 유의점

prden 2023. 9. 14. 13:24

1. 파일 다운로드 

  1. Directory Traversal Attacks: Attackers might attempt to traverse directories by manipulating the fileName parameter. To prevent this, you should validate and sanitize the fileName parameter to ensure it only points to files within the designated storage directory.
  2. Authentication and Authorization: Implement proper authentication and authorization mechanisms to ensure that only authorized users can access the download API and specific files. You can use Spring Security for this purpose.
  3. Secure File Storage: Ensure that your file storage directory is not accessible via direct URL access. Store uploaded files in a directory that is not directly accessible from the web. You can use a location outside the web root or configure your web server to deny access to the storage directory.
  4. Content-Disposition Header: Be cautious with the Content-Disposition header. Make sure that you are not blindly setting it with user-supplied data. In your code, you are setting it based on the fileName parameter. Verify that the file name is safe and doesn't contain malicious content.
  5. Input Validation: Implement strict input validation to sanitize and validate user input, including the fileName parameter. Reject any input that doesn't conform to your expected file name format.
  6. Rate Limiting: Consider implementing rate limiting to prevent abuse of your download API.
  7. Logging and Monitoring: Implement logging and monitoring to track access to the download API and detect any suspicious activity.
  8. Content-Type and File Type Checking: Verify the content type of the file being requested matches the expected type based on the file extension. Don't serve files with potentially harmful content types, such as executable files.
  9. HTTPS: Ensure that your API is served over HTTPS to encrypt data in transit.
  10. Regular Updates: Keep your Spring Boot and other dependencies up to date to benefit from security patches and updates.

 

 

Directory Traversal Attacks

A Directory Traversal Attack (also known as Path Traversal Attack) is a type of security vulnerability where an attacker tries to access files or directories outside the intended scope by manipulating input that specifies a file or directory path. In the context of your file download API, here's a deeper explanation of the concept and how to prevent it:

 

1. Directory Traversal Attack Explained:

Let's say your API accepts a fileName parameter in a URL path, and you use this parameter to construct a file path on your server. For example, a request like /svc/v1/downloadfile/../../secret/passwords.txt might be sent by an attacker. If your code blindly uses the fileName parameter to construct the file path, it could allow the attacker to traverse directories and access files that they shouldn't be able to access.

In the example above, the attacker added ../../ to the fileName, trying to move up two directories before specifying the file they want to access. Without proper validation and sanitization, this could potentially allow them to access sensitive files on your server.

 

2. Preventing Directory Traversal Attacks:

To prevent directory traversal attacks, you should follow these practices:

  • Input Validation: Validate and sanitize the fileName parameter to ensure it doesn't contain any special characters or sequences that allow directory traversal. For example, you can restrict it to only contain alphanumeric characters and certain safe symbols.
  • Canonicalization: Use a method that ensures the fileName parameter is treated as a relative path and doesn't contain any directory traversal attempts. In Java, you can use the Paths class to normalize the path:
try {
            Path filePath = Paths.get(fileStoragePath).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                throw new FileNotFoundException(fileName);
            }
        } catch (MalformedURLException ex) {
            return ResponseEntity.badRequest().body("File not found");
        }
  • This code will ensure that fileName is treated as a relative path and any attempts to traverse directories will be removed.
  • Base Directory: Make sure you construct the file path using a base directory (e.g., your storage directory) and then append the fileName to it. This ensures that the file path starts within the designated storage directory, and no directory traversal is possible.
  • File Existence Check: Before serving the file, check if the file actually exists at the constructed path. If it doesn't exist, return an appropriate response (e.g., a 404 Not Found error).

 

2. 파일 업로드

 

  1. Input Validation:
    • File Type Validation: Ensure that the uploaded file is of the expected type. Check the file extension and content type to verify it matches the expected format. Don't rely solely on file extensions, as they can be manipulated.
    • File Size Limit: Set a maximum allowed file size to prevent large files from overloading your server or storage.
    • Sanitize File Names: Ensure that the file name doesn't contain any special characters or sequences that could be used for directory traversal attacks. Rename the file if necessary.
  2. File Storage:
    • Secure Storage: Store uploaded files in a location that is outside of the web root directory to prevent direct access via URLs. This way, users can't access uploaded files by guessing URLs.
    • File Permissions: Restrict file access permissions to only the necessary users or processes. Avoid using overly permissive file permissions.
    • File Deletion: Implement a retention policy and regularly clean up files that are no longer needed.
  3. Anti-Virus Scanning:
    • Consider implementing an anti-virus scanning mechanism to check uploaded files for malware or malicious content before saving them to disk.
  4. Authentication and Authorization:
    • Authenticate users and ensure that only authorized users can upload files. Implement proper access control to restrict who can upload files.
    • Validate user roles and permissions to ensure that only authorized users can access and modify uploaded files.
  5. Secure Communication:
    • Use HTTPS to encrypt data in transit between the client and server during the file upload process. This prevents eavesdropping on sensitive data.
  6. Rate Limiting:
    • Implement rate limiting to prevent abuse of your file upload API. This can help mitigate denial-of-service (DoS) attacks.
  7. Input Validation (Again):
    • Always validate and sanitize user-provided data, including file names and any other input fields in your API. Protect against cross-site scripting (XSS) and other injection attacks.
  8. Logging and Monitoring:
    • Implement logging to record details of file uploads, including timestamps, user information, and file details. Regularly review logs for suspicious activities.
    • Use monitoring tools to track API usage patterns and detect anomalies.
  9. File Overwrite Protection:
    • Implement mechanisms to prevent accidental or malicious overwriting of existing files. You can generate unique file names or append timestamps to file names.
  10. Content Disposition Headers:
    • When serving files for download, set appropriate Content-Disposition headers to indicate whether files should be displayed in the browser or treated as attachments.
  11. File Metadata Handling:
    • Be cautious when handling file metadata (e.g., EXIF data in images) as it may contain sensitive information.
  12. Error Handling:
    • Implement clear and informative error messages to prevent information leakage in case of errors or exceptions.