IC Improve Code Recipes

Recipe 7.6 · C#

Protecting Against SQL Injection and Path Traversal

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.

C#
// Not this: injectable filter and sort, and a traversable path.
string sql = "SELECT * FROM Customer WHERE LastName LIKE '" +
    txtName.Text + "%' ORDER BY " + Request["sort"];

string file = Path.Combine(@"D:\Reports", Request["name"]);
Response.TransmitFile(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.

C#
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Security;

public static class CustomerSearchCommand
{
    // Identifiers can't be parameters, so map names to known SQL.
    private static readonly Dictionary<string, string> SortColumns =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["name"] = "c.LastName",
            ["city"] = "c.City",
            ["created"] = "c.CreatedUtc"
        };

    public static SqlCommand Create(
        SqlConnection connection,
        string? lastNamePrefix,
        string? sort,
        bool descending)
    {
        string orderBy = sort is not null
            && SortColumns.TryGetValue(sort, out string? column)
            ? column
            : SortColumns["name"];

        string direction = descending ? "DESC" : "ASC";

        string sql = $"""
            SELECT TOP (200) c.CustomerId, c.LastName, c.City
            FROM dbo.Customer AS c
            WHERE c.LastName LIKE @prefix ESCAPE '\'
            ORDER BY {orderBy} {direction}, c.CustomerId;
            """;

        var command = new SqlCommand(sql, connection);
        command.Parameters.Add("@prefix", SqlDbType.NVarChar, 102)
            .Value = EscapeLike(lastNamePrefix ?? string.Empty) + "%";
        return command;
    }

    // Makes %, _ and [ in user input match literally.
    private static string EscapeLike(string value) =>
        value.Replace(@"\", @"\\")
             .Replace("%", @"\%")
             .Replace("_", @"\_")
             .Replace("[", @"\[");
}
C#
using System;
using System.IO;

namespace ImproveCode.Security;

public static class SafePath
{
    private static readonly StringComparison PathComparison =
        OperatingSystem.IsWindows()
            ? StringComparison.OrdinalIgnoreCase
            : StringComparison.Ordinal;

    /// <summary>Combines a base folder with an untrusted relative
    /// path and throws if the result escapes the base folder.
    /// </summary>
    public static string Resolve(string baseFolder, string untrusted)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(baseFolder);
        ArgumentException.ThrowIfNullOrWhiteSpace(untrusted);

        string root = Path.GetFullPath(baseFolder);
        if (!Path.EndsInDirectorySeparator(root))
        {
            root += Path.DirectorySeparatorChar;
        }

        string full = Path.GetFullPath(Path.Combine(root, untrusted));

        if (!full.StartsWith(root, PathComparison))
        {
            throw new UnauthorizedAccessException(
                "The requested path is outside the allowed folder.");
        }

        return full;
    }

    /// <summary>For downloads by name: drops any folder part.
    /// </summary>
    public static string ResolveFileName(
        string baseFolder, string untrustedName) =>
        Resolve(baseFolder, Path.GetFileName(untrustedName));
}

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.