Learn & practice AWS Hacking:<imgsrc="../../.gitbook/assets/arte.png"alt=""data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<imgsrc="../../.gitbook/assets/arte.png"alt=""data-size="line">\
Learn & practice GCP Hacking: <imgsrc="../../.gitbook/assets/grte.png"alt=""data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<imgsrc="../../.gitbook/assets/grte.png"alt=""data-size="line">](https://training.hacktricks.xyz/courses/grte)
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
GraphQL is **highlighted** as an **efficient alternative** to REST API, offering a simplified approach for querying data from the backend. In contrast to REST, which often necessitates numerous requests across varied endpoints to gather data, GraphQL enables the fetching of all required information through a **single request**. This streamlining significantly **benefits developers** by diminishing the intricacy of their data fetching processes.
With the advent of new technologies, including GraphQL, new security vulnerabilities also emerge. A key point to note is that **GraphQL does not include authentication mechanisms by default**. It's the responsibility of developers to implement such security measures. Without proper authentication, GraphQL endpoints may expose sensitive information to unauthenticated users, posing a significant security risk.
Identifying open GraphQL instances allows for the examination of supported queries. This is crucial for understanding the data accessible through the endpoint. GraphQL's introspection system facilitates this by detailing the queries a schema supports. For more information on this, refer to the GraphQL documentation on introspection: [**GraphQL: A query language for APIs.**](https://graphql.org/learn/introspection/)
The tool [**graphw00f**](https://github.com/dolevf/graphw00f) is capable to detect wich GraphQL engine is used in a server and then prints some helpful information for the security auditor.
To check if a URL is a GraphQL service, a **universal query**, `query{__typename}`, can be sent. If the response includes `{"data": {"__typename": "Query"}}`, it confirms the URL hosts a GraphQL endpoint. This method relies on GraphQL's `__typename` field, which reveals the type of the queried object.
Graphql usually supports **GET**, **POST** (x-www-form-urlencoded) and **POST**(json). Although for security it's recommended to only allow json to prevent CSRF attacks.
#### Introspection
To use introspection to discover schema information, query the `__schema` field. This field is available on the root type of all queries.
With this query you can extract all the types, it's fields, and it's arguments (and the type of the args). This will be very useful to know how to query the database.
If introspection is enabled but the above query doesn't run, try removing the `onOperation`, `onFragment`, and `onField` directives from the query structure.
{% endhint %}
```bash
#Full introspection query
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
args {
...InputValue
}
onOperation #Often needs to be deleted to run query
onFragment #Often needs to be deleted to run query
In the introspection you can find **which object you can directly query for** (because you cannot query an object just because it exists). In the following image you can see that the "_queryType_" is called "_Query_" and that one of the fields of the "_Query_" object is "_flags_", which is also a type of object. Therefore you can query the flag object.
If these objects don't need any argument to search, could **retrieve all the information from them** just **asking** for the data you want. In this example from Internet you could extract the saved usernames and passwords:
Anyway, we already knew that, in the [Basic Enumeration](graphql.md#basic-enumeration) section a query was purposed that was showing us all the needed information: `query={__schema{types{name,fields{name, args{name,description,type{name, kind, ofType{name, kind}}}}}}}`
Note that I **discovered** that I could ask for the **parameters** "_**user**_" and "_**password**_" because if I try to look for something that doesn't exist (`query={user(uid:1){noExists}}`) I get this error:
If you can search by a string type, like: `query={theusers(description: ""){username,password}}` and you **search for an empty string** it will **dump all data**. (_Note this example isn't related with the example of the tutorials, for this example suppose you can search using "**theusers**" by a String field called "**description**"_).
In this setup, a **database** contains **persons** and **movies**. **Persons** are identified by their **email** and **name**; **movies** by their **name** and **rating**. **Persons** can be friends with each other and also have movies, indicating relationships within the database.
In the **introspection** you can find the **declared****mutations**. In the following image the "_MutationType_" is called "_Mutation_" and the "_Mutation_" object contains the names of the mutations (like "_addPerson_" in this case):
In this setup, a **database** contains **persons** and **movies**. **Persons** are identified by their **email** and **name**; **movies** by their **name** and **rating**. **Persons** can be friends with each other and also have movies, indicating relationships within the database.
Additionally, the database supports a **mutation** operation, named `addPerson`, which allows for the creation of **persons** along with their associations to existing **friends** and **movies**. It's crucial to note that the friends and movies must pre-exist in the database before linking them to the newly created person.
As explained in [**one of the vulns described in this report**](https://www.landh.tech/blog/20240304-google-hack-50000/), a directive overloading implies to call of a directive even millions of times to make the server waste operations until it's possible to DoS it.
Authentication through GraphQL API with **simultaneously sending many queries with different credentials** to check it. It’s a classic brute force attack, but now it’s possible to send more than one login/password pair per HTTP request because of the GraphQL batching feature. This approach would trick external rate monitoring applications into thinking all is well and there is no brute-forcing bot trying to guess passwords.
Below you can find the simplest demonstration of an application authentication request, with **3 different email/passwords pairs at a time**. Obviously it’s possible to send thousands in a single request in the same way:
As we can see from the response screenshot, the first and the third requests returned _null_ and reflected the corresponding information in the _error_ section. The **second mutation had the correct authentication** data and the response has the correct authentication session token.
More and more **graphql endpoints are disabling introspection**. However, the errors that graphql throws when an unexpected request is received are enough for tools like [**clairvoyance**](https://github.com/nikitastupin/clairvoyance) to recreate most part of the schema.
Moreover, the Burp Suite extension [**GraphQuail**](https://github.com/forcesunseen/graphquail) extension **observes GraphQL API requests going through Burp** and **builds** an internal GraphQL **schema** with each new query it sees. It can also expose the schema for GraphiQL and Voyager. The extension returns a fake response when it receives an introspection query. As a result, GraphQuail shows all queries, arguments, and fields available for use within the API. For more info [**check this**](https://blog.forcesunseen.com/graphql-security-testing-without-a-schema).
To bypass restrictions on introspection queries in APIs, inserting a **special character after the `__schema` keyword** proves effective. This method exploits common developer oversights in regex patterns that aim to block introspection by focusing on the `__schema` keyword. By adding characters like **spaces, new lines, and commas**, which GraphQL ignores but might not be accounted for in regex, restrictions can be circumvented. For instance, an introspection query with a newline after `__schema` may bypass such defenses:
If unsuccessful, consider alternative request methods, such as **GET requests** or **POST with `x-www-form-urlencoded`**, since restrictions may apply only to POST requests.
As mentioned in [**this talk**](https://www.youtube.com/watch?v=tIo\_t5uUK50), check if it might be possible to connect to graphQL via WebSockets as that might allow you to bypass a potential WAF and make the websocket communication leak the schema of the graphQL:
```javascript
ws = new WebSocket('wss://target/graphql', 'graphql-ws');
When introspection is disabled, examining the website's source code for preloaded queries in JavaScript libraries is a useful strategy. These queries can be found using the `Sources` tab in developer tools, providing insights into the API's schema and revealing potentially **exposed sensitive queries**. The commands to search within the developer tools are:
Therefore, as CSRF requests like the previous ones are sent **without preflight requests**, it's possible to **perform****changes** in the GraphQL abusing a CSRF.
However, note that the new default cookie value of the `samesite` flag of Chrome is `Lax`. This means that the cookie will only be sent from a third party web in GET requests.
Note that it's usually possible to send the **query****request** also as a **GET****request and the CSRF token might not being validated in a GET request.**
Also, abusing a [**XS-Search**](../../pentesting-web/xs-search/) **attack** might be possible to exfiltrate content from the GraphQL endpoint abusing the credentials of the user.
Similar to CRSF vulnerabilities abusing graphQL it's also possible to perform a **Cross-site WebSocket hijacking to abuse an authentication with GraphQL with unprotected cookies** and make a user perform unexpected actions in GraphQL.
In the below example you can see that the operation is "forgotPassword" and that it should only execute the forgotPassword query associated with it. This can be bypassed by adding a query to the end, in this case we add "register" and a user variable for the system to register as a new user.
In GraphQL, aliases are a powerful feature that allow for the **naming of properties explicitly** when making an API request. This capability is particularly useful for retrieving **multiple instances of the same type** of object within a single request. Aliases can be employed to overcome the limitation that prevents GraphQL objects from having multiple properties with the same name.
For a detailed understanding of GraphQL aliases, the following resource is recommended: [Aliases](https://portswigger.net/web-security/graphql/what-is-graphql#aliases).
While the primary purpose of aliases is to reduce the necessity for numerous API calls, an unintended use case has been identified where aliases can be leveraged to execute brute force attacks on a GraphQL endpoint. This is possible because some endpoints are protected by rate limiters designed to thwart brute force attacks by restricting the **number of HTTP requests**. However, these rate limiters might not account for the number of operations within each request. Given that aliases allow for the inclusion of multiple queries in a single HTTP request, they can circumvent such rate limiting measures.
Consider the example provided below, which illustrates how aliased queries can be used to verify the validity of store discount codes. This method could sidestep rate limiting since it compiles several queries into one HTTP request, potentially allowing for the verification of numerous discount codes simultaneously.
**Alias Overloading** is a GraphQL vulnerability where attackers overload a query with many aliases for the same field, causing the backend resolver to execute that field repeatedly. This can overwhelm server resources, leading to a **Denial of Service (DoS)**. For example, in the query below, the same field (`expensiveField`) is requested 1,000 times using aliases, forcing the backend to compute it 1,000 times, potentially exhausting CPU or memory:
{% code overflow="wrap" %}
```graphql
# Test provided by https://github.com/dolevf/graphql-cop
curl -X POST -H "Content-Type: application/json" \
To mitigate this, implement alias count limits, query complexity analysis, or rate limiting to prevent resource abuse.
### **Array-based Query Batching**
**Array-based Query Batching** is a vulnerability where a GraphQL API allows batching multiple queries in a single request, enabling an attacker to send a large number of queries simultaneously. This can overwhelm the backend by executing all the batched queries in parallel, consuming excessive resources (CPU, memory, database connections) and potentially leading to a **Denial of Service (DoS)**. If no limit exists on the number of queries in a batch, an attacker can exploit this to degrade service availability.
{% code overflow="wrap" %}
```graphql
# Test provided by https://github.com/dolevf/graphql-cop
In this example, 10 different queries are batched into one request, forcing the server to execute all of them simultaneously. If exploited with a larger batch size or computationally expensive queries, it can overload the server.
### **Directive Overloading Vulnerability**
**Directive Overloading** occurs when a GraphQL server permits queries with excessive, duplicated directives. This can overwhelm the server’s parser and executor, especially if the server repeatedly processes the same directive logic. Without proper validation or limits, an attacker can exploit this by crafting a query with numerous duplicate directives to trigger high computational or memory usage, leading to **Denial of Service (DoS)**.
{% code overflow="wrap" %}
```bash
# Test provided by https://github.com/dolevf/graphql-cop
Note that in the previous example `@aa` is a custom directive that **might not be declared**. A common directive that usually exists is **`@include`**:
You can also send an introspection query to discover all the declared directives:
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{"query": "{ __schema { directives { name locations args { name type { name kind ofType { name } } } } } }"}' \
'https://example.com/graphql'
```
And then **use some of the custom** ones.
### **Field Duplication Vulnerability**
**Field Duplication** is a vulnerability where a GraphQL server permits queries with the same field repeated excessively. This forces the server to resolve the field redundantly for every instance, consuming significant resources (CPU, memory, and database calls). An attacker can craft queries with hundreds or thousands of repeated fields, causing high load and potentially leading to a **Denial of Service (DoS)**.
```bash
# Test provided by https://github.com/dolevf/graphql-cop
curl -X POST -H "User-Agent: graphql-cop/1.13" -H "Content-Type: application/json" \
* [https://github.com/assetnote/batchql](https://github.com/assetnote/batchql): GraphQL security auditing script with a focus on performing batch GraphQL queries and mutations.
* [https://github.com/gsmith257-cyber/GraphCrawler](https://github.com/gsmith257-cyber/GraphCrawler): Toolkit that can be used to grab schemas and search for sensitive data, test authorization, brute force schemas, and find paths to a given type.
* [https://blog.doyensec.com/2020/03/26/graphql-scanner.html](https://blog.doyensec.com/2020/03/26/graphql-scanner.html): Can be used as standalone or [Burp extension](https://github.com/doyensec/inql).
* [https://github.com/swisskyrepo/GraphQLmap](https://github.com/swisskyrepo/GraphQLmap): Can be used as a CLI client also to automate attacks
* [https://gitlab.com/dee-see/graphql-path-enum](https://gitlab.com/dee-see/graphql-path-enum): Tool that lists the different ways of **reaching a given type in a GraphQL schema**.
* [https://github.com/doyensec/GQLSpection](https://github.com/doyensec/GQLSpection): The Successor of Standalone and CLI Modes os InQL
* [https://github.com/doyensec/inql](https://github.com/doyensec/inql): Burp extension for advanced GraphQL testing. The _**Scanner**_ is the core of InQL v5.0, where you can analyze a GraphQL endpoint or a local introspection schema file. It auto-generates all possible queries and mutations, organizing them into a structured view for your analysis. The _**Attacker**_ component lets you run batch GraphQL attacks, which can be useful for circumventing poorly implemented rate limits.
* [https://github.com/nikitastupin/clairvoyance](https://github.com/nikitastupin/clairvoyance): Try to get the schema even with introspection disabled by using the help of some Graphql databases that will suggest the names of mutations and parameters.
Learn & practice AWS Hacking:<imgsrc="../../.gitbook/assets/arte.png"alt=""data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<imgsrc="../../.gitbook/assets/arte.png"alt=""data-size="line">\
Learn & practice GCP Hacking: <imgsrc="../../.gitbook/assets/grte.png"alt=""data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<imgsrc="../../.gitbook/assets/grte.png"alt=""data-size="line">](https://training.hacktricks.xyz/courses/grte)
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.