Insecure File Uploads
Vulnerable Code:
javaCopy codePart filePart = request.getPart("file");
filePart.write("/uploads/" + filePart.getSubmittedFileName());Reason for vulnerability: No validation or sanitization of the uploaded file.
Fixed Code:
javaCopy codePart filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
if (!isValidFile(fileName)) {
throw new IllegalArgumentException("Invalid file");
}
filePart.write("/uploads/" + fileName);Reason for fix: Validate and sanitize the uploaded file name.
Vulnerable Code:
pythonCopy code@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file.save(os.path.join('/uploads', file.filename))Reason for vulnerability: No validation or sanitization of the uploaded file.
Fixed Code:
Reason for fix: Use secure_filename and validate the uploaded file name.
Vulnerable Code:
Reason for vulnerability: The code doesn't validate the uploaded file type. An attacker could upload executable files that could be executed on the server.
Fixed Code:
Java Example
Vulnerable Code:
Reason for Vulnerability:
This code allows uploading of any file type to any location, potentially leading to execution of malicious files.
Fixed Code:
Reason for Fix:
The fixed code validates file types, uses a random filename, and restricts the upload directory to prevent malicious file uploads and overwriting.
PHP Example
Vulnerable Code:
Reason for Vulnerability:
This code allows uploading of any file type with any name, potentially leading to execution of malicious files.
Fixed Code:
Reason for Fix:
The fixed code validates file types, uses a random filename, and restricts the upload directory to prevent malicious file uploads.
Python Example
Vulnerable Code:
Reason for Vulnerability:
This code allows uploading of any file type with any name to a specified directory, potentially leading to security issues.
Fixed Code:
Reason for Fix:
The fixed code validates file types, uses secure_filename to sanitize filenames, and restricts the upload directory to prevent security issues.
Last updated