Filename coming from the request

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: python-django/open-filename-from-request

Language: Python

Severity: Error

Category: Security

CWE: 22

Description

Improper validation of input data, leading to potential data leaks. The path should be checked and validated before opening a file in order to prevent opening random files and leaking data.

Learn More

Non-Compliant Code Examples

def download_file1(request):
    url = request.GET.get("filename")
    print(f"url of the file: {url}")
    file = open(url, "rb")

    with open(url) as f:
        pass
    pass


def download_file2(request):
    url = request.POST.get("filename")
    print(f"url of the file: {url}")
    file = open(url, "rb")

    with open(url) as f:
        pass
    pass

def download_file3(request):
    url = request.BLA.get("filename")
    print(f"url of the file: {url}")
    file = open(url, "rb")

    with open(url) as f:
        pass
    pass

Compliant Code Examples

import os

def download_file(request):
    url = request.GET.get("filename")

    if ".." in url:
        return

    sanitized_path = os.path.realpath(url, strict=True)

    print(f"url of the file: {url}")
    file = open(sanitized_path, "rb")

    with open(sanitized_path) as f:
        pass
    pass
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis