IC Improve Code Recipes

Recipe 7.6 · Python

Protecting Against SQL Injection and Path Traversal

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Two attacks show up on almost every review I do. SQL injection, from search screens that splice user input into SQL, especially for sort columns and LIKE filters where "parameters don't work." And path traversal, from download or upload handlers that join a user-supplied file name to a folder, so that ..\..\web.config walks out of the folder.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Install: pip install fastapi

Python Concatenated SQL with user sort and an untrusted file path (p157_r7_6_sql_concat_path_traversal_before.py)
"""Concatenated SQL with user sort and an untrusted file path

Source: ImproveCode, Chapter 7, Recipe 7.6 "Protecting Against SQL Injection and Path Traversal"
Section: The way it's often written
Book page: 157  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Web Forms Request/Response become FastAPI Request and FileResponse.
"""

import os

from fastapi import Request
from fastapi.responses import FileResponse


def build_search_sql(txt_name: str, request: Request) -> str:
    # Not this: injectable filter and sort, and a traversable path.
    sql = ("SELECT * FROM Customer WHERE LastName LIKE '" +
           txt_name + "%' ORDER BY " + request.query_params["sort"])
    return sql


def send_report(request: Request) -> FileResponse:
    file = os.path.join("D:\\Reports", request.query_params["name"])
    return FileResponse(file)

The improved recipe

Parameters for every value, an allow-list for identifiers such as sort columns, escaped LIKE wildcards, and a path helper that resolves the full path and checks it is still inside the base folder. The SQL part uses Microsoft.Data.SqlClient.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Parameterized customer search with whitelisted sort columns (p157_r7_6_customer_search_safe_sort.py)
"""Parameterized customer search with whitelisted sort columns

Source: ImproveCode, Chapter 7, Recipe 7.6 "Protecting Against SQL Injection and Path Traversal"
Section: The improved recipe
Book page: 157-158  -- original C# listing
Converted from C# to Python.
pyodbc with ? parameters replaces SqlCommand; instead of returning a command
object, create() returns the SQL text and its parameter tuple.
"""

# Identifiers can't be parameters, so map names to known SQL.
_SORT_COLUMNS: dict[str, str] = {
    "name": "c.LastName",
    "city": "c.City",
    "created": "c.CreatedUtc",
}


def create(last_name_prefix: str | None, sort: str | None,
           descending: bool) -> tuple[str, tuple[str]]:
    order_by = (_SORT_COLUMNS.get(sort.lower(), _SORT_COLUMNS["name"])
                if sort is not None else _SORT_COLUMNS["name"])

    direction = "DESC" if descending else "ASC"

    sql = f"""
SELECT TOP (200) c.CustomerId, c.LastName, c.City
FROM dbo.Customer AS c
WHERE c.LastName LIKE ? ESCAPE '\\'
ORDER BY {order_by} {direction}, c.CustomerId;
"""

    prefix = _escape_like(last_name_prefix or "") + "%"
    return sql, (prefix,)


# Makes %, _ and [ in user input match literally.
def _escape_like(value: str) -> str:
    return (value.replace("\\", "\\\\")
                 .replace("%", "\\%")
                 .replace("_", "\\_")
                 .replace("[", "\\["))


# Usage: cursor.execute(*create("O'Br", "city", False))

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Resolving untrusted relative paths without escaping the base folder (p158_r7_6_safe_path_resolve.py)
"""Resolving untrusted relative paths without escaping the base folder

Source: ImproveCode, Chapter 7, Recipe 7.6 "Protecting Against SQL Injection and Path Traversal"
Section: The improved recipe
Book page: 158-159  -- original C# listing
Converted from C# to Python.
os.path.abspath/join replace Path.GetFullPath/Combine; PermissionError stands in
for UnauthorizedAccessException; os.path.normcase gives case-insensitive compare on Windows.
"""

import os


class SafePath:
    @staticmethod
    def resolve(base_folder: str, untrusted: str) -> str:
        """Combines a base folder with an untrusted relative path and raises
        if the result escapes the base folder."""
        if not base_folder or not base_folder.strip():
            raise ValueError("base_folder")
        if not untrusted or not untrusted.strip():
            raise ValueError("untrusted")

        root = os.path.abspath(base_folder)
        if not root.endswith((os.sep, os.altsep or os.sep)):
            root += os.sep

        full = os.path.abspath(os.path.join(root, untrusted))

        if not os.path.normcase(full).startswith(os.path.normcase(root)):
            raise PermissionError(
                "The requested path is outside the allowed folder.")

        return full

    @staticmethod
    def resolve_file_name(base_folder: str, untrusted_name: str) -> str:
        """For downloads by name: drops any folder part."""
        return SafePath.resolve(
            base_folder, os.path.basename(untrusted_name.replace("\\", "/")))

How it works

A parameter is sent to SQL Server separately from the SQL text, so its value is always data and never code, no matter what it contains. Chapter 1 covers parameters in depth. The two places people say parameters "don't work" are handled here.

Sort columns are identifiers, which can't be parameters. The fix is an allow-list: the user sends a short name such as city, and the code maps it to a fixed piece of SQL it wrote itself. Anything not on the list falls back to the default. User input never reaches the SQL text, only your own constants do. The extra c.CustomerId in the ORDER BY makes paging stable when names repeat.

For LIKE, the value is a parameter, but %, _ and [ inside it are still wildcards. A user searching for 100% or a name containing an underscore would get wrong results, and % alone would return everything. EscapeLike turns them into literals using the ESCAPE '\' clause. The parameter is typed with a length (NVARCHAR(102) for a 50-character column after escaping, plus the %), which also keeps query plans reusable (Chapter 1, Recipe 1.2).

For paths, Path.GetFullPath resolves .. segments, so ..\..\web.config becomes the real target before the check. If the untrusted part is absolute (C:\Windows\win.ini or \\server\share\x), Path.Combine returns it unchanged and the check rejects it. Adding the trailing separator to the root stops the classic near miss where D:\Reports accepts D:\ReportsArchive\secret.pdf because the string starts with the same characters.

Variations and pitfalls

  • The check is lexical. A symbolic link or junction inside the base folder can still point elsewhere. Don't let users create links there, and resolve links with FileSystemInfo.ResolveLinkTarget if the folder isn't fully under your control.
  • Better still, don't use user-supplied names on disk at all. Store uploads under a generated name (a GUID) and keep the original name in the database. Chapter 10 covers file handling further, and Chapter 8 covers validating uploads.
  • Dynamic SQL inside stored procedures needs the same discipline: sp_executesql with parameters for values and QUOTENAME for identifiers (Chapter 2).
  • Command injection is the same bug with Process.Start. Use ProcessStartInfo.ArgumentList, which quotes each argument, instead of building an Arguments string from input.
  • Run the app's database login with the least privilege it needs. If injection does slip through, a login that can only execute the app's procedures limits the damage.