Skip to content
RCE Write-up Advanced

I Found a Tiny Filename Bypass That Broke a “Safe” Loader — and Earned $ $$$

A model-loading API validated shard filenames with a string suffix check but later determined the file type with a path library's suffix property, and the two disagreed on a filename consisting only of the extension. An attacker-controlled checkpoint index could therefore route a malicious shard into the generic PyTorch loader with weights_only disabled, potentially allowing unsafe pickle deserialisation and code execution.

Mohamed Mekawy Follow

Published on medium.com

Cybersecurity

Mohamed Mekawy, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

## Context

The target was an application that exposed a model-loading API. The API had a safety option enabled by default:

```
safe=True
```

The intended behaviour was simple: accept Safetensors files and use the safe loading path. The dangerous alternative is loading arbitrary Python pickle data. The researcher was not looking for a way to exploit `torch.load()` itself, but for a way to make the program think it was loading something safe when it was not.

The bug was caused by a tiny inconsistency in filename parsing. One part of the application considered a file named:

```
.safetensors
```

to be a valid Safetensors file. Another part considered the exact same filename to have no extension at all. This happened inside a security-sensitive loading path, and the result was a path from an attacker-controlled checkpoint to:

```
torch.load(..., weights_only=False)
```

The report was accepted, rated Medium, rewarded with a bounty, and fixed.

## Setup

The report does not describe accounts, roles, tools or versions. The work was done by tracing the filename from validation all the way to the final loader, and by building a minimal sharded checkpoint to test the path.

## Finding it

The researcher started with a question that sounds almost stupid:

> "What if I give it a really weird filename?"


{{media:0}}


The sharded checkpoint logic used a check similar to:

```
shard_file.endswith(".safetensors")
```

For example:

```
"model-00001-of-00002.safetensors".endswith(".safetensors")
```

returns:

```
True
```

Nothing interesting there. Then the researcher tried edge cases. One filename caught their attention:

```
.safetensors
```

And:

```
".safetensors".endswith(".safetensors")
```

returns:

```
True
```

The result was not surprising. What mattered was the next question: does the next stage interpret this filename the same way?

Later in the loading process, the code used:

```
Path(shard_file).suffix
```

For a normal filename:

```
Path("model.safetensors").suffix
```

we get:

```
.safetensors
```

But for:

```
Path(".safetensors").suffix
```

we get:

The same filename was now being interpreted differently:

```
┌──────────────────────────────────────────────┐│ Filename: .safetensors                       │├──────────────────────────────────────────────┤│ endswith(".safetensors")  → TRUE �
          ││ Path(...).suffix            → "" ❌           │└──────────────────────────────────────────────┘
```

A parser mismatch is only interesting from a security perspective if it changes something important, so the researcher followed the execution path. The first check was part of the sharded checkpoint validation. The second check influenced which loader would actually process the file. Because `.safetensors` produced an empty suffix with `Path(...).suffix`, the Safetensors-specific branch was not selected. Execution could fall through to the generic PyTorch loader:

```
torch.load(    checkpoint_file,    map_location=map_location,    weights_only=weights_only,)
```

And in this path:

```
weights_only=False
```

The application was trying to enforce "Only load Safetensors here", but the input effectively behaved like this:

```
.safetensors                 │                 ▼        Validation check                 │                 ▼               "SAFE"                 │                 ▼       Different filename parser                 │                 ▼            "Not Safetensors"                 │                 ▼          Generic loader                 │                 ▼      torch.load(..., weights_only=False)
```

That is a security boundary problem.

## Exploitation

### Step 1: Check whether the shard filename is controllable

Sharded checkpoints use an index file that maps model weights to shard files. The researcher created a minimal test case where the index referenced:

```
.safetensors
```

For example:

```
{  "metadata": {    "format": "pt"  },  "weight_map": {    "w": ".safetensors"  }}
```

And the checkpoint directory looked like:

```
checkpoint/├── model.safetensors.index.json└── .safetensors
```

The chain then looked like:

```
Attacker-controlled index          ↓Attacker-controlled filename          ↓.safetensors          ↓passes validation          ↓different extension interpretation          ↓unsafe loader
```

