Unrestricted upload of dangerous file type High

Insufficiently restricted file uploads can allow a file to be uploaded that runs malicious code. For example, a website that doesn't check the file extension of an image can be exploited by uploading a script with an extension, such as .php or .asp, that can be run on the server.

Detector ID
python/unrestricted-file-upload@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1from flask import app
2
3
4@app.route('/', methods=['GET', 'POST'])
5def file_upload_non_compliant():
6    import os
7    from flask import request
8    upload_file = request.files['file']
9    # Noncompliant: the uploaded file can have any extension.
10    upload_file.save(os.path.join('/path/to/the/uploads',
11                                  upload_file.filename))

Compliant example

1from flask import app
2
3
4@app.route('/', methods=['GET', 'POST'])
5def file_upload_compliant():
6    import os
7    from flask import request
8    extensions = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
9    upload_file = request.files['file']
10    # Compliant: the uploaded file must have one of the allowed extensions.
11    if '.' in upload_file.filename and \
12            upload_file.filename.split('.')[-1] in extensions:
13        upload_file.save(os.path.join('/path/to/the/uploads',
14                                      upload_file.filename))