📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your ASP.NET Core API lets customers upload documents and images. What can go wrong with file uploads, and how do you build the endpoint securely? Cover size limits, validating content rather than trusting the extension or Content-Type, file names, storage outside the web root in Blob Storage with SAS, and malware scanning.

Secure file upload in ASP.NET Core 10: request size limits, streaming, extension allow-lists plus magic-number checks, generated storage names, private Blob containers with short-lived user-delegation SAS, quarantine and malware scanning, and safe download headers.

Mid-Level Security Intermediate aspnet-core azure-blob-storage file-upload malware-scanning owasp security

🎯 Key points

  • Threats: DoS via huge or many files, stored XSS via HTML/SVG, web shells if stored under the web root, path traversal through file names, malware delivered to staff, zip bombs, parser exploits
  • One layered size strategy: Kestrel MaxRequestBodySize as the global ceiling, per-endpoint RequestSizeLimit/RequestFormLimits for the real limit, plus rate limiting, per-user quotas and a WAF (Azure Front Door / Application Gateway) request-size rule at the edge
  • Never trust the client: extension allow-list AND file signature (magic number) check; Content-Type header and file name are attacker-controlled
  • Generate the stored name (GUID); keep the original name only as sanitised metadata; never Path.Combine user input
  • Store outside the web root: private Blob container, stream the upload, serve downloads via short-lived user-delegation SAS or an authorised endpoint
  • Quarantine then scan: Defender for Storage malware scanning; clean files are promoted, malicious ones are deleted or moved to an isolated container, the upload is marked Rejected and security is alerted
  • Safe serving: Content-Disposition: attachment, X-Content-Type-Options: nosniff, correct Content-Type, separate user-content domain, and a CSP on the app so any rendered content can't run script
  • Log and monitor uploads (user, size, type, scan verdict) without logging contents; alert on spikes, repeated rejections and malware verdicts; antiforgery for cookie-authenticated form uploads

⏱ 30-second answer

File upload is one of the riskiest features: attackers use it for DoS (huge files), stored XSS (HTML or SVG served back), web shells (files under the web root), path traversal through file names, and malware delivered to staff. I set size limits at Kestrel and per endpoint, then stream the body rather than buffering it. I validate with an extension allow-list plus a magic-number check, because the extension and Content-Type are attacker-controlled. The stored name is a generated GUID; the original name is only sanitised metadata. Files go to a private Blob container, first into quarantine, are malware-scanned (Defender for Storage), and only then promoted. Downloads use a short-lived user-delegation SAS or an authorised endpoint with Content-Disposition: attachment and nosniff. The trade-off is latency: scanning makes upload asynchronous, so the UI must show a "processing" state.

🗣 Full answer (senior)

How I would answer this in an interview

"I treat every uploaded file as hostile. The risks are denial of service from very large or very many files, stored XSS if we ever serve an HTML or SVG file back from our own origin, remote code execution if a file lands somewhere the web server executes it, path traversal if the client's file name reaches Path.Combine, and malware that a staff member later opens. Then there are parser bugs: image libraries and PDF parsers have had plenty of CVEs, so processing untrusted files is itself risky.

In ASP.NET Core I put limits in layers: Kestrel's MaxRequestBodySize, a per-endpoint RequestSizeLimit and form limits, plus rate limiting and per-user quotas. I stream the multipart body straight to Blob Storage with MultipartReader or IFormFile.OpenReadStream() instead of reading it into a byte array. I validate against an allow-list of extensions and check the first bytes against the expected signature - %PDF-, the PNG header, FF D8 FF for JPEG - because the Content-Type header and the file name are just strings the attacker chose. The blob name is a GUID; the original name goes into metadata after sanitising. Uploads land in a private quarantine container, Defender for Storage malware scanning tags them, and an Event Grid-triggered function moves clean files to the real container and deletes malicious ones.

For downloads I never make containers public. Either the API checks authorisation and streams the file with Content-Disposition: attachment and X-Content-Type-Options: nosniff, or it hands out a user-delegation SAS valid for a few minutes for that one blob. The mistake I see is checking only the extension and saving to wwwroot/uploads, which turns an upload form into a web shell or an XSS host. The senior point is that uploads are a pipeline - limit, validate, quarantine, scan, promote, serve safely - not a single SaveAs call."


