Unsafe file uploads

Unsafe file uploads in C#

Description

Returning an uploaded file as text/html tells the browser to interpret its contents as a web page.

Potential impact

Scripts in that file may run in the visitor’s browser, causing stored XSS. A public download can also distribute malicious files.

Remediation

Limit size and allowed extensions, check the actual content against the expected MIME type, and scan for malware. Store files outside the web root. Serve verified plain text as text/plain.

Examples

Before

csharp
using Microsoft.AspNetCore.Mvc;

public sealed class UploadController : Controller
{
    public IActionResult View(string id)
    {
        var fileBytes = System.IO.File.ReadAllBytes("/tmp/uploads/" + id);
        return File(fileBytes, "text/html");
    }
}

After

csharp
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;

public sealed class UploadController : Controller
{
    public async Task<IActionResult> Upload([FromForm] IFormFile file)
    {
        if (file.Length is <= 0 or > 1_048_576) return BadRequest();
        if (!string.Equals(
                Path.GetExtension(file.FileName), ".txt",
                StringComparison.OrdinalIgnoreCase)) return BadRequest();

        // Only the service must be able to write to this path and its parent directories.
        var uploadRoot = Path.GetFullPath("/var/lib/app/uploads");
        Directory.CreateDirectory(uploadRoot);
        var storedName = $"{Guid.NewGuid():N}.txt";
        var destination = Path.Combine(uploadRoot, storedName);
        await using var output = new FileStream(
            destination, FileMode.CreateNew, FileAccess.Write, FileShare.None);
        await file.CopyToAsync(output);
        return Accepted(new { id = storedName });
    }
}

The upload handler accepts nonempty .txt files up to 1 MiB and creates a new file under a server-generated name. It identifies the format by extension only. Implement content checks and the download response separately.

References