文件上传是一个常见的功能,但也是一个重大的安全风险——恶意文件可能导致代码执行、恶意软件传播或系统泄露。保护上传需要验证文件类型、大小和内容,安全地存储文件,并谨慎地提供这些文件。
文件上传的风险
Allowing users to upload files is dangerous if not secured:
✗ MALICIOUS executable/script files → could run on the server (e.g. uploading a web
shell / script that gets executed → server compromise)
✗ MALWARE distribution (files served to other users)
✗ Oversized files → denial of service (disk/memory exhaustion)
✗ Path traversal in filenames (../../) → overwrite system files
✗ Files with misleading types/content (a .jpg that's actually a script)
保护文件上传
✓ VALIDATE file TYPE → check the actual CONTENT/MIME (not just the extension, which lies);
ALLOWLIST permitted types (don't blocklist); reject everything else
✓ LIMIT file SIZE → prevent resource exhaustion (max upload size)
✓ Don't execute uploads → store OUTSIDE the web root; never serve from an executable
directory; serve via a handler (not directly executable)
✓ RENAME files (random/generated names) → avoid path traversal and overwrites; sanitize
filenames
✓ SCAN for malware where appropriate; set correct Content-Type/Content-Disposition when serving
✓ Use separate storage/domain or object storage (S3) for user files; access controls