Threats and controls

Threat Example Control
DoS 5 GB upload, thousands of small uploads, zip bomb Kestrel and endpoint size limits, streaming, rate limiting, quotas, don't decompress untrusted archives without limits
Stored XSS invoice.html or SVG with script served inline Allow-list, Content-Disposition: attachment, nosniff, separate user-content domain, CSP
Web shell / RCE shell.aspx saved under the web root Store outside the web root (Blob), never execute uploads
Path traversal file name ..\..\appsettings.json Generated names, never use client file names in paths
Malware Macro-laden document opened by staff Quarantine and scan before promotion
Parser exploits Malformed image triggers a library CVE Patch libraries, process in an isolated worker, re-encode images
IDOR on download /files/123 fetches another user's file Authorise per file; unguessable ids are not authorisation
CSRF Cookie-authenticated upload form Antiforgery tokens (on by default for form-bound Minimal API endpoints in .NET 8+)

Validation: what you can and can't trust

Signal Trust Use
IFormFile.FileName None Display only, after sanitising
IFormFile.ContentType None Ignore for security decisions
Extension Low Allow-list as a first filter
Magic number (first bytes) Medium Confirms the format family
Full parse / re-encode Higher Images: re-encode to strip payloads; PDFs: sanitise if feasible
Malware scan Higher Required before anyone opens the file

Production example

[A claims portal] previously saved uploads to wwwroot/uploads with the original file name. After moving to a streamed upload into a quarantine container with Defender for Storage scanning, memory per upload dropped from [~the file size] to [~80 KB of buffers], and in the first [quarter] the scanner blocked [N] malicious files that would previously have reached claims assessors.

🔍 What the interviewer is checking

Checks whether the candidate sees file upload as a multi-threat feature and knows the concrete ASP.NET Core and Azure controls.

Green flags

  • Lists DoS, XSS, web shells, traversal and malware as distinct threats.
  • Knows Kestrel and per-endpoint size limits and streaming.
  • Validates by signature, not Content-Type; generates storage names.
  • Private storage, quarantine and scanning, short-lived SAS.
  • Safe download headers and per-file authorisation.

Red flags

  • "Check the extension and save it to wwwroot."
  • Public Blob containers.
  • No mention of size limits or scanning.

📚 Learn in depth

1. How ASP.NET Core receives a file

 client --multipart/form-data--> Kestrel (MaxRequestBodySize, default ~28.6 MB)
                                    |
                                    v
                          endpoint metadata (RequestSizeLimit, form limits)
                                    |
          +-------------------------+-------------------------+
          | IFormFile binding                                 | MultipartReader (streaming)
          | form read into memory up to 64 KB,                | sections read one by one,
          | then buffered to temp files on disk               | you copy the stream directly
          | (FormOptions.MultipartBodyLengthLimit 128 MB)     | to Blob Storage
          v                                                   v
     simple, fine for small files                      needed for large files, low memory

Key settings:

  • KestrelServerOptions.Limits.MaxRequestBodySize - global cap (default 30,000,000 bytes).
  • [RequestSizeLimit], [DisableRequestSizeLimit], or IHttpMaxRequestBodySizeFeature - per endpoint.
  • FormOptions (MultipartBodyLengthLimit, ValueCountLimit, MultipartHeadersLengthLimit) - form parsing limits, settable per endpoint with [RequestFormLimits].
  • IIS in-process hosting also has maxAllowedContentLength in web.config.

2. File signatures

Format Signature (hex) ASCII
PDF 25 50 44 46 2D %PDF-
PNG 89 50 4E 47 0D 0A 1A 0A .PNG....
JPEG FF D8 FF
ZIP / DOCX / XLSX 50 4B 03 04 PK..
GIF 47 49 46 38 GIF8

Signatures confirm the format family, not safety: a valid PDF can contain malicious JavaScript, a DOCX can contain macros (DOCM masquerading), and polyglot files are valid in two formats. That's why scanning and safe serving still matter.

3. Storage design on Azure

  API --stream--> [quarantine container, private]
                      |  Defender for Storage on-upload malware scanning
                      |  -> blob index tag: Malware Scanning scan results
                      v
                 Event Grid (scan result event)
                      |
                      v
                 Function: clean? copy to [documents] + delete original
                           malicious? delete or move to [infected], alert
                      |
  Client <--user-delegation SAS (5 min, read, one blob)-- API (after authorisation)
  • User-delegation SAS is signed with a key obtained via Entra ID, scoped to one blob, short-lived, and revocable; prefer it over account-key SAS.
  • Disable public blob access and shared-key access on the account.
  • Set Content-Disposition and Content-Type on the blob (or as SAS response overrides) so browsers download rather than render.
  • A separate domain for user content (e.g. usercontent.example.com.au) isolates any rendering from your app's cookies and origin.

4. Processing untrusted files safely

  • Images: decode and re-encode with a maintained library (ImageSharp, SkiaSharp), stripping metadata (EXIF can include GPS location - a privacy issue too). Enforce maximum pixel dimensions to prevent decompression bombs.
  • Archives: cap entry count, total uncompressed size and compression ratio; reject entries with .. or absolute paths (zip slip).
  • Office documents: reject macro-enabled types if not needed.
  • Run processing in a separate worker with minimal permissions, so a parser exploit doesn't reach the API's identity.

5. Australian context

Uploaded identity documents and medical records are personal and often sensitive information: APP 11 applies, they're prime NDB material, and they should be retained only as long as needed. Remove EXIF location from photos to avoid collecting information you didn't intend to. For government systems, the ISM includes controls on content filtering and malware scanning of files from external sources.

Try it yourself

  1. Upload a 100 MB file to an endpoint with default settings and observe the 413 response; then raise the limit for that endpoint only.
  2. Measure memory with dotnet-counters monitor while uploading via IFormFile versus streaming with MultipartReader.
  3. Rename an .html file to .png and confirm your magic-number check rejects it.
  4. Enable Defender for Storage malware scanning on a test account and upload the EICAR test file; watch the blob index tag and the Event Grid event.
  5. Generate a user-delegation SAS valid for 5 minutes and confirm it fails after expiry.

💻 Code

Vulnerable: saves under the web root with the client's file name and trusts the Content-Type:

app.MapPost("/upload", async (IFormFile file, IWebHostEnvironment env) =>
{
    if (file.ContentType != "application/pdf") return Results.BadRequest(); // attacker sets this header
    var path = Path.Combine(env.WebRootPath, "uploads", file.FileName);     // ..\..\ or shell.aspx
    await using var fs = File.Create(path);
    await file.CopyToAsync(fs);
    return Results.Ok($"/uploads/{file.FileName}");                         // served inline from our origin
});

Exploit in one line: upload x.html with Content-Type: application/pdf containing a script, then send staff the /uploads/x.html link (stored XSS), or use a traversal file name to overwrite files.

Fixed: limits, allow-list plus signature check, generated name, private quarantine container:

namespace Claims.Api;

public static class UploadEndpoints
{
    private static readonly Dictionary<string, byte[][]> Allowed = new(StringComparer.OrdinalIgnoreCase)
    {
        [".pdf"] = ["%PDF-"u8.ToArray()],
        [".png"] = [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]],
        [".jpg"] = [[0xFF, 0xD8, 0xFF]],
        [".jpeg"] = [[0xFF, 0xD8, 0xFF]],
    };

    public static void Map(WebApplication app)
    {
        app.MapPost("/claims/{claimId:guid}/documents", UploadAsync)
           .RequireAuthorization("ClaimOwner")
           .RequireRateLimiting("uploads")
           .WithMetadata(new RequestSizeLimitAttribute(10 * 1024 * 1024)); // 10 MB for this endpoint only
    }

    private static async Task<IResult> UploadAsync(
        Guid claimId, IFormFile file, BlobContainerClient quarantine, CancellationToken ct)
    {
        var ext = Path.GetExtension(file.FileName);
        if (!Allowed.TryGetValue(ext, out var signatures))
            return Results.Problem("File type not allowed.", statusCode: 415);

        await using var input = file.OpenReadStream();
        var header = new byte[8];
        var read = await input.ReadAtLeastAsync(header, header.Length, throwOnEndOfStream: false, ct);
        if (!signatures.Any(s => read >= s.Length && header.AsSpan(0, s.Length).SequenceEqual(s)))
            return Results.Problem("File content does not match its type.", statusCode: 415);
        input.Position = 0; // IFormFile streams are seekable (buffered); use MultipartReader for very large files

        var blobName = $"{claimId}/{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; // never the client's name
        var blob = quarantine.GetBlobClient(blobName);
        await blob.UploadAsync(input, new BlobUploadOptions
        {
            HttpHeaders = new BlobHttpHeaders
            {
                ContentType = ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase) ? "application/pdf" : $"image/{ext.TrimStart('.').ToLowerInvariant().Replace("jpg", "jpeg")}",
                ContentDisposition = "attachment"
            },
            Metadata = new Dictionary<string, string>
            {
                ["originalName"] = Uri.EscapeDataString(Path.GetFileName(file.FileName)) // display only
            }
        }, ct);

        // Status stays 'Scanning' until the Defender scan result event promotes the blob.
        return Results.Accepted(value: new { documentId = blobName, status = "Scanning" });
    }
}

Issuing a short-lived, single-blob download link after authorisation:

public sealed class DownloadLinks(BlobServiceClient service)
{
    public async Task<Uri> CreateAsync(BlobClient blob, CancellationToken ct)
    {
        var now = DateTimeOffset.UtcNow;
        var key = await service.GetUserDelegationKeyAsync(now.AddMinutes(-1), now.AddMinutes(10), ct);
        var sas = new BlobSasBuilder(BlobSasPermissions.Read, now.AddMinutes(5))
        {
            BlobContainerName = blob.BlobContainerName,
            BlobName = blob.Name,
            Resource = "b",
            ContentDisposition = "attachment"
        };
        return new BlobUriBuilder(blob.Uri) { Sas = sas.ToSasQueryParameters(key.Value, service.AccountName) }.ToUri();
    }
}

⚠ Common mistakes

  • Mistake: Trusting IFormFile.ContentType or the extension alone. Why it is wrong: Both are attacker-controlled strings. Instead: Use an extension allow-list plus a file-signature check, then scan.
  • Mistake: Saving uploads under wwwroot. Why it is wrong: Files become directly reachable and may be served inline or, with misconfiguration, executed. Instead: Store in a private Blob container and serve through authorisation or short-lived SAS.
  • Mistake: Using the client's file name in the storage path. Why it is wrong: Enables path traversal, overwrites and collisions. Instead: Generate a GUID name; keep the original only as sanitised metadata.
  • Mistake: Reading the whole file into memory with CopyToAsync(MemoryStream) or ToArray(). Why it is wrong: A few concurrent large uploads exhaust memory and land on the LOH. Instead: Stream to storage and set size limits.
  • Mistake: Raising MaxRequestBodySize globally for one upload endpoint. Why it is wrong: Every endpoint now accepts huge bodies, widening DoS exposure. Instead: Raise the limit per endpoint.
  • Mistake: Making the container public so the front end can show files. Why it is wrong: Anyone with or guessing a URL reads other customers' documents. Instead: User-delegation SAS per blob, minutes long, after an authorisation check.
  • Mistake: Letting users open files before scanning completes. Why it is wrong: Malware reaches staff or other users. Instead: Quarantine, scan, then promote; show a processing state.
  • Mistake: Serving user content inline from the app's origin. Why it is wrong: HTML and SVG run script with your cookies' origin (stored XSS). Instead: Content-Disposition: attachment, nosniff, and ideally a separate user-content domain.

🏛 Senior insight: trade-offs

A senior engineer designs upload as an asynchronous pipeline with explicit states (Uploaded -> Scanning -> Clean / Rejected) because that's what makes scanning, image re-encoding and retention possible without blocking requests. They also push most of the heavy lifting to managed services: Blob Storage for durable, private storage, Defender for Storage for scanning, and SAS for delegated downloads, so the API process never holds large files in memory or runs risky parsers.

Trade-offs to name: scanning adds seconds to minutes of latency and costs per GB scanned; direct-to-Blob uploads with a write-only SAS remove load from the API but move validation after the upload, so the quarantine step becomes mandatory. Measure: upload p95 latency, memory per upload, scan latency, and blocked files per month.

Approach When it fits Cost When not to
Upload through the API (IFormFile) Small files (< 10 MB), simple flows API bandwidth and memory Large media files
Streamed through the API (MultipartReader) Larger files needing server-side checks before storage More code Very high volumes
Direct to Blob with write-only SAS Large files, high volume Validation only after upload; quarantine mandatory When you must reject before storing
Defender for Storage malware scanning Any user-supplied files on Azure Per-GB scanning cost Files never opened by people or other systems (rare)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions not using the client's file name in paths. Why: Checks the candidate understands path traversal in depth, which upload file names can trigger.
    How to answer

    It is a path traversal vulnerability. file=../../../etc/passwd resolves outside the reports folder, and file=/etc/passwd is worse: Path.Combine discards the base path when the second argument is rooted. The endpoint also has no authorisation and leaks whether files exist.

    Fix: do not let users name files. Map an ID to a stored path (database), or if names are required, take only Path.GetFileName(file), build the path, Path.GetFullPath it and check it starts with the root plus a separator, using the platform's case rules. Serve through PhysicalFileProvider or Results.File with the checked path, and add authorisation.

  2. When: Candidate mentions request size limits. Why: Checks broader payload limits beyond files: JSON depth, form value counts, request body size.
    How to answer

    Set limits at every layer and fail fast with a clear status. Lower Kestrel's MaxRequestBodySize (default about 28.6 MB) globally, and per endpoint with [RequestSizeLimit]; requests over the limit get 413 Payload Too Large. Set FormOptions limits for multipart. Keep System.Text.Json's MaxDepth (64 by default; lower it for shallow contracts), so deeply nested JSON fails with 400. Validate collection counts in FluentValidation or data annotations and return a ValidationProblem. Stream large uploads instead of buffering, and add rate limiting (AddRateLimiter) so repeated large requests can't exhaust CPU and memory (a denial-of-service vector).

  3. When: Candidate mentions serving files inline or SVG risks. Why: Checks understanding of stored XSS, which uploaded HTML or SVG enables.
    How to answer

    XSS is when attacker-controlled input is rendered as script in your page, so it runs in your origin with the victim's session: it can read the DOM, call your API as the user and steal tokens kept in localStorage. Stored XSS is saved and served to other users; reflected echoes request input back; DOM-based happens entirely in client-side JavaScript (innerHTML, location.hash).

    Razor's @ HTML-encodes by default, which stops most of it. The gaps are the escape hatches (Html.Raw, HtmlString, React's dangerouslySetInnerHTML, Blazor's MarkupString) and wrong contexts: HTML encoding doesn't make a value safe inside a <script> block or an href="javascript:...". Rich text needs an allow-list sanitiser. A CSP with nonces is the safety net, not the fix.

🛠 Real-world problems: how you handle them

Stored XSS through uploaded SVGs in a claims portal
Situation
[A claims portal] let customers upload supporting images, saved to `wwwroot/uploads` and shown to [~150] claims assessors in the internal UI on the same origin as the assessor app.
Signals
A pen tester reported that an uploaded SVG containing script executed in an assessor's browser session when the claim was opened, with access to the assessor's antiforgery token and session context.
Investigation
Reproduced with a harmless `alert` SVG in a test environment, confirmed the upload check only compared `ContentType` against a list that included `image/svg+xml`, reviewed IIS logs for previously uploaded SVGs, and checked the assessor app's cookies and CSP (none).
Resolution
Immediate: removed SVG from the allow-list, set `Content-Disposition: attachment` and `nosniff` on the uploads path, and moved existing uploads out of the web root. Long term: rebuilt the endpoint to stream into a private quarantine container with signature checks, Defender for Storage scanning and short-lived SAS downloads from a separate user-content domain, and added a CSP to the assessor app.
Prevention
Integration tests uploading HTML, SVG and mismatched-signature files, a security checklist item for any upload feature, OWASP ZAP in the release pipeline, and Defender for Storage alerts routed to the security channel.

How to tell it (STAR)

**S:** Our claims portal saved customer uploads under the web root, and assessors viewed them on the same origin. **T:** A pen test found stored XSS through uploaded SVGs, and I [owned] the fix. **A:** I closed it the same day by blocking SVG and forcing downloads, then rebuilt uploads as a pipeline: size limits, signature checks, generated names, a private quarantine container with malware scanning, and five-minute SAS links from a separate domain. **R:** The retest found [no issues], upload memory dropped [to a few KB of buffers per upload], and the scanner has since blocked [N] malicious files before any assessor opened them.

More in Senior Security Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me