Filename coming from the request

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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