logo

Database

Python Markup Safe User Input

Description

Detects potential Cross-Site Scripting (XSS) vulnerabilities in Python code where untrusted user input is passed directly to markup/templating functions without proper escaping or sanitization. This can allow attackers to inject malicious scripts that execute in users' browsers.

Weakness:

014 - Insecure functionality

Category: Functionality Abuse

Detection Strategy

    • Check for imports of potentially dangerous markup/templating libraries or functions

    • Identify function calls to these dangerous markup functions by their identifier names

    • Analyze the function arguments to determine if they contain or originate from user input

    • Flag cases where user-controlled data flows into markup functions without proper sanitization or escaping

Vulnerable code example

from django.http import HttpRequest
from django.utils.safestring import mark_safe
from django.shortcuts import render

def vulnerable_xss(request):
    user_input = request.GET.get('name', '')  
    html_output = mark_safe(f"<h1>{user_input}</h1>")  # VULNERABLE: Directly marks user input as safe HTML
    return render(request, 'template.html', {'content': html_output})

✅ Secure code example

from django.http import HttpRequest
from django.shortcuts import render

def secure_view(request):
    user_input = request.GET.get('name', '')
    # Let Django's template engine handle HTML escaping automatically
    return render(request, 'template.html', {'content': user_input})