### Step 2: Prove the complete data flow

Finding `torch.load(..., weights_only=False)` does not automatically make something a vulnerability, and finding `".safetensors".endswith(".safetensors")` is not enough. The researcher instrumented the real code path and verified:

```
1. The crafted shard name was accepted.2. The Safetensors branch was not selected.3. The generic loader was reached.4. The call used weights_only=False.5. The input originated from the attacker-controlled checkpoint.
```

That was the moment the finding became much more interesting. Finding a weird filename is "huh, that's odd". Finding the same filename reach `torch.load(..., weights_only=False)` is "Oh." Finding out it is reachable through the default safe-loading path is "OH."

## Root cause

The vulnerability was not "PyTorch has an unsafe deserialisation mechanism". The actual issue was that a specially crafted filename could bypass the intended safe-loading validation and redirect attacker-controlled checkpoint data into an unsafe deserialisation path. The caller did not explicitly request unsafe pickle loading, and the safety control was supposed to prevent exactly this kind of behaviour. But the two parts of the application disagreed about what the filename meant.

The entire bypass relied on two slightly different concepts of "extension". The first check asked "Does this string end with `.safetensors`?" and for `.safetensors` the answer is yes. The second check asked "What does the path library consider the extension?" and for `.safetensors` the answer is nothing. Neither operation is inherently dangerous. The danger came from using them as though they were equivalent. They were not.

The full attack chain:

```
ATTACKER                     │                     ▼        Crafted sharded checkpoint                     │                     ▼         Controlled shard filename                     │                     ▼            ".safetensors"                     │                     ▼        passes filename validation                     │                     ▼         different extension parser                     │                     ▼        Safetensors branch skipped                     │                     ▼             torch.load()                     │                     ▼         weights_only=False                     │                     ▼          unsafe deserialization                     │                     ▼             potential RCE
```

## Impact

Potentially, yes, this could lead to RCE. Unsafe Python pickle deserialisation can become an arbitrary code execution primitive when an attacker controls the serialised data being loaded. Under the right conditions, a malicious checkpoint could potentially result in code execution inside the victim process, and the attacker could potentially access whatever the process itself has permission to access:

```
Environment variablesAPI keysCredentialsLocal filesConfigurationApplication data
```

The exact impact depends heavily on the victim's environment and process permissions.

There is an important catch. This was not:

```
Attacker   ↓Internet   ↓Instant RCE on random machines
```

The victim has to actually obtain and load the malicious checkpoint through the vulnerable path:

```
Attacker publishes malicious checkpoint                ↓Victim downloads / receives it                ↓Victim loads the checkpoint                ↓Vulnerable path is triggered                ↓Unsafe deserialization
```

That exploitation requirement is important when evaluating severity. The vulnerability was ultimately rated Medium.

## Fix

The fundamental fix is to make the validation and loading logic agree on what constitutes a valid Safetensors file:

```
One definition        ↓One validation rule        ↓One interpretation        ↓No parser mismatch
```

Security-sensitive decisions should not depend on multiple subtly different interpretations of the same attacker-controlled string. The report states that the issue was fixed.

## Variants to test

When looking at filename validation, the researcher likes testing edge cases such as:

```
.hidden...file.file..extfoo..bar.safetensors
```

You do not need every weird string to produce a vulnerability. You just need one input that causes two pieces of security-sensitive code to disagree. A useful mental model is:

```
Input  ↓Validation  ↓Normalization  ↓Routing  ↓Parsing  ↓Dangerous sink
```

A security boundary can look perfectly fine at step #2 and still fail at step #5. When you see:

```
if something_is_safe:    ...
```

do not immediately move on. Follow the exact input afterward and ask whether every component interprets this input the same way. A positive result is an input that passes the safety check in one component but is classified differently by the component that selects the loader, reaching a dangerous sink such as `torch.load(..., weights_only=False)`.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

## What happened, in plain words

A security researcher found a bug in an application that loads machine-learning models. The application had a safety switch turned on by default, meant to make sure it only loaded a safe file format called Safetensors. The researcher discovered that a file with a very strange name, `.safetensors`, was treated as safe by one part of the program but as something completely different by another part. That disagreement sent the file down a dangerous path where the program would load it in a way that can potentially run code. The report was accepted, rated Medium, paid a bounty, and fixed.

