← All posts

Field notes / Security

It's Just a File, Right? Understanding File Upload Vulnerabilities

File uploads are everywhere.

Profile pictures.

PDF attachments.

Résumés.

Receipts.

Support tickets.

Import files.

Documents.

Videos.

Backups.

Applications routinely accept files from users and store or process them.

That sounds simple:

User
  ↓
Choose file
  ↓
Upload
  ↓
Server stores file

From a security perspective, however, an upload is something much more significant:

The application is accepting attacker-controlled content and introducing it into a trusted environment.

That creates several security decisions.

What kind of file is it?

How is that determined?

Where will it be stored?

What name will it receive?

Who can access it?

Will another application process it?

Can the web server execute it?

Can it overwrite something?

Can it contain active content?

Can it consume excessive resources?

The vulnerability is rarely just:

The application allows file uploads.

The problem is what the application allows an uploaded file to become.

The Basic Upload Flow

Consider a profile-picture feature.

The intended workflow is:

User
   ↓
avatar.jpg
   ↓
Application validates image
   ↓
Application stores image
   ↓
Web server serves image

The developer expects something like:

cat.jpg

But an attacker controls the input.

They may instead submit:

something.php

or:

something.jpg.php

or:

document.html

or a file whose name says one thing while its contents contain something completely different.

The application now has to determine whether the uploaded object is safe.

That turns out to be considerably harder than checking a filename.

The Filename Is User Input

Suppose an application accepts:

profile.jpg

and validates the upload using only the extension:

if filename.endswith(".jpg"):
    save_file(file)

The application has made an important assumption:

.jpg = JPEG image

But filenames are labels.

They do not determine what bytes are actually inside a file.

An attacker can rename something:

payload.txt

to:

payload.jpg

The contents do not magically become an image.

This gives us the first major principle of upload security:

A filename describes a file. It does not prove what the file is.

Extensions Are Useful, But Not Sufficient

File extensions still matter.

If an application expects profile images, there is little reason to accept:

.php
.jsp
.aspx
.sh
.exe

An extension allowlist can therefore reduce attack surface.

For example:

.jpg
.jpeg
.png

is better than trying to enumerate every extension that might be dangerous.

But even an allowlist does not prove that the contents are valid.

A file named:

photo.jpg

may not actually contain JPEG data.

Validation needs additional layers.

MIME Types

HTTP uploads commonly include a content type.

For example:

Content-Type: image/jpeg

An application might check that value:

if uploaded_file.content_type == "image/jpeg":
    save_file(uploaded_file)

That looks stronger than checking only the filename.

There is a problem.

In many upload scenarios, the client supplies this value.

An attacker can potentially send:

Content-Type: image/jpeg

regardless of what the file actually contains.

So this:

Content-Type: image/jpeg

means:

The client claims this is a JPEG

not necessarily:

The server proved this is a JPEG

Client-controlled metadata should never be treated as authoritative security evidence.

Content Inspection

The server can examine the file itself.

Many file formats contain recognizable structures or signatures.

A JPEG commonly begins with bytes associated with the JPEG format.

A PNG has its own signature.

A PDF has recognizable structure.

Libraries can inspect file contents and attempt to determine the actual type.

Conceptually:

Filename
   ↓
Extension check

Client MIME type
   ↓
Metadata check

File contents
   ↓
Server-side type detection

This provides stronger evidence.

But even content inspection is not the end of the problem.

Files can be complex.

Some formats can contain active content.

Some parsers interpret files differently.

Some files can satisfy more than one parser.

And some perfectly valid files can still be dangerous depending on how the application uses them.

Context Determines Whether a File Is Dangerous

Consider:

report.html

Stored as an attachment and downloaded with a safe content disposition, it may present relatively little risk.

Serve that same file directly from the application's origin:

https://example.com/uploads/report.html

and the browser may interpret it as active HTML.

Now uploaded content may execute in the security context of the application's domain.

The file did not change.

The execution context changed.

This is why file upload security cannot be reduced to a list of bad extensions.

A file becomes dangerous based partly on what systems do with it afterward.

The Worst Combination: Upload Plus Execution

One of the most serious upload scenarios occurs when:

Attacker uploads file
        ↓
File stored inside web-accessible directory
        ↓
Web server recognizes file as executable
        ↓
Attacker requests file
        ↓
Server executes attacker-controlled code

Imagine a server configured to execute PHP files inside:

/var/www/html/uploads/

If an attacker can successfully place:

shell.php

there, requesting:

/uploads/shell.php

may cause the web server to execute the file rather than return it as static content.

The security boundary has changed dramatically.

What began as:

Upload an avatar

can become:

Execute attacker-controlled server-side code

That is why storage location is just as important as validation.

Store Uploads Outside the Web Root

A strong design avoids placing untrusted uploads inside executable web directories.

Instead of:

/var/www/html/uploads/

consider storage outside the web root:

/srv/application-uploads/

Then files can be retrieved through controlled application logic:

Browser
   ↓
GET /files/12345
   ↓
Application
   ↓
Authorization check
   ↓
Read stored file
   ↓
Return as data

The web server never interprets the uploaded object as application code.

This creates an important architectural boundary:

APPLICATION CODE

        ≠

USER UPLOADS

Those two categories should not share an execution environment unnecessarily.

Never Trust the Original Filename

Users control filenames.

That introduces more problems than file type alone.

Suppose the application stores files using the submitted name:

destination = "/uploads/" + filename

Now the filename may influence the filesystem path.

A malicious filename could potentially attempt to escape the intended directory if path handling is unsafe.

Conceptually:

Expected:

/uploads/photo.jpg

Attacker-controlled:

/uploads/../../something

The file upload feature has now crossed into a path-handling problem.

Even without traversal, duplicate filenames can cause collisions:

invoice.pdf
invoice.pdf
invoice.pdf

Which user's file wins?

Does the application overwrite the existing file?

Can an attacker predict another user's filename?

Can they replace an existing resource?

A safer pattern is to generate server-side identifiers.

For example:

User filename:
quarterly-report.pdf

Stored filename:
7f4b1d62-39a8-4dc4-aaf7-9dbf88c82a17

The original filename can be retained as metadata when needed without using it directly as the filesystem path.

Overwriting Files Can Be Its Own Vulnerability

Imagine an upload feature that stores:

/uploads/<user-supplied-name>

without checking whether that file already exists.

An attacker may be able to replace:

logo.png

or another user's uploaded document.

If the upload location overlaps with application resources, the consequences can become considerably worse.

This creates another useful AppSec question:

What happens if the uploaded filename already exists?

Secure upload design should define that behavior explicitly rather than leaving it to filesystem defaults.

Double Extensions

Developers sometimes block dangerous extensions using logic such as:

if filename.endswith(".php"):
    reject()

That raises an obvious question:

What does the application do with:

avatar.php.jpg

or:

avatar.jpg.php

The answer depends on:

Validation logic
Web-server configuration
Filesystem behavior
Framework behavior

A security control that checks only whether a filename contains an expected substring can be particularly fragile.

For example:

if ".jpg" in filename:
    allow()

would accept:

avatar.jpg.php

This is why filename parsing should be explicit and predictable.

Case Sensitivity

Validation may reject:

.php

but behave differently for:

.PHP
.Php
.pHp

Whether this matters depends on the operating system, web server, framework, and validation implementation.

The broader lesson is not to memorize casing tricks.

It is to make validation canonical and deterministic.

Normalize what you are evaluating before applying security policy.

Polyglot Files

Some files can be constructed so that more than one parser considers them meaningful.

These are sometimes called polyglot files.

Conceptually:

One sequence of bytes
       ↓
Image parser → valid enough
       ↓
Another parser → meaningful content

This illustrates an important weakness in the assumption:

The image parser accepted it,
therefore it is safe.

Validation tells you something about a file.

It does not necessarily tell you everything another system might do with it.

That is another reason execution controls and storage architecture matter.

Image Processing Can Reduce Risk

For image uploads, applications can sometimes avoid storing the original object directly.

Instead:

Uploaded image
      ↓
Decode using image library
      ↓
Create new image representation
      ↓
Re-encode
      ↓
Store generated image

This changes the trust model.

Rather than asking:

Is this attacker-supplied file safe enough to keep?

the application creates a new file from successfully decoded image data.

This can eliminate some unwanted metadata or structures from the original upload.

It is not a universal solution.

Image-processing libraries themselves can contain vulnerabilities.

But transformation can be a valuable defense when appropriate.

File Processing Creates Another Attack Surface

Uploaded files are often passed to additional software.

For example:

Upload
  ↓
Virus scanner
  ↓
Image processor
  ↓
PDF parser
  ↓
Document converter
  ↓
Metadata extractor

Every parser becomes part of the attack surface.

A malformed file may not attack the application directly.

It may target the software that processes the upload.

This means secure upload design also requires:

Patched processing libraries
Resource limits
Sandboxing where appropriate
Timeouts
Isolation
Safe parser configuration

The upload endpoint is only the beginning of the file's lifecycle.

File Size Matters

Not every upload attack requires code execution.

Suppose an application allows arbitrary file sizes.

An attacker uploads:

10 GB
10 GB
10 GB
10 GB
...

Eventually:

Disk fills
     ↓
Application cannot write
     ↓
Logs fail
     ↓
Database or services may fail

The vulnerability is now an availability problem.

Applications should define reasonable limits for:

Individual file size
Total user storage
Request size
Processing time
Number of uploads

Security includes resource consumption.

Archive Files Add Complexity

Archives deserve special attention.

A ZIP file may look like one upload:

documents.zip

but extraction creates many filesystem operations.

Potential problems include:

Unexpected paths
Large decompressed size
Huge numbers of files
Nested archives
Resource exhaustion

A small compressed archive can potentially expand into a much larger amount of data.

This is sometimes called a ZIP bomb or decompression bomb.

Archive extraction therefore needs its own security policy.

The application should not assume:

Small upload = small extracted result

Access Control Still Applies

Suppose an application securely validates and stores PDF files.

There can still be a serious vulnerability if every uploaded document is available at:

/uploads/1.pdf
/uploads/2.pdf
/uploads/3.pdf

and no authorization check occurs.

The upload mechanism itself may be safe.

The retrieval mechanism is not.

This becomes an access-control problem:

User A uploads private document
        ↓
Predictable identifier
        ↓
User B requests document
        ↓
No authorization check
        ↓
Private document disclosed

File upload security includes the entire lifecycle:

Upload
  ↓
Validation
  ↓
Storage
  ↓
Processing
  ↓
Retrieval
  ↓
Deletion

Every stage can introduce vulnerabilities.

Public Versus Private Files

Applications should explicitly decide whether uploaded content is:

Public
Authenticated
User-specific
Role-restricted
Temporary
Internal-only

Do not let the storage location accidentally make that decision.

Putting a file under:

/public/uploads/

is effectively an access-control decision.

Architecture is policy, whether the developer intended it to be or not.

Content-Disposition Matters

When files are returned to users, HTTP response headers influence how browsers handle them.

For files that should be downloaded rather than rendered, applications can use an appropriate Content-Disposition, such as:

Content-Disposition: attachment

This helps prevent browsers from interpreting certain uploaded content directly within the application's origin.

Likewise, returning an appropriate Content-Type matters.

These controls should complement proper validation and storage architecture, not replace them.

Separate Uploads From the Application Origin

For some applications, uploaded content can be served from a separate domain or storage service.

Conceptually:

Application:

app.example.com

User uploads:

uploads.exampleusercontent.com

Now even if uploaded content contains something a browser interprets actively, it does not automatically execute under:

app.example.com

with the same origin and security context as the main application.

This can substantially reduce the consequences of content-handling mistakes.

Malware Is Another Problem

A file may be perfectly valid according to its format and still be malicious.

For example:

Valid Office document
        ↓
