Argument/Code Injection via ActiveStorage's image transformation functionality
ActiveStorage's image transformation methods pass user-supplied arguments to ImageMagick without sanitisation, allowing argument injection and arbitrary file write. Additionally, the transformation name is passed to Ruby's send, enabling code execution if the application uses user-controlled transformation names.
- Triaged in 7 days
- Fixed in 12 months
- Disclosed after 2.3 years
Affected components
Tested on:
- activestorage 6.1.3.1
- image_processing 1.12.1
- mini_magick 4.11.0
Found by
Gabriel Quadros and Ricardo Silva from Conviso Application Security
Description
Intro
ActiveStorage has an image transformation functionality [1, 2, 3, 4, 5, 6] which uses the concept of variants. By their own words [5]:
Image blobs can have variants that are the result of a set of transformations applied to the original. These variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the original.
Variants rely on ImageProcessing gem for the actual transformations of the file, so you must add gem "image_processing" to your Gemfile if you wish to use variants. By default, images will be processed with ImageMagick using the MiniMagick gem, but you can also switch to the libvips processor operated by the ruby-vips gem).
One example of direct usage can be seen in the docs as:
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
This will create an image tag with a variant URL, which when visited will return the avatar image transformed to the new size.
Another example uses the preview() method, which can be used to generate images from videos and PDF files. Once the preview image is generated, it also calls variant() under the hood.
<ul>
<% @message.files.each do |file| %>
<li>
<%= image_tag file.preview(resize_to_limit: [100, 100]) %>
</li>
<% end %>
</ul>
Vulnerabilities
First, it is worth noting that the docs [3, 4, 7] do not state anything about it being insecure to pass user-supplied values as arguments to the variant()/preview() methods.
Rails uses the gem ImageProcessing [8] with MiniMagick by default, passing the transformations to the apply method.
File: activestorage/lib/active_storage/transformers/image_processing_transformer.rb
12 module ActiveStorage
13 module Transformers
14 class ImageProcessingTransformer < Transformer
15 private
16 def process(file, format:)
17 processor.
18 source(file).
19 loader(page: 0).
20 convert(format).
21 apply(operations).
22 call
23 end
This method passes these operations to the builder object by iterating over them and calling methods providing arguments, as can be seen below.
File: lib/image_processing/chainable.rb
24 # Add multiple operations as a hash or an array.
25 #
26 # .apply(resize_to_limit: [400, 400], strip: true)
27 # # or
28 # .apply([[:resize_to_limit, [400, 400]], [:strip, true])
29 def apply(operations)
30 operations.inject(self) do |builder, (name, argument)|
31 if argument == true || argument == nil
32 builder.send(name)
33 elsif argument.is_a?(Array)
34 builder.send(name, *argument)
35 elsif argument.is_a?(Hash)
36 builder.send(name, **argument)
37 else
38 builder.send(name, argument)
39 end
40 end
41 end
At some point, ImageProcessing passes these operations to MiniMagick via method calling as well:
File: lib/image_processing/processor.rb
51 # Calls the operation to perform the processing. If the operation is
52 # defined on the processor (macro), calls the method. Otherwise calls the
53 # operation directly on the accumulator object. This provides a common
54 # umbrella above defined macros and direct operations.
55 def apply_operation(name, *args, &block)
56 receiver = respond_to?(name) ? self : @accumulator
57
58 if args.last.is_a?(Hash)
59 kwargs = args.pop
60 receiver.public_send(name, *args, **kwargs, &block)
61 else
62 receiver.public_send(name, *args, &block)
63 end
64 end
MiniMagick receives these operations by defining a method_missing method, which takes the called methods and convert them to CLI options:
File: lib/mini_magick/tool.rb
260 ##
261 # Any undefined method will be transformed into a CLI option
262 #
263 # @example
264 # mogrify = MiniMagick::Tool.new("mogrify")
265 # mogrify.adaptive_blur("...")
266 # mogrify.foo_bar
267 # mogrify.command.join(" ") # => "mogrify -adaptive-blur ... -foo-bar"
268 #
269 def method_missing(name, *args)
270 option = "-#{name.to_s.tr('_', '-')}"
271 self << option
272 self.merge!(args)
273 self
274 end
Argument Injection
The first problem arrises when a user-supplied value is passed as input to a hard-coded transformation, such as:
<%= image_tag user.avatar.variant(resize: params[:new_size]) %>
Since Rails params[] can be an array, one thing the attacker could do here is to pass an array and inject arbitrary arguments into the command to be executed (ImageMagick's convert by default).
Example:
https://example.com/controller?new_size[]=123&new_size[]=-set&new_size[]=comment&new_size[]=MYCOMMENT&new_size[]=-write&new_size[]=/tmp/file.erb
This is going to generate the following command:
convert ORIGINAL_IMAGE -auto-orient -resize 123 -set comment MYCOMMENT -write /tmp/file.erb /tmp/image_processing20210328-23426-63rmm2.png
Which has the effect of writing a file containing user-controlled data anywhere in the system. This could be used easily to achieve RCE against Rails applications by overwriting ERB files, for example.
User-controlled transformation
A second problem arrises when the user is also allowed to choose the kind of transformation to be applied, such as:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
This is still dangerous since ImageMagick's convert program has a lot of powerful command-line options and they can be used to compromise the application. For example, the user could pass:
https://example.com/controller?t=write&v=/tmp/file2.erb
This is going to generate the following command:
convert ORIGINAL_IMAGE -auto-orient -write /tmp/file2.erb /tmp/image_processing20210328-23426-63rmm2.png
Which has a similar effect as the previous attack, if we consider the original image is usually user-controlled.
Code Injection
The third problem occurs due the way ImageProcessing passes the operations to the builder object (via send()). There is no filtering to check if the called method is a valid operation and this can be explored by an attacker to execute code.
Consider the same pattern as before:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
The attacker could pass:
https://example.com/controller?t=eval&v=system("touch /tmp/hacked")
And the Ruby code system("touch /tmp/hacked") would be executed.
Recomendations
- Add some notes in the documentation to warn developers about the dangers of passing user-supplied data to the affected methods (variant/preview) without sanitization;
- Fix the argument injection problem;
- Implement an operations whitelist in ImageProcessing, so it won't call unexpected methods.
References
- https://guides.rubyonrails.org/active_storage_overview.html#transforming-images
- https://guides.rubyonrails.org/active_storage_overview.html#previewing-files
- https://api.rubyonrails.org/v6.1.3.1/classes/ActiveStorage/Blob/Representable.html#method-i-variant
- https://api.rubyonrails.org/v6.1.3.1/classes/ActiveStorage/Blob/Representable.html#method-i-preview
- https://api.rubyonrails.org/v6.1.3.1/classes/ActiveStorage/Variant.html
- https://api.rubyonrails.org/v6.1.3.1/classes/ActiveStorage/Preview.html
- https://github.com/rails/rails/issues/32989
- https://github.com/janko/image_processing
Impact
Vulnerable code patterns could allow the attacker to achieve RCE.
Context
ActiveStorage, the file attachment component of Ruby on Rails, ships an image transformation feature built around variants. As the Rails documentation puts it, image blobs can have variants that are the result of a set of transformations applied to the original, and these variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the original.
Variants rely on the ImageProcessing gem for the actual transformations, so gem "image_processing" has to be in the Gemfile if variants are used. By default images are processed with ImageMagick through the MiniMagick gem, but the libvips processor operated by the ruby-vips gem can be selected instead.
The documented usage is straightforward. A view can render a resized avatar:
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
This creates an image tag with a variant URL, and visiting that URL returns the avatar transformed to the new size. A second documented pattern uses preview(), which generates images from videos and PDF files and calls variant() under the hood once the preview image exists:
<ul>
<% @message.files.each do |file| %>
<li>
<%= image_tag file.preview(resize_to_limit: [100, 100]) %>
</li>
<% end %>
</ul>
The report was written by Gabriel Quadros and Ricardo Silva from Conviso Application Security, and it concerns the rails/rails repository. The central observation is that the documentation does not state anything about it being insecure to pass user-supplied values as arguments to the variant() and preview() methods. That gap between a convenient API and an unsafe calling convention is what the three findings below exploit.
Setup
The behaviour was tested against the following component versions:
- activestorage [redacted]
- image_processing 1.12.1
- mini_magick 4.11.0
No accounts, roles or special tooling are described beyond a Rails application using ActiveStorage variants with the default ImageMagick/MiniMagick processor. The precondition for every attack is application code that forwards user-controlled input into variant() or preview(), either as an argument value or as the transformation name itself.
Finding it
The researcher followed the call path from ActiveStorage down to the command line. Rails uses the ImageProcessing gem with MiniMagick by default and passes the transformations to the apply method.
File: activestorage/lib/active_storage/transformers/image_processing_transformer.rb
12 module ActiveStorage
13 module Transformers
14 class ImageProcessingTransformer < Transformer
15 private
16 def process(file, format:)
17 processor.
18 source(file).
19 loader(page: 0).
20 convert(format).
21 apply(operations).
22 call
23 end
That method hands the operations to the builder object, which iterates over them and calls methods with the supplied arguments:
File: lib/image_processing/chainable.rb
24 # Add multiple operations as a hash or an array.
25 #
26 # .apply(resize_to_limit: [400, 400], strip: true)
27 # # or
28 # .apply([[:resize_to_limit, [400, 400]], [:strip, true])
29 def apply(operations)
30 operations.inject(self) do |builder, (name, argument)|
31 if argument == true || argument == nil
32 builder.send(name)
33 elsif argument.is_a?(Array)
34 builder.send(name, *argument)
35 elsif argument.is_a?(Hash)
36 builder.send(name, **argument)
37 else
38 builder.send(name, argument)
39 end
40 end
41 end
ImageProcessing then passes the operations to MiniMagick through method calls as well:
File: lib/image_processing/processor.rb
51 # Calls the operation to perform the processing. If the operation is
52 # defined on the processor (macro), calls the method. Otherwise calls the
53 # operation directly on the accumulator object. This provides a common
54 # umbrella above defined macros and direct operations.
55 def apply_operation(name, *args, &block)
56 receiver = respond_to?(name) ? self : @accumulator
57
58 if args.last.is_a?(Hash)
59 kwargs = args.pop
60 receiver.public_send(name, *args, **kwargs, &block)
61 else
62 receiver.public_send(name, *args, &block)
63 end
64 end
Finally MiniMagick receives the operations through a method_missing implementation that turns called methods into CLI options:
File: lib/mini_magick/tool.rb
260 ##
261 # Any undefined method will be transformed into a CLI option
262 #
263 # @example
264 # mogrify = MiniMagick::Tool.new("mogrify")
265 # mogrify.adaptive_blur("...")
266 # mogrify.foo_bar
267 # mogrify.command.join(" ") # => "mogrify -adaptive-blur ... -foo-bar"
268 #
269 def method_missing(name, *args)
270 option = "-#{name.to_s.tr('_', '-')}"
271 self << option
272 self.merge!(args)
273 self
274 end
Three properties of this chain stood out. Arguments supplied by the caller are splatted into the builder call, so an array becomes multiple arguments. The transformation name itself is passed to send, with no check that it is a legitimate operation. And MiniMagick converts any unknown method name into an arbitrary ImageMagick CLI option. Each of these becomes a separate vulnerability.
Exploitation
Step 1: Argument injection into a hard-coded transformation
The first problem arises when a user-supplied value is passed as input to a hard-coded transformation, such as:
<%= image_tag user.avatar.variant(resize: params[:new_size]) %>
Because Rails params[] can be an array, an attacker can pass an array and inject arbitrary arguments into the command that will be executed, ImageMagick's convert by default. The example request is:
https://example.com/controller?new_size[]=123&new_size[]=-set&new_size[]=comment&new_size[]=MYCOMMENT&new_size[]=-write&new_size[]=/tmp/file.erb
This generates the following command:
convert ORIGINAL_IMAGE -auto-orient -resize 123 -set comment MYCOMMENT -write /tmp/file.erb /tmp/image_processing20210328-23426-63rmm2.png
The array elements are splatted as separate arguments to the resize operation. The first element, 123, is the legitimate size. The remaining elements are interpreted by ImageMagick as new options: -set comment MYCOMMENT attaches attacker-controlled data to the image, and -write /tmp/file.erb writes the result to an arbitrary path. The effect is that a file containing user-controlled data can be written anywhere in the system. The report notes this could be used easily to achieve RCE against Rails applications by overwriting ERB files, for example.
Step 2: User-controlled transformation name
The second problem arises when the user is also allowed to choose the kind of transformation to be applied:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
This is still dangerous because ImageMagick's convert has a lot of powerful command-line options that can be used to compromise the application. The attacker could pass:
https://example.com/controller?t=write&v=/tmp/file2.erb
This generates the following command:
convert ORIGINAL_IMAGE -auto-orient -write /tmp/file2.erb /tmp/image_processing20210328-23426-63rmm2.png
Here the transformation name write becomes the -write option directly, with no need to smuggle it through an array. The effect is similar to the previous attack, particularly because the original image is usually user-controlled, so the attacker controls what gets written to the target path.
Step 3: Code injection through send
The third problem comes from the way ImageProcessing passes operations to the builder object via send(). There is no filtering to check whether the called method is a valid operation, and an attacker can use this to execute code. With the same pattern as before:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
The attacker could pass:
https://example.com/controller?t=eval&v=system("touch /tmp/hacked")
And the Ruby code system("touch /tmp/hacked") would be executed. The transformation name eval is dispatched through builder.send(name, argument), so the argument string is evaluated as Ruby rather than treated as an image operation.
Root cause
The chain shown here has no validation of operation names or arguments. apply in ImageProcessing calls builder.send(name, ...) with whatever name it is given, so any method reachable on the builder can be invoked, including eval. apply_operation in the processor likewise dispatches with public_send to either the processor or the accumulator without checking that the name is a known operation. MiniMagick's method_missing then deliberately converts any undefined method name into a CLI option, which is what turns an unexpected method name into an arbitrary ImageMagick flag. On top of that, array arguments are splatted into separate arguments, so a single parameter can inject multiple CLI options into a hard-coded transformation.
The documentation does not warn that passing user-supplied values to variant() or preview() is unsafe, and the report explicitly notes that the docs say nothing about it. There is no allowlist of operations in ImageProcessing, and no filtering of method names before send.
Impact
Vulnerable code patterns could allow the attacker to achieve RCE. The three paths differ in what they require from the application: argument injection needs a user-controlled value passed to a fixed transformation, the user-controlled transformation needs the transformation name to be attacker-chosen, and the code injection needs the same pattern but reaches Ruby's eval through send. In all cases the precondition is application code that forwards request parameters into variant() or preview() without sanitisation. The report says vulnerable code patterns could allow the attacker to achieve RCE, and describes file write to arbitrary paths in the first two variants.
Fix
The report makes three recommendations:
- Add notes to the documentation warning developers about the dangers of passing user-supplied data to the affected methods (
variant/preview) without sanitisation. - Fix the argument injection problem.
- Implement an operations whitelist in ImageProcessing, so it will not call unexpected methods.
The report does not state which of these were adopted or what code changes were made.
Variants to test
- Array-valued parameters into a fixed transformation. Look for views that pass a request parameter straight into a named operation, as in
variant(resize: params[:new_size]). A positive result is a generatedconvertcommand in which the extra array elements appear as separate ImageMagick options, for example a-writeto a path you chose. - Attacker-chosen transformation name. Look for
variant(params[:t].to_s => params[:v].to_s)or similar hash construction from request data. A positive result is a command containing the option derived from yourtvalue, such as-write /tmp/file2.erb. - Method dispatch through
send. With the same pattern, try a transformation name that is a Ruby method rather than an image operation, such aseval, and an argument containing Ruby code. A positive result is execution of that code, for example the creation of the file named in the payload. - Other processors. The report describes the default ImageMagick/MiniMagick path. If the application uses libvips through ruby-vips, check whether the same unvalidated dispatch of operation names and arguments exists on that path; the report does not cover it.
preview()call sites. The report notes thatpreview()callsvariant()under the hood, so the same patterns should be checked wherever previews of videos or PDFs are generated from user input.
What happened, in plain words
Imagine a website where people upload a profile picture. The website needs to show that picture at a small size, say 100 by 100 pixels, so it asks a helper program to shrink it. That helper program is called ImageMagick, and it is a very old, very powerful tool for editing images from the command line (the text interface where you type commands instead of clicking buttons).
Ruby on Rails is a popular framework for building websites. It has a component called ActiveStorage that handles uploaded files, and a feature called variants that asks ImageMagick to make resized copies of images. The problem the researchers found is that if a website passes something a visitor typed (a URL parameter) straight into that feature, the visitor can sneak extra instructions into the command that gets run on the server. Depending on how the website is written, that can let an attacker write files anywhere on the server, or even run their own code on it. Running your own code on someone else's server is called remote code execution, or RCE, and it is about as bad as it gets.
The report was written by Gabriel Quadros and Ricardo Silva from Conviso Application Security, and it concerns the rails/rails repository on GitHub. It describes three related problems, all coming from the same root: the image transformation feature trusts whatever it is given, and never checks that the names and values it receives are legitimate image operations.
The product and the feature
ActiveStorage is the part of Rails that stores files that users upload: avatars, attachments, PDFs, videos. A variant is a transformed copy of an uploaded image. As the Rails documentation puts it, image blobs can have variants that are the result of a set of transformations applied to the original, and these variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the original.
Variants rely on the ImageProcessing gem for the actual transformations, so gem "image_processing" has to be in the Gemfile if variants are used. A gem is a reusable package of Ruby code, the equivalent of an app or a plugin you install. By default images are processed with ImageMagick through the MiniMagick gem, but the libvips processor operated by the ruby-vips gem can be selected instead. ImageMagick is the program that actually does the pixel work; MiniMagick is a thin Ruby wrapper that builds the ImageMagick command line for you.
The documented usage is straightforward. A view (the part of a Rails app that produces HTML for the browser) can render a resized avatar:
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
Line by line:
<%= ... %>is Rails template syntax meaning "run this Ruby code and put the result into the page".image_tagis a Rails helper that produces an HTML<img>tag.user.avataris the uploaded file attached to a user..variant(resize_to_limit: [100, 100])asks ActiveStorage for a transformed copy, no larger than 100 by 100 pixels.
This creates an image tag with a variant URL, and visiting that URL returns the avatar transformed to the new size. Visiting that URL returns the avatar transformed to the new size.
A second documented pattern uses preview(), which generates images from videos and PDF files and calls variant() under the hood once the preview image exists:
<ul>
<% @message.files.each do |file| %>
<li>
<%= image_tag file.preview(resize_to_limit: [100, 100]) %>
</li>
<% end %>
</ul>
Line by line:
<ul>and<li>are plain HTML for a bulleted list and its items.<% @message.files.each do |file| %>loops over every file attached to a message;@messageis data the page was given.<%= image_tag file.preview(resize_to_limit: [100, 100]) %>asks for a preview image of that file, resized to at most 100 by 100 pixels, and shows it.<% end %>closes the loop.
The central observation is that the documentation does not state anything about it being insecure to pass user-supplied values as arguments to the variant() and preview() methods. That gap between a convenient API and an unsafe calling convention is what the three findings below exploit. An API here just means the set of methods a programmer can call; the point is that the manual never warns you about feeding it untrusted input.
Setup
The behaviour was tested against the following component versions:
- activestorage [redacted]
- image_processing 1.12.1
- mini_magick 4.11.0
No accounts, roles or special tooling are described beyond a Rails application using ActiveStorage variants with the default ImageMagick/MiniMagick processor. The precondition for every attack is application code that forwards user-controlled input into variant() or preview(), either as an argument value or as the transformation name itself. In plain terms: the bug is not in a website by default; it appears when a developer writes a page that lets the visitor decide part of the image operation.
Finding it
The researcher followed the call path from ActiveStorage down to the command line. Rails uses the ImageProcessing gem with MiniMagick by default and passes the transformations to the apply method. Following a call path means reading the code step by step, the way you might follow a parcel from the shop to your door, to see where an untrusted value ends up.
File: activestorage/lib/active_storage/transformers/image_processing_transformer.rb
12 module ActiveStorage
13 module Transformers
14 class ImageProcessingTransformer < Transformer
15 private
16 def process(file, format:)
17 processor.
18 source(file).
19 loader(page: 0).
20 convert(format).
21 apply(operations).
22 call
23 end
Line by line:
- Lines 12 to 14 declare the module and class names;
moduleandclassare Ruby's way of grouping code. - Line 15 marks what follows as
private, meaning only code inside this class can call it. - Line 16 defines
process, which takes the uploaded file and a target format. - Lines 17 to 22 are one chained expression: take the processor, give it the source file, set the loader page to 0 (relevant for PDFs, where page 0 is the first page), convert to the requested format, apply the requested operations, and finally run it. The dots at the end of each line mean the chain continues on the next line.
That method hands the operations to the builder object, which iterates over them and calls methods with the supplied arguments:
File: lib/image_processing/chainable.rb
24 # Add multiple operations as a hash or an array.
25 #
26 # .apply(resize_to_limit: [400, 400], strip: true)
27 # # or
28 # .apply([[:resize_to_limit, [400, 400]], [:strip, true])
29 def apply(operations)
30 operations.inject(self) do |builder, (name, argument)|
31 if argument == true || argument == nil
32 builder.send(name)
33 elsif argument.is_a?(Array)
34 builder.send(name, *argument)
35 elsif argument.is_a?(Hash)
36 builder.send(name, **argument)
37 else
38 builder.send(name, argument)
39 end
40 end
41 end
Line by line:
- Lines 24 to 28 are comments showing how
applycan be called: with a hash (a set of key and value pairs, like a labelled list) or with an array of pairs. - Line 29 defines
apply, which receives the operations. - Line 30 walks through the operations one at a time, carrying a
builderalong, and splits each one into anameand anargument. - Lines 31 and 32: if the argument is
trueor empty (nil), call the method namednamewith no argument. - Lines 33 and 34: if the argument is an array, call the method and spread the array's elements out as separate arguments. The
*is Ruby's "splat" operator, and this line is the heart of the first vulnerability. - Lines 35 and 36: if the argument is a hash, spread it out as named arguments (
**). - Lines 37 and 38: otherwise, call the method with the single argument.
sendis Ruby's way of calling a method whose name is stored in a variable rather than written in the code. That flexibility is the heart of the third vulnerability.
ImageProcessing then passes the operations to MiniMagick through method calls as well:
File: lib/image_processing/processor.rb
51 # Calls the operation to perform the processing. If the operation is
52 # defined on the processor (macro), calls the method. Otherwise calls the
53 # operation directly on the accumulator object. This provides a common
54 # umbrella above defined macros and direct operations.
55 def apply_operation(name, *args, &block)
56 receiver = respond_to?(name) ? self : @accumulator
57
58 if args.last.is_a?(Hash)
59 kwargs = args.pop
60 receiver.public_send(name, *args, **kwargs, &block)
61 else
62 receiver.public_send(name, *args, &block)
63 end
64 end
Line by line:
- Lines 51 to 54 are comments explaining the method's job.
- Line 55 defines
apply_operation, taking a name, any number of arguments, and an optional block (a chunk of code passed along). - Line 56 picks who will receive the call: the processor itself if it knows a method with that name, otherwise the accumulator (the object that collects the command line options).
- Lines 58 to 60: if the last argument is a hash, pull it out and pass it as named arguments.
- Lines 61 to 63: otherwise pass the arguments as they are.
public_sendis likesendbut only reaches methods that are meant to be called from outside. The name is still never checked against a list of valid image operations.
Finally MiniMagick receives the operations through a method_missing implementation that turns called methods into CLI options:
File: lib/mini_magick/tool.rb
260 ##
261 # Any undefined method will be transformed into a CLI option
262 #
263 # @example
264 # mogrify = MiniMagick::Tool.new("mogrify")
265 # mogrify.adaptive_blur("...")
266 # mogrify.foo_bar
267 # mogrify.command.join(" ") # => "mogrify -adaptive-blur ... -foo-bar"
268 #
269 def method_missing(name, *args)
270 option = "-#{name.to_s.tr('_', '-')}"
271 self << option
272 self.merge!(args)
273 self
274 end
Line by line:
- Lines 260 to 268 are comments, including an example: calling
adaptive_blurproduces-adaptive-blur, and callingfoo_barproduces-foo-bar. - Line 269 defines
method_missing, a special Ruby hook that runs whenever someone calls a method that does not exist. - Line 270 builds the option text: a dash followed by the method name with underscores turned into dashes.
trmeans translate characters. - Line 271 appends that option to the command being built.
- Line 272 appends the arguments after it.
- Line 273 returns the object so calls can be chained.
Three properties of this chain stood out. Arguments supplied by the caller are splatted into the builder call, so an array becomes multiple arguments. The transformation name itself is passed to send, with no check that it is a legitimate operation. And MiniMagick converts any unknown method name into an arbitrary ImageMagick CLI option. Each of these becomes a separate vulnerability.
Exploitation
Step 1: Argument injection into a hard-coded transformation
The first problem arises when a user-supplied value is passed as input to a hard-coded transformation, such as:
<%= image_tag user.avatar.variant(resize: params[:new_size]) %>
Line by line:
- The developer meant to fix the operation (
resize) and let the visitor choose only the size. paramsis Rails' collection of everything the visitor sent in the URL or form.params[:new_size]reads the value namednew_size.- The mistake is that
params[:new_size]is not guaranteed to be a single number. Rails lets a visitor send the same name several times with[]after it, and then the value arrives as an array.
Because Rails params[] can be an array, an attacker can pass an array and inject arbitrary arguments into the command that will be executed, ImageMagick's convert by default. The example request is:
https://example.com/controller?new_size[]=123&new_size[]=-set&new_size[]=comment&new_size[]=MYCOMMENT&new_size[]=-write&new_size[]=/tmp/file.erb
Reading the URL piece by piece:
https://example.com/controlleris the page being visited.?starts the query string, the part of a URL that carries parameters.new_size[]=123sets the first element of the array to123.new_size[]=-set,new_size[]=comment,new_size[]=MYCOMMENTadd three more elements that look like ImageMagick options.new_size[]=-writeandnew_size[]=/tmp/file.erbadd two more, asking ImageMagick to write a file to/tmp/file.erb.
This generates the following command:
convert ORIGINAL_IMAGE -auto-orient -resize 123 -set comment MYCOMMENT -write /tmp/file.erb /tmp/image_processing20210328-23426-63rmm2.png
Line by line:
convertis the ImageMagick program that transforms an image.ORIGINAL_IMAGEis the uploaded picture.-auto-orientis an option Rails always adds, which rotates the image according to its metadata.-resize 123is the intended operation, with the first array element as its size.-set comment MYCOMMENTattaches attacker-controlled text to the image.-write /tmp/file.erbwrites the result to a path the attacker chose.- The final path is the temporary output file ImageProcessing uses.
The array elements are splatted as separate arguments to the resize operation. The first element, 123, is the legitimate size. The remaining elements are interpreted by ImageMagick as new options: -set comment MYCOMMENT attaches attacker-controlled data to the image, and -write /tmp/file.erb writes the result to an arbitrary path. The effect is that a file containing user-controlled data can be written anywhere in the system. The report notes this could be used easily to achieve RCE against Rails applications by overwriting ERB files, for example. ERB files are the templates Rails uses to build pages, and they contain Ruby code, so a file the attacker can write into a template location can become code that runs on the server.
Step 2: User-controlled transformation name
The second problem arises when the user is also allowed to choose the kind of transformation to be applied:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
Line by line:
params[:t]is the transformation name the visitor sent, andparams[:v]is its value..to_sturns each into a string of text, so the code builds a hash whose key and value both come from the request.- That hash is passed to
variant, so the visitor now decides which operation runs, not just its size.
This is still dangerous because ImageMagick's convert has a lot of powerful command-line options that can be used to compromise the application. The attacker could pass:
https://example.com/controller?t=write&v=/tmp/file2.erb
Reading it: t=write makes the transformation name write, and v=/tmp/file2.erb makes its value the target path.
This generates the following command:
convert ORIGINAL_IMAGE -auto-orient -write /tmp/file2.erb /tmp/image_processing20210328-23426-63rmm2.png
Line by line:
convert ORIGINAL_IMAGE -auto-orientis the same start as before.-write /tmp/file2.erbis now the operation itself, produced directly from the visitor'standvvalues.- The final path is again the temporary output file.
Here the transformation name write becomes the -write option directly, with no need to smuggle it through an array. The effect is similar to the previous attack, particularly because the original image is usually user-controlled, so the attacker controls what gets written to the target path.
Step 3: Code injection through send
The third problem comes from the way ImageProcessing passes operations to the builder object via send(). There is no filtering to check whether the called method is a valid operation, and an attacker can use this to execute code. With the same pattern as before:
<%= image_tag user.avatar.variant(params[:t].to_s => params[:v].to_s) %>
The attacker could pass:
https://example.com/controller?t=eval&v=system("touch /tmp/hacked")
Reading it: t=eval makes the transformation name eval, and v=system("touch /tmp/hacked") makes the value a piece of Ruby code. eval is a Ruby method that runs whatever text it is given as code, and system runs an operating system command, here touch /tmp/hacked, which creates an empty file.
And the Ruby code system("touch /tmp/hacked") would be executed. The transformation name eval is dispatched through builder.send(name, argument), so the argument string is evaluated as Ruby rather than treated as an image operation.
Root cause
The chain shown here has no validation of operation names or arguments. apply in ImageProcessing calls builder.send(name, ...) with whatever name it is given, so any method reachable on the builder can be invoked, including eval. apply_operation in the processor likewise dispatches with public_send to either the processor or the accumulator without checking that the name is a known operation. MiniMagick's method_missing then deliberately converts any undefined method name into a CLI option, which is what turns an unexpected method name into an arbitrary ImageMagick flag. On top of that, array arguments are splatted into separate arguments, so a single parameter can inject multiple CLI options into a hard-coded transformation.
The documentation does not warn that passing user-supplied values to variant() or preview() is unsafe, and the report explicitly notes that the docs say nothing about it. There is no allowlist of operations in ImageProcessing, and no filtering of method names before send. An allowlist is a list of things that are permitted, with everything else refused; its absence is why any name gets through.
Impact
Vulnerable code patterns could allow the attacker to achieve RCE. The three paths differ in what they require from the application: argument injection needs a user-controlled value passed to a fixed transformation, the user-controlled transformation needs the transformation name to be attacker-chosen, and the code injection needs the same pattern but reaches Ruby's eval through send. In all cases the precondition is application code that forwards request parameters into variant() or preview() without sanitisation. Sanitisation means cleaning input so that only expected values get through. The report says vulnerable code patterns could allow the attacker to achieve RCE, and describes file write to arbitrary paths in the first two variants.
Fix
The report makes three recommendations:
- Add notes to the documentation warning developers about the dangers of passing user-supplied data to the affected methods (
variant/preview) without sanitisation. - Fix the argument injection problem.
- Implement an operations whitelist in ImageProcessing, so it will not call unexpected methods.
The report does not state which of these were adopted or what code changes were made.
Variants to test
- Array-valued parameters into a fixed transformation. Look for views that pass a request parameter straight into a named operation, as in
variant(resize: params[:new_size]). A positive result is a generatedconvertcommand in which the extra array elements appear as separate ImageMagick options, for example a-writeto a path you chose. - Attacker-chosen transformation name. Look for
variant(params[:t].to_s => params[:v].to_s)or similar hash construction from request data. A positive result is a command containing the option derived from yourtvalue, such as-write /tmp/file2.erb. - Method dispatch through
send. With the same pattern, try a transformation name that is a Ruby method rather than an image operation, such aseval, and an argument containing Ruby code. A positive result is execution of that code, for example the creation of the file named in the payload. - Other processors. The report describes the default ImageMagick/MiniMagick path. If the application uses libvips through ruby-vips, check whether the same unvalidated dispatch of operation names and arguments exists on that path; the report does not cover it.
preview()call sites. The report notes thatpreview()callsvariant()under the hood, so the same patterns should be checked wherever previews of videos or PDFs are generated from user input.
Glossary
- ActiveStorage: the part of the Ruby on Rails framework that stores and serves files uploaded by users.
- Allowlist (whitelist): a list of things that are explicitly permitted; anything not on the list is refused.
- API: the set of methods or functions a piece of software offers to programmers who use it.
- Array: an ordered list of values in programming, written with square brackets.
- Argument: a value passed to a method or command to tell it what to do.
- Argument injection: sneaking extra arguments into a command through a value the program did not expect to contain them.
- Blob: a chunk of binary data, here an uploaded file stored by ActiveStorage.
- Builder: an object that collects operations and turns them into a command.
- CLI (command line interface): a way of running programs by typing text commands rather than clicking.
- Code injection: making a program run code that the attacker supplied.
- Command line: the text interface where commands are typed.
- convert: the ImageMagick program that transforms images.
- ERB: the template format Rails uses to build web pages, mixing HTML with Ruby code.
- eval: a Ruby method that runs whatever text it is given as code.
- Gem: a reusable package of Ruby code, like a plugin.
- Gemfile: the file in a Ruby project that lists which gems it needs.
- Hash: a collection of key and value pairs, like a labelled list.
- ImageMagick: a long-standing command-line program for editing and converting images.
- ImageProcessing: a Ruby gem that builds image transformation commands for ImageMagick or libvips.
- libvips: an alternative image processing library that can be used instead of ImageMagick.
- method_missing: a Ruby hook that runs when code calls a method that does not exist.
- MiniMagick: a Ruby gem that wraps ImageMagick and builds its command line.
- Module / class: Ruby's way of grouping related code and data.
- Parameter (param): a value sent with a request, usually in the URL or a form.
- public_send / send: Ruby ways of calling a method whose name is held in a variable.
- RCE (remote code execution): running your own code on someone else's server over the network.
- Rails: a popular framework for building websites in the Ruby language.
- Ruby: the programming language Rails is written in.
- Sanitisation: cleaning input so only expected values get through.
- Splat (
*): Ruby syntax that spreads an array's elements out as separate arguments. - system: a Ruby method that runs an operating system command.
- Variant: a transformed copy of an uploaded image, such as a thumbnail.
- View: the part of a Rails app that produces the HTML sent to the browser.
- Vulnerability: a weakness in software that an attacker can use to make it behave in ways its author did not intend.