This article walks through the same steps the researcher took, but assumes you have never done security work before. You only need to know how to use a browser and a computer. Every technical term is explained where it first appears.

## The starting point: a model-loading API

The target was an application that exposed a **model-loading API**. An API (Application Programming Interface) is a way for one program to ask another program to do something. Think of it like a restaurant menu: you choose an item, the kitchen prepares it, and you get a result. Here, the menu item was "load a machine-learning model from a file."

A machine-learning model is a large file full of numbers that a computer uses to make predictions or generate text. Loading it means reading that file into memory so the program can use it.

The API had a safety option enabled by default:

```
safe=True
```

This is a setting in the code. `safe=True` means "yes, please use the safe mode." The intended behaviour was simple: accept Safetensors files and use the safe loading path. Safetensors is a file format designed to store model data without allowing code execution. The dangerous alternative is loading arbitrary Python pickle data. Pickle is Python's way of saving objects to a file, and loading a pickle file can run code hidden inside it. That is why the safe option exists.

The researcher was not looking for a way to exploit `torch.load()` itself. `torch.load()` is a function in PyTorch, a popular machine-learning library, that reads model files. The researcher was looking for a way to make the program think it was loading something safe when it was not.

The bug was caused by a tiny inconsistency in filename parsing. Parsing means breaking a piece of text into parts and deciding what each part means. One part of the application considered a file named:

```
.safetensors
```

to be a valid Safetensors file. Another part considered the exact same filename to have no extension at all. An extension is the part of a filename after the last dot, like `.txt` in `notes.txt`. This happened inside a security-sensitive loading path, and the result was a path from an attacker-controlled checkpoint to:

```
torch.load(..., weights_only=False)
```

`weights_only=False` is a setting that tells PyTorch to allow more than just plain numbers when loading. It can allow pickle data, which can run code. The report was accepted, rated Medium, rewarded with a bounty, and fixed.

## Setup

The report does not describe accounts, roles, tools or versions. The work was done by tracing the filename from validation all the way to the final loader, and by building a minimal sharded checkpoint to test the path. A sharded checkpoint is a model split into several files, called shards, plus an index file that says which shard holds which part of the model. Think of it like a book split into chapters, with a table of contents telling you where each chapter is.

## Finding it

The researcher started with a question that sounds almost stupid:

> "What if I give it a really weird filename?"


{{media:0}}


The sharded checkpoint logic used a check similar to:

```
shard_file.endswith(".safetensors")
```

This is a line of Python code. `shard_file` is a variable holding a filename as text. `.endswith(".safetensors")` asks a simple question: does this text end with the characters `.safetensors`? It returns `True` or `False`. Think of it like checking whether a sentence ends with a particular word.

For example:

```
"model-00001-of-00002.safetensors".endswith(".safetensors")
```

returns:

```
True
```

This is a normal filename. It ends with `.safetensors`, so the check says yes. Nothing interesting there.

Then the researcher tried edge cases. An edge case is an unusual input that sits at the boundary of what the code expects, like an empty name or a name made only of dots. One filename caught their attention:

```
.safetensors
```

And:

```
".safetensors".endswith(".safetensors")
```

returns:

```
True
```

This filename is just a dot followed by the word safetensors. There is no name before the dot. The check still says yes, because the text does end with those characters. The result was not surprising. What mattered was the next question: does the next stage interpret this filename the same way?

Later in the loading process, the code used:

```
Path(shard_file).suffix
```

`Path` is a Python tool for working with file paths. `.suffix` asks it for the extension of the file. Think of it as asking a librarian, "What is the file extension on this label?" The librarian follows a rule: the extension is the part after the last dot, but only if there is something before that dot. A file named just `.safetensors` has a dot at the very start and nothing before it, so the librarian says there is no extension.

For a normal filename:

```
Path("model.safetensors").suffix
```

we get:

```
.safetensors
```

That is expected. The name is `model`, the dot separates it from the extension, and the extension is `.safetensors`.

But for:

```
Path(".safetensors").suffix
```

