Skip to content

9.3. Security

9.3.1. Extension Forgery Verification

The extension provided by the client must be compared and verified against the actual MIME type of the file content.

java
public class FileValidator {

  private final StorageProperties properties;

  public void validate(MultipartFile file) {
    String extension = extractExtension(file.getOriginalFilename());

    // 1. Allowed extension verification
    if (!properties.allowedExtensions().contains(extension)) {
      throw new InvalidFileException("File extension not allowed: " + extension);
    }

    // 2. MIME type verification
    String contentType = file.getContentType();
    if (contentType == null || !properties.allowedMimeTypes().contains(contentType)) {
      throw new InvalidFileException("File type not allowed: " + contentType);
    }

    // 3. File size verification
    if (file.getSize() > properties.maxFileSize()) {
      throw new InvalidFileException("File size exceeds the limit.");
    }
  }
}

9.3.2. Path Traversal Prevention

The file path must be validated to ensure it does not contain .. or absolute path components.

java
public static void validatePath(String filename) {
  if (filename.contains("..") || filename.contains("/") || filename.contains("\\")) {
    throw new InvalidFileException("Invalid filename.");
  }
}

9.3.3. Access Control

  • The file download API must be accessible only to authenticated users.
  • When necessary, authorization verification should be added to restrict downloads to the file owner only.
  • The upload directory must be configured so that the web server cannot access it directly. Files must be served exclusively through the API.

9.3.4. Prohibited Practices

Prohibited ItemReason
Serving static files from the upload directoryRisk of Path Traversal and executable file access
Storing client-provided filenames as-isRisk from special characters, duplicates, and security vulnerabilities
Validating file type by extension onlyExtension forgery is possible
Allowing unlimited file sizesRisk of DoS attacks

TIENIPIA QUALIFIED STANDARD