Unrestricted Upload of File with Dangerous Type
The product allows the upload of files without properly validating the file type, which can lead to execution of malicious code.
When users can upload files without restriction, attackers may upload executable files, scripts, or other dangerous content that can be executed by the server or other users.
如何修复此漏洞
基于 3 条 Shoulder 检测规则的 Unrestricted File Upload 预防策略。
Validate file type, enforce size limits, and use generated filenames for uploads
func upload(w http.ResponseWriter, r *http.Request) { - file, header, _ := r.FormFile("file") - defer file.Close() - dst, _ := os.Create("/var/www/uploads/" + header.Filename) + r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024) + file, header, err := r.FormFile("file") + if err != nil { + http.Error(w, "Invalid file", 400) + return + } + defer file.Close() + ext := filepath.Ext(header.Filename) + allowed := map[string]bool{".jpg": true, ".png": true, ".pdf": true} + if !allowed[ext] { + http.Error(w, "File type not allowed", 400) + return + } + safeFilename := uuid.New().String() + ext + dst, _ := os.Create(filepath.Join("/var/uploads", safeFilename)) defer dst.Close() io.Copy(dst, file) }
Add fileFilter to multer to validate uploaded file types
- const upload = multer({ dest: 'uploads/' }); + const upload = multer({ + dest: 'uploads/', + fileFilter: (req, file, cb) => { + const allowed = ['image/jpeg', 'image/png', 'image/gif']; + if (allowed.includes(file.mimetype)) { + cb(null, true); + } else { + cb(new Error('Invalid file type'), false); + } + } + }); app.post('/upload', upload.single('file'), handler);
Validate file extension, MIME type, and size; use secure_filename() for paths
- from flask import request - - @app.route('/upload', methods=['POST']) - def upload(): - file = request.files['file'] - file.save(f'uploads/{file.filename}') - return {'status': 'uploaded'} + from flask import request, jsonify + from werkzeug.utils import secure_filename + + ALLOWED = {'png', 'jpg', 'pdf'} + + @app.route('/upload', methods=['POST']) + def upload(): + file = request.files['file'] + ext = file.filename.rsplit('.', 1)[-1].lower() + if ext not in ALLOWED: + return jsonify({'error': 'Invalid type'}), 400 + filename = secure_filename(file.filename) + file.save(f'uploads/{filename}') + return jsonify({'filename': filename})
查找代码中的漏洞
使用Shoulder扫描代码中的Unrestricted Upload of File with Dangerous Type模式。 3 规则.
# Scan with Shoulder CLI npx @shoulderdev/cli trust --cwe=434 # Or scan entire project npx @shoulderdev/cli trust .
检测规则 (3)
代码审查中需要关注的内容
这些模式表明潜在的Unrestricted Upload of File with Dangerous Type漏洞。在代码审查和安全审计中注意查找。
扫描你的代码库: Unrestricted Upload of File with Dangerous Type
Shoulder CLI 在整个代码库中找到易受攻击的模式。