we get:

An empty string means "nothing." The same filename was now being interpreted differently. The first check said yes, it is a Safetensors file. The second check said it has no extension at all.

The researcher drew it like this:

```
┌──────────────────────────────────────────────┐│ Filename: .safetensors                       │├──────────────────────────────────────────────┤│ endswith(".safetensors")  → TRUE �
          ││ Path(...).suffix            → "" ❌           │└──────────────────────────────────────────────┘
```

This box shows the disagreement. The top line is the filename. The next line shows the first check returning true. The last line shows the second check returning an empty string. Two parts of the same program, looking at the same text, reached different conclusions.

A parser mismatch is only interesting from a security perspective if it changes something important, so the researcher followed the execution path. Execution path means the order in which the program runs its lines of code. The first check was part of the sharded checkpoint validation. Validation means checking that input is allowed before using it. The second check influenced which loader would actually process the file. A loader is the piece of code that reads the file into memory.

Because `.safetensors` produced an empty suffix with `Path(...).suffix`, the Safetensors-specific branch was not selected. A branch is a choice in the code, like a fork in a road. The program looked at the empty suffix, decided this was not a Safetensors file, and took the other road. Execution could fall through to the generic PyTorch loader:

```
torch.load(    checkpoint_file,    map_location=map_location,    weights_only=weights_only,)
```

This is a call to `torch.load()`. `checkpoint_file` is the file to load. `map_location` tells PyTorch where to place the data in memory. `weights_only` is the safety setting passed along. The call uses whatever value `weights_only` has at that point.

And in this path:

```
weights_only=False
```

That means the safety setting is off. The generic loader is allowed to load pickle data, which can run code.

The application was trying to enforce "Only load Safetensors here", but the input effectively behaved like this:

```
.safetensors                 │                 ▼        Validation check                 │                 ▼               "SAFE"                 │                 ▼       Different filename parser                 │                 ▼            "Not Safetensors"                 │                 ▼          Generic loader                 │                 ▼      torch.load(..., weights_only=False)
```

This diagram reads from top to bottom. The filename goes into the validation check, which says "SAFE." Then a different filename parser looks at it and says "Not Safetensors." That sends it to the generic loader, which calls `torch.load` with `weights_only=False`. That is a security boundary problem. A security boundary is an imaginary line that separates safe from unsafe. Here the line was crossed because two parts of the program disagreed about which side of the line the file was on.

## Exploitation

Exploitation means turning a bug into a practical attack. The researcher needed to prove the whole chain worked, not just that a weird filename existed.

### Step 1: Check whether the shard filename is controllable

Sharded checkpoints use an index file that maps model weights to shard files. The index is like a table of contents. If an attacker can write the index, they can choose the filenames inside it. The researcher created a minimal test case where the index referenced:

```
.safetensors
```

For example:

```
{  "metadata": {    "format": "pt"  },  "weight_map": {    "w": ".safetensors"  }}
```

This is a JSON file, a common text format for structured data. The `metadata` section says the format is `pt`, which stands for PyTorch. The `weight_map` section maps a weight named `w` to a file named `.safetensors`. In plain words: "The model part called w lives in a file called .safetensors." If an attacker controls this file, they control the filename that the program will later check.

And the checkpoint directory looked like:

```
checkpoint/├── model.safetensors.index.json└── .safetensors
```

This shows a folder named `checkpoint` containing two files: the index file `model.safetensors.index.json` and the shard file `.safetensors`. The tree drawing uses lines to show what is inside what.

The chain then looked like:

```
Attacker-controlled index          ↓Attacker-controlled filename          ↓.safetensors          ↓passes validation          ↓different extension interpretation          ↓unsafe loader
```

This reads from top to bottom. The attacker controls the index, which controls the filename. The filename is `.safetensors`. It passes validation. A different part of the program interprets the extension differently. That leads to the unsafe loader.

### Step 2: Prove the complete data flow

Data flow means the journey of data through the program, from where it enters to where it is used. Finding `torch.load(..., weights_only=False)` does not automatically make something a vulnerability, and finding `".safetensors".endswith(".safetensors")` is not enough. Many programs contain dangerous functions that are never reachable with attacker input. The researcher instrumented the real code path and verified:

```
1. The crafted shard name was accepted.2. The Safetensors branch was not selected.3. The generic loader was reached.4. The call used weights_only=False.5. The input originated from the attacker-controlled checkpoint.
```

Instrumented means adding temporary logging or checks to see what the program actually does at each step. The list confirms five things. First, the crafted shard name was accepted. Second, the Safetensors branch was not selected. Third, the generic loader was reached. Fourth, the call used `weights_only=False`. Fifth, the input originated from the attacker-controlled checkpoint. All five together mean the attacker's filename really did travel all the way to the dangerous call.

That was the moment the finding became much more interesting. Finding a weird filename is "huh, that's odd". Finding the same filename reach `torch.load(..., weights_only=False)` is "Oh." Finding out it is reachable through the default safe-loading path is "OH."

## Root cause

Root cause means the underlying reason the bug exists, not just where it shows up. The vulnerability was not "PyTorch has an unsafe deserialisation mechanism". Deserialisation is the process of turning saved data back into objects in memory. It is like unpacking a box. If the box can contain instructions, unpacking it can run those instructions. That is a known property of pickle. The actual issue was that a specially crafted filename could bypass the intended safe-loading validation and redirect attacker-controlled checkpoint data into an unsafe deserialisation path. The caller did not explicitly request unsafe pickle loading, and the safety control was supposed to prevent exactly this kind of behaviour. But the two parts of the application disagreed about what the filename meant.

The entire bypass relied on two slightly different concepts of "extension". The first check asked "Does this string end with `.safetensors`?" and for `.safetensors` the answer is yes. The second check asked "What does the path library consider the extension?" and for `.safetensors` the answer is nothing. Neither operation is inherently dangerous. The danger came from using them as though they were equivalent. They were not.

The full attack chain:

```
ATTACKER                     │                     ▼        Crafted sharded checkpoint                     │                     ▼         Controlled shard filename                     │                     ▼            ".safetensors"                     │                     ▼        passes filename validation                     │                     ▼         different extension parser                     │                     ▼        Safetensors branch skipped                     │                     ▼             torch.load()                     │                     ▼         weights_only=False                     │                     ▼          unsafe deserialization                     │                     ▼             potential RCE
```

This diagram reads from top to bottom. The attacker creates a crafted sharded checkpoint. The shard filename is controlled. The filename is `.safetensors`. It passes filename validation. A different extension parser looks at it. The Safetensors branch is skipped. `torch.load()` is called. `weights_only=False` is used. Unsafe deserialisation happens. That can lead to potential RCE, which stands for remote code execution: an attacker's code running on the victim's machine.

## Impact

Impact means what an attacker could actually do if the bug is exploited. Potentially, yes, this could lead to RCE. Unsafe Python pickle deserialisation can become an arbitrary code execution primitive when an attacker controls the serialised data being loaded. A primitive here means a basic building block that can be used to do more. Under the right conditions, a malicious checkpoint could potentially result in code execution inside the victim process, and the attacker could potentially access whatever the process itself has permission to access:

```
Environment variablesAPI keysCredentialsLocal filesConfigurationApplication data
```

This list shows what a running program can often see. Environment variables are settings stored by the operating system, sometimes including secrets. API keys are passwords for services. Credentials are usernames and passwords. Local files are files on the same computer. Configuration is the program's settings. Application data is whatever the program stores. If an attacker can run code inside the process, they could potentially read these, limited by what the process is allowed to access.

The exact impact depends heavily on the victim's environment and process permissions. Process permissions are the rules about what a running program may read, write or execute.

There is an important catch. This was not:

```
Attacker   ↓Internet   ↓Instant RCE on random machines
```

This idea means the attacker cannot simply send something over the internet and instantly run code on random computers. The victim has to actually obtain and load the malicious checkpoint through the vulnerable path:

```
Attacker publishes malicious checkpoint                ↓Victim downloads / receives it                ↓Victim loads the checkpoint                ↓Vulnerable path is triggered                ↓Unsafe deserialization
```

This reads from top to bottom. The attacker publishes a malicious checkpoint. The victim downloads or receives it. The victim loads the checkpoint. The vulnerable path is triggered. Unsafe deserialisation happens. The victim has to take those steps. That exploitation requirement is important when evaluating severity. Severity is a rating of how serious a bug is. The vulnerability was ultimately rated Medium.

## Fix

The fundamental fix is to make the validation and loading logic agree on what constitutes a valid Safetensors file:

```
One definition        ↓One validation rule        ↓One interpretation        ↓No parser mismatch
```

This reads from top to bottom. One definition of what a Safetensors file is. One validation rule. One interpretation. No parser mismatch. Security-sensitive decisions should not depend on multiple subtly different interpretations of the same attacker-controlled string. The report states that the issue was fixed.

## Variants to test

When looking at filename validation, the researcher likes testing edge cases such as:

```
.hidden...file.file..extfoo..bar.safetensors
```

This is a list of strange filenames, one per line. `.hidden` starts with a dot. `..` is just two dots. `.file` starts with a dot. `file..ext` has two dots in the middle. `foo..bar.safetensors` has two dots and then a normal extension. These are the kinds of inputs that make different parsers disagree.

You do not need every weird string to produce a vulnerability. You just need one input that causes two pieces of security-sensitive code to disagree. A useful mental model is:

```
Input  ↓Validation  ↓Normalization  ↓Routing  ↓Parsing  ↓Dangerous sink
```

This reads from top to bottom. Input enters. Validation checks it. Normalization cleans it up into a standard form. Routing decides where it goes. Parsing breaks it into parts. A dangerous sink is a place where bad input causes harm, like `torch.load(..., weights_only=False)`. A security boundary can look perfectly fine at step #2 and still fail at step #5. When you see:

```
if something_is_safe:    ...
```

do not immediately move on. This is an `if` statement: if the condition is true, run the indented code. Follow the exact input afterward and ask whether every component interprets this input the same way. A positive result is an input that passes the safety check in one component but is classified differently by the component that selects the loader, reaching a dangerous sink such as `torch.load(..., weights_only=False)`.

## Glossary

- **API**: A way for one program to ask another program to do something, like a menu in a restaurant.
- **Bounty**: A reward paid for finding and reporting a security bug.
- **Branch**: A choice in code, like a fork in a road.
- **Checkpoint**: A saved model file, or a set of files, that can be loaded later.
- **Credentials**: Usernames and passwords, or other proof of identity.
- **Data flow**: The journey of data through a program, from where it enters to where it is used.
- **Deserialisation**: Turning saved data back into objects in memory, like unpacking a box.
- **Edge case**: An unusual input at the boundary of what code expects, like an empty name or a name made only of dots.
- **Environment variables**: Settings stored by the operating system, sometimes including secrets.
- **Execution path**: The order in which a program runs its lines of code.
- **Extension**: The part of a filename after the last dot, like `.txt` in `notes.txt`.
- **Index file**: A file that maps parts of a model to the shard files that hold them, like a table of contents.
- **Instrumented**: Code with temporary logging or checks added to see what it actually does.
- **JSON**: A common text format for structured data.
- **Loader**: The piece of code that reads a file into memory.
- **Model**: A large file of numbers that a computer uses to make predictions or generate text.
- **Normalization**: Cleaning input into a standard form.
- **Parser**: Code that breaks text into parts and decides what each part means.
- **Parser mismatch**: When two parts of a program interpret the same input differently.
- **Pickle**: Python's way of saving objects to a file; loading it can run code.
- **Primitive**: A basic building block that can be used to do more.
- **Process**: A running program.
- **Process permissions**: The rules about what a running program may read, write or execute.
- **PyTorch**: A popular machine-learning library for Python.
- **RCE**: Remote code execution, an attacker's code running on the victim's machine.
- **Root cause**: The underlying reason a bug exists.
- **Safetensors**: A file format for model data designed to avoid code execution.
- **Severity**: A rating of how serious a bug is.
- **Shard**: One file of a model that has been split into several files.
- **Sharded checkpoint**: A model split into shards plus an index file.
- **Sink**: A place in code where bad input causes harm.
- **Validation**: Checking that input is allowed before using it.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.