# 通过Content-Disposition绕过恶意文件上传导致的XSS

- **ID:** `security/xss-via-malicious-file-upload-with-content-disposition-bypass`
- **领域:** security
- **类别:** resource_error
- **错误码:** `XSS_FILE_UPLOAD_CONTENT_DISPOSITION`
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

当文件上传端点在Content-Disposition头中返回用户提供的文件名而未进行适当清理时，攻击者可以注入脚本代码，在下载文件时在浏览器中执行。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Apache Tomcat 9.0.70 | active | — | — |
| Spring Boot 2.7.10 | active | — | — |
| Nginx 1.24.0 | active | — | — |
| IIS 10.0 | active | — | — |

## 解决方案

1. ```
   Sanitize the filename by stripping all non-alphanumeric characters except dots and hyphens. Example in Python: import re; safe_filename = re.sub(r'[^a-zA-Z0-9._-]', '', original_filename). Then set Content-Disposition to attachment; filename="safe_filename" and ensure Content-Type is correct.
   ```
2. ```
   Use a random UUID as the filename on the server and store the original filename in a database, never returning it in headers. Example: response.setHeader('Content-Disposition', 'attachment; filename="' + uuid + '"');
   ```
3. ```
   Add Content-Security-Policy header with 'sandbox' directive for file download endpoints to prevent script execution.
   ```

## 无效尝试

- **** — Sanitizing the filename by removing only script tags is insufficient because attackers can use event handlers like onerror or encode characters to bypass filters. (65% 失败率)
- **** — Setting Content-Type to application/octet-stream does not prevent XSS if the browser sniffs the content type or if the filename contains script that executes on download. (55% 失败率)
- **** — Using a whitelist of allowed extensions is bypassed if the filename contains script in the parameter string (e.g., file.html?script=alert(1)). (50% 失败率)