Malicious content

or:

Valid archive
        ↓
Malware inside

If uploaded files are redistributed to other users, the application can become a malware delivery mechanism.

Depending on the use case, upload pipelines may therefore include malware scanning.

Again, the important concept is:

Valid file does not mean safe file.

Validity and security are different properties.

Testing File Upload Functionality

A disciplined file-upload assessment begins by understanding the intended behavior.

Start with a legitimate file.

Observe:

Accepted extensions
Maximum size
Request structure
Content-Type
Server response
Generated filename
Storage location
Retrieval URL
Authentication requirements

Then begin changing one property at a time.

For example:

Filename
Extension
MIME type
Actual content
Size
Metadata

Observe what the application validates and what it trusts.

A useful testing workflow is:

Baseline valid upload
        ↓
Understand expected behavior
        ↓
Change one property
        ↓
Observe validation
        ↓
Determine storage behavior
        ↓
Determine retrieval behavior
        ↓
Determine processing behavior

This is more informative than simply throwing a collection of malicious filenames at the endpoint.

The goal is to understand the application's trust decisions.

Questions Worth Asking

When evaluating an upload feature, ask:

Each answer reveals another part of the trust boundary.

Remediation

There is no single magical file-upload security check.

Strong upload security uses multiple controls.

Allow Only Required File Types

Use an explicit allowlist based on business requirements.

If users only need JPEG and PNG images, do not accept arbitrary formats.

Validate Server-Side

Do not rely on browser-side validation.

Attackers control their HTTP requests.

Inspect File Contents

Use appropriate server-side libraries to verify that files match expected formats.

Do not rely exclusively on filenames or client-provided MIME types.

Generate Filenames Server-Side

Avoid using attacker-controlled filenames directly as filesystem paths.

Store Uploads Outside Executable Directories

Do not allow user-controlled content to become server-side executable code.

Separate Uploaded Content

Where appropriate, serve untrusted files from isolated storage or a separate origin.

Enforce Size and Resource Limits

Limit upload size, processing time, storage consumption, and archive extraction.

Apply Authorization During Retrieval

Possessing or guessing a file URL should not automatically grant access to private content.

Secure File Processing

Keep parsers and conversion libraries patched and isolate risky processing where appropriate.

Return Safe Response Headers

Control whether uploaded content is rendered or downloaded.

Monitor Upload Activity

Logging and monitoring can help identify unusual upload volume, repeated validation failures, or suspicious file types.

Defense in Depth

The strongest upload architecture assumes individual controls can fail.

Imagine an attacker bypasses file-type validation.

The next control should still prevent execution:

Validation bypass
      ↓
Random server-generated filename
      ↓
Storage outside web root
      ↓
Non-executable storage
      ↓
Separate origin
      ↓
Controlled retrieval

No single mistake immediately becomes remote code execution.

That is what defense in depth looks like.

Contrast that with:

Weak extension check
      ↓
Original filename retained
      ↓
Stored under web root
      ↓
Executable directory
      ↓
Publicly accessible

Every design decision amplifies the previous mistake.

Security architecture determines whether a validation bug becomes a minor defect or a complete server compromise.

The Bigger AppSec Lesson

File upload vulnerabilities are often introduced with a simple challenge:

Upload a web shell.

That demonstrates one particularly serious outcome.

But it does not capture the larger lesson.

The important transition occurs much earlier:

External user
      ↓
Attacker-controlled bytes
      ↓
Trusted application environment

Once those bytes cross that boundary, the application becomes responsible for everything that happens next.

It must decide:

What is this?

Where can it go?

Who can access it?

What can process it?

Can it execute?

How much space can it consume?

What happens when someone retrieves it?

A secure upload feature does not rely on correctly answering only one of those questions.

It builds layers so that one incorrect answer does not become catastrophic.

That is the larger application-security principle behind file uploads:

Never confuse accepting untrusted content with trusting untrusted content.

The upload is only the beginning.

What the system does with the file afterward determines the vulnerability.

← Back to the blog