IC Improve Code Recipes

Recipe 8.4 · C#

Validating Uploaded Files

Problem

A user uploads a file, and the code checks that the name ends in .pdf. That check says nothing about the content. A renamed executable passes, and so does a 2 GB file that fills the disk. The original file name is then used to save the file, which brings its own trouble: names with ..\, reserved device names, or a name that overwrites another user's upload.

The way it's often written

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

C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    string ext = Path.GetExtension(fu.FileName).ToLower();
    if (ext == ".pdf" || ext == ".jpg" || ext == ".xls")
    {
        fu.SaveAs(Server.MapPath("~/uploads/") + fu.FileName);
    }
}

The extension is the only check, the size limit is whatever the web server allows, and the client-supplied name decides where the bytes land on disk, inside the web root.

The improved recipe

The validator below checks four things: the extension is on an allow-list, the size is within a limit, the first bytes match the file type's signature, and the stored name is generated by the server. It works on a Stream and a name, so it has no dependency on ASP.NET Core and is easy to test.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Validation;

public sealed record UploadCheck(
    bool IsValid, string? Error, string? StoredFileName)
{
    public static UploadCheck Fail(string error) =>
        new(false, error, null);
}

public sealed class UploadValidator
{
    private const int TextSampleBytes = 8192;

    // Leading "magic" bytes per extension. Empty means text.
    private static readonly Dictionary<string, byte[][]>
        Signatures = new(StringComparer.OrdinalIgnoreCase)
        {
            [".pdf"] = [[0x25, 0x50, 0x44, 0x46, 0x2D]],
            [".png"] = [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A,
                         0x1A, 0x0A]],
            [".jpg"] = [[0xFF, 0xD8, 0xFF]],
            [".jpeg"] = [[0xFF, 0xD8, 0xFF]],
            [".xlsx"] = [[0x50, 0x4B, 0x03, 0x04]],
            [".docx"] = [[0x50, 0x4B, 0x03, 0x04]],
            [".csv"] = [],
            [".txt"] = [],
        };

    private readonly long _maxBytes;
    private readonly HashSet<string> _allowed;

    public UploadValidator(
        long maxBytes, IEnumerable<string> allowedExtensions)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxBytes);
        ArgumentNullException.ThrowIfNull(allowedExtensions);
        _maxBytes = maxBytes;
        _allowed = new HashSet<string>(
            allowedExtensions, StringComparer.OrdinalIgnoreCase);

        var unknown = _allowed.Where(e => !Signatures.ContainsKey(e));
        if (unknown.Any())
        {
            throw new ArgumentException(
                "No signature known for: " + string.Join(", ", unknown),
                nameof(allowedExtensions));
        }
    }

    public async Task<UploadCheck> ValidateAsync(
        string? clientFileName, Stream content,
        CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(content);

        string ext = Path.GetExtension(clientFileName ?? "");
        if (ext.Length == 0 || !_allowed.Contains(ext))
        {
            return UploadCheck.Fail("This file type is not allowed.");
        }

        if (content.CanSeek && content.Length > _maxBytes)
        {
            return UploadCheck.Fail("The file is too large.");
        }

        if (content.CanSeek && content.Length == 0)
        {
            return UploadCheck.Fail("The file is empty.");
        }

        byte[] sample = new byte[TextSampleBytes];
        int read = await content.ReadAtLeastAsync(
            sample, sample.Length, throwOnEndOfStream: false, ct);
        if (content.CanSeek)
        {
            content.Position = 0;
        }

        if (!MatchesType(ext, sample.AsSpan(0, read)))
        {
            return UploadCheck.Fail(
                "The file content does not match its type.");
        }

        string stored =
            $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}";
        return new UploadCheck(true, null, stored);
    }

    private static bool MatchesType(
        string ext, ReadOnlySpan<byte> head)
    {
        byte[][] signatures = Signatures[ext];
        if (signatures.Length == 0)
        {
            // Text: non-empty, and no NUL bytes in the sample.
            return !head.IsEmpty && !head.Contains((byte)0);
        }
        foreach (byte[] signature in signatures)
        {
            if (head.StartsWith(signature))
            {
                return true;
            }
        }
        return false;
    }
}

A usage snippet for an ASP.NET Core minimal API endpoint, not a complete program:

C#
app.MapPost("/documents", async (IFormFile file,
    UploadValidator validator, CancellationToken ct) =>
{
    await using var stream = file.OpenReadStream();
    var check = await validator.ValidateAsync(
        file.FileName, stream, ct);
    if (!check.IsValid)
    {
        return Results.BadRequest(check.Error);
    }
    // Save under check.StoredFileName (see Recipe 10.1).
    return Results.Ok(check.StoredFileName);
}).DisableAntiforgery();

How it works

The extension check is an allow-list, never a deny-list. The constructor refuses any extension it has no signature for, so nobody can add .exe to configuration and have it pass silently.

The size check uses Stream.Length when the stream can seek, which is true for IFormFile.OpenReadStream(). Keep the server-side request limit as well (FormOptions.MultipartBodyLengthLimit and Kestrel's MaxRequestBodySize), because by the time your code runs, the body has been buffered.

The signature check reads up to 8 KB with ReadAtLeastAsync, which, unlike a single ReadAsync, keeps reading until it has the bytes or reaches the end. Binary types must start with their known magic bytes: %PDF- for PDF, the eight-byte PNG header, FF D8 FF for JPEG, and PK plus two bytes for the zip container that .xlsx and .docx use. Text types must not contain a zero byte in the sample, which rejects most binaries renamed to .csv.

The stored name is a new GUID plus the lowercased extension. The client's file name is kept only as display data, stored in your database next to the GUID. That single decision removes a whole class of overwrite and traversal bugs.

Variations and pitfalls

  • Signatures are a filter, not a guarantee. Every .xlsx starts with PK, and so does every zip file. If you go on to open the file, use a library that fails cleanly on malformed input (Recipe 11.3 covers importing Excel safely), and scan uploads with your antivirus product when the risk warrants it.
  • Store outside the web root. Save uploads to a folder or blob container the web server does not serve directly, and stream them back through an endpoint that sets Content-Disposition: attachment.
  • Path checks belong with path code. If you must combine a user-influenced name with a folder, use the safe path recipe in Chapter 10, Recipe 10.1, which rejects traversal outright.
  • Images can carry surprises. If you display user images, consider re-encoding them with an image library. That strips metadata, including GPS coordinates from phone photos.
  • Don't trust ContentType. The browser sets it from the extension. It is a hint for display, not evidence.