You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java及JSP文件上传触发Fortify‘文件上传误用’告警,求修复方案

Hey there, let's fix that Fortify "Often Misused: File Upload" warning you're seeing! The root issue is that your current code skips critical security checks for uploaded files, which is why Fortify is flagging both the Java backend method and the JSP file input. Here's a step-by-step solution:

Backend (Java) Fixes

The core security checks need to happen on the backend—frontend checks are just for user experience, not actual security. Update your setAttachedFile method with these mandatory validations:

public void setAttachedFile(FormFile formFile) {
    attachedFile = formFile;
    if (attachedFile != null) {
        // 1. Enforce maximum file size (example: 10MB limit)
        long maxAllowedSize = 10 * 1024 * 1024; // 10MB in bytes
        if (attachedFile.getSize() > maxAllowedSize) {
            throw new IllegalArgumentException("File exceeds maximum allowed size of 10MB");
        }

        // 2. Validate file type using a whitelist (never use blacklists—they're easy to bypass)
        String allowedExtensions = "pdf,doc,docx,xls,xlsx,jpg,png";
        String fileName = attachedFile.getFileName().toLowerCase();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        
        if (!allowedExtensions.contains(fileExtension)) {
            throw new IllegalArgumentException(
                "Invalid file type. Allowed types: " + allowedExtensions
            );
        }

        // 3. Sanitize filename to prevent path traversal attacks
        String safeFileName = sanitizeFileName(fileName);
        // If your FormFile allows modifying the filename, update it here
        // attachedFile.setFileName(safeFileName);

        // 4. Optional but recommended: Validate file content (check file headers to avoid fake extensions)
        if (!isValidFileContent(attachedFile.getInputStream())) {
            throw new IllegalArgumentException("File content is invalid or malicious");
        }

        formData.put("attachedFile", attachedFile);
    } else {
        formData.remove("attachedFile");
    }
}

// Helper: Clean filename to remove path traversal characters and special symbols
private String sanitizeFileName(String fileName) {
    // Keep only letters, numbers, dots, underscores, and hyphens; remove ../ or \ characters
    return fileName.replaceAll("[^a-zA-Z0-9._-]", "")
                   .replaceAll("\\.\\./", "")
                   .replaceAll("\\\\", "");
}

// Helper: Check file header to verify actual file type (example for PDF, JPG, PNG)
private boolean isValidFileContent(InputStream inputStream) throws IOException {
    byte[] headerBytes = new byte[4];
    inputStream.read(headerBytes);
    inputStream.reset(); // Reset stream so it can be read again later

    String header = new String(headerBytes);
    // Check for common valid file headers
    return header.startsWith("%PDF-") // PDF
        || (headerBytes[0] == (byte)0xFF && headerBytes[1] == (byte)0xD8) // JPG
        || header.startsWith("\u0089PNG"); // PNG
}
Frontend (JSP) Fixes

While frontend checks don't replace backend validation, they improve user experience and reduce unnecessary requests. Update your file input with these tweaks:

<table width="100%" border="0" cellspacing="0" cellpadding="3">
    <tr>
        <td class="label" width="1%">&nbsp;</td>
        <td class="label" width="22%">Select File Name</td>
        <td class="field" width="26%">&nbsp;
            <input class="textfield width450" 
                   type="file" 
                   name="File_Name" 
                   maxlength="255" 
                   accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png"
                   onchange="validateUploadedFile(this)">
            <script>
                function validateUploadedFile(input) {
                    const file = input.files[0];
                    if (!file) return;

                    // Check file size (match backend limit)
                    const maxSize = 10 * 1024 * 1024;
                    if (file.size > maxSize) {
                        alert("File is too large! Max allowed size is 10MB.");
                        input.value = "";
                        return;
                    }

                    // Check file MIME type
                    const allowedMimeTypes = [
                        "application/pdf",
                        "application/msword",
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                        "application/vnd.ms-excel",
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        "image/jpeg",
                        "image/png"
                    ];
                    if (!allowedMimeTypes.includes(file.type)) {
                        alert("Invalid file type! Allowed types: PDF, Word, Excel, JPG, PNG.");
                        input.value = "";
                        return;
                    }
                }
            </script>
        </td>
    </tr>
</table>
Extra Security Best Practices

To make your file upload feature even more secure:

  • Store uploaded files outside your web root directory (never in /WEB-INF or public access folders) to prevent direct execution of malicious scripts.
  • Use randomly generated filenames instead of the user-provided ones to avoid filename conflicts and path traversal risks.
  • Set appropriate HTTP headers (like Content-Disposition: attachment) when serving uploaded files to force browsers to download them instead of executing.
  • Regularly scan uploaded directories for malware or suspicious files.

内容的提问来源于stack exchange,提问作者Rosy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:23