17 Янв, 2023

Методология тестирования на проникновение GraphQL

Penetration Testing as a service (PTaaS)

Tests security measures and simulates attacks to identify weaknesses.

Введение в GraphQL

GraphQL is open-source query language designed to build APIs in various languages, which become a great alternative to well established API like REST due to its ease of use. The very difference is that in GraphQL you can use single endpoint and send bunch of parameters you need in the one request which is pretty structured and flexible, while in the REST you need to send specific parameters to specific endpoints and all the dependences between them in the server may be very complicated to deal with.

From a client’s point of view, GraphQL is a unified way to access all the application’s data sources that may be written in the different languages. Server-side, GraphQL is an engine that maps the user queries to actual data in the database. It is essentially a язык запросов designed to traverse the application data graph and return the data user is asking for. For additional information about key differences between GraphQL and REST, click here.

Основные характеристики

As an API, GraphQL implements all of the CRUD functions in its own way: you read data using queries and manipulate with it through mutations. Also, you can “subscribe” to updates specific information on the server in real-time (due to WebSocket that build in GraphQL) using subscription.

In other words:

Запросы – Select Statements. Mutations – Insert/Update Statements. Subscription – Updates when a mutation happens.

GraphQL APIs are organized in terms of types and fields, not endpoints. You can access the full capabilities of all your data from a single endpoint.

GraphQL services implement a schema which is capabilities document that has a list of all the questions which the client can ask the GraphQL and set the limits of what can be answered by the GraphQL layer. Schemas and Types – Define Object Types and Fields (Object and Attributes).

Узлы – Objects with fields. Sometimes it allows us to access objects directly by ID and may cause Authorization bypass. Edges – Connections between objects that include some data. Often developers secure nodes but forget about edges!

Инструменты для использования

IDE: graphql-ide / altair-graphql-клиент / график-игровая площадка

Визуализируйте: graphql-вояджер

Обучение: graphql-github-проводник / public-graphql-api-интерфейсыпентестлаб / хакмеграф / пентестлаб

Полезный: json-to-graphql-запрос / GraphQLmap / хакерон

Перед самым началом

Look for endpoints below. Some of them may disclose sensitive information or allow to have access to the GraphQl console of the server.

The full list of endpoints:


./graphql /v1/graphql /v2/graphql
/graphql/console /v1/graphql/console /v2/graphql/console
/graphql.php /v1/graphql.php /v2/graphql.php
/graphiql /v1/graphiql /v2/graphiql
/graphiql.php /v1/graphiql.php /v2/graphiql.php
/ проводник /v1/explorer /v2/explorer
/ альтаир /v1/altair /v2/altair
/детская площадка /v1/playground /v2/playground

Также добавьте ?debug=1  к URL-адресу

Запросы на самоанализ

As a strongly typed language, GraphQL utilizes a type system: GraphQL services implement a schema which is essentially a comprehensive description of all available data and ways to interact with it: all the types, fields, API calls. That doesn’t sound like the information you would share with anybody, which brings us to the first common vulnerability.

Default configuration in GraphQL is Introspection that may let user to see all possible queries, types and so on it supports in Response body by sending special Query in Request POST body. This may lead to Information Disclosure vulnerability.

Пример кода запроса для самоанализа здесь или вы можете получить код непосредственно из graphql-вояджер для того, чтобы визуализировать зависимости между параметрами схемы нет.

Но что, если самоанализ отключен? Во-первых, некоторые запросы не могут быть отключены! Попробуйте все возможные их варианты.

Try to search for subdomains with /dev.example.com and /staging.example.com endpoints. Introspection can be disabled in production, but not in the developing stage. Also try to put all fields that logically can be in the schema and check for sensitive information in Response body. Remember that if you close enough to the right field, GraphQl will suggest the correct one (it’s a feature of Apollo server).

Note! Always watch for error messages to find sensitive/glue information inside the JSON that comes back due to GraphQL HTTP Response is always 200 OK and doesn’t have typically HTTP errors.


Since the GraphQL framework does not provide any means for securing your data (as well as Input Validation, Query Whitelisting, Rate Limiting), developers are in charge of implementing Access Control as stated in the documentation. Authorization is no built-in feature, so it’s up to developers to implements an authorization logic. By the way, Access Control and Data Disclosure are наиболее распространенные уязвимости в GraphQL.

App should be protected with an authentication middleware, but still there can be problems if specific parameters in Query fields in schema set up with protection and some of them didn’t. If so, you may modify a legitimate GraphQL query such that it returns sensitive information.

Sometimes authorization is enabled only for specific queries, but not for other API calls (especially when it’s new-build fields features).

If access control is implemented at the GraphQL layer rather than the business logic layer (according to the GraphQL recommendation) or simply implemented poorly, you might encounter vulnerabilities like IDOR.

Due to this, first you should check is bypassing Token session management (send request without it).

For example, using Burp Suite:

Another way to bypass the authentication is use nested queries as root by simply leave only nested query in the response.

Example below:

Инъекции SQL и NoSQL   

When the application doesn’t have, for example, параметризованные запросы implementation it may be vulnerable to the SQL injection attacks. GraphQL doesn’t have any input validation by itself, so it’s up to the developers to implement so. Another problem is when some variables not sanitized properly before rendering and cause to exploit even old SQL injection payloads.

An SQL database does not distinguish between authorized and unauthorized queries — it just executes them. It goes without saying consequences might be devastating: bypassing authentication, sensitive information leakage, and malicious code execution. Examples of SQL injection:

You should consider is that today’s many APIs with GraphQL are connected to MongoDB and use JSON пользовательские скалярные типы, так что вам нужно изучить внедрение NoSQL здесь. When build schema the developer should set the specific type of the query in every field (e.g., Int, Bool, String, Float, JSON etc.) and using simple scalar types not enough to fully concretize the input and output of the application. So that’s where we can try to exploit this issue.

Note! You can use tools like sqlmap to look for injection paths by saving your HTTP request with query fields to the request.txt file and test it there.

DoS - атака

Sends a costly query designed to overload the server and increases its spending on requests. A typical example of an attack would be a deep nested query. If not handled properly, such requests take forever to run and consume all the server’s computation powers, thus rendering it unresponsive for other users. Example of cycled nested queries:

Но более распространенный и удобный запрос будет поступать в форме JSON через HTTP POST-запрос, подобный этому, и здесь мы имеем дело с количеством байтов JSON, поступающих на сервер.

Инструменты безопасности GraphQL 

Setting up the testing environment.

Очень уязвимое приложение GraphQL на Kali Linux


This is the testing environment (website which is hosted locally) for practicing pentester’s skills and testing GraphQL security/scans/pentest tools. Have fun!

1. Clone the repository:

git - клон https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application

2. Open the folder with app cd Чертовски уязвимый-GraphQL-Application/ и запустить:

sudo сборка docker -t dvga .

sudo запуск docker -t -p 5013:5013 -e WEB_HOST= dvga

3. Open the browser and navigate to http://localhost:5013

Готово! Убедитесь, что все требования к приложению выполнены. Теперь мы можем протестировать все инструменты, используя http://localhost:5013



It helps you to determine endpoints on the website specific with GraphQL implementation. For example, we have example.com and search for example.com/graphql

It helps you to fingerprint the website, which is means – identifying the type and version of web server that a website is running on. Knowing this information, we can check which configurations and known vulnerabilities exist for the server and try to exploit them.

1. Clone the repository:

git - клон https://github.com/dolevf/graphw00f.git

2. Open the folder with app cd graphw00f/ and run for detection endpoints:

python3 main.py -д -т http://localhost:5013/

3. Now we can check endpoint http://localhost:5013/graphql for fingerprinting:

python3 main.py -ф -т http://localhost:5013/graphql

GraphQL Cop


It’s python utility that helps you to test common vulnerabilities in GraphQL. After results you should manually check the potential vulnerabilities, but still this tool gives you a clue for threads you should check first. Even if you don’t know the endpoint with graphql on the website, this tool will find it by itself with -f команда.

1. Clone the repository:

git - клон https://github.com/dolevf/graphql-cop

2. Open the folder with app cd graphql-cop/ and run scanner:

питон graphql-cop.py -т http://localhost:5013



Это поможет вам сделать размывание и грубое принуждение с его библиотеками (цифры, слова и т.д.) для тестирования уязвимости типа "Отказ в обслуживании" и поиска конечных точек, принятых заголовков, методов HTTP и путей.

1. Download and open folder with tool:

git - клон https://github.com/NozakiLabs/nozaki && cd нозаки

2. Install:

установка cpan Найти::Lib JSON YAML::Tiny Mojo::UserAgent

3. Example of scanning (return only 200 OK Response results):

perl nozaki.pl --url-адрес http://localhost:5013/ --возвращение 200

4. Set a specific wordlist and HTTP method:

perl nozaki.pl GET http://localhost:5013/ --возвращение 200 -список слов example.txt



It helps you to detect possible batching attack (possibility to send duplicate queries with parameters in the one query per request that cause server overloading and may increase spendings on request by server). Also, it detects if Самоанализ включен, и если подделка межсайтовых запросов это возможно.

1. Clone the repository:

git - клон https://github.com/assetnote/batchql

2. Open the folder with app cd пакетный sql / и запустить сканер:

питон batch.py -е http://localhost:5013/graphql



It helps you to use Introspection, test SQL и NoSQL injections. To test SQL/NoSQL injections you should provide any Queries from the target URL.

1. Clone the repository:

git - клон https://github.com/swisskyrepo/GraphQLmap

2. Open the folder with app cd GraphQLmap/ и установить:

sudo python setup.py установить

3. Run the scanner. Notice that URL must have /qraphql конечная точка:

graphqlmap графическая карта -у http://localhost:5013/graphql

4. print dump_via_интроспекция команда.



Полезный инструмент для brute forcing Schema когда самоанализ отключен. Если вы столкнулись с проблемами во время запуска инструмента, попробуйте установить и запустить как корень user through root terminal. Also you may face issues trying to scan localhost.

1. Install via pip:

установка pip ясновидение

2. Run the program using wordlist txt document and get JSON file with results:

python3 -m ясновидение -o результат.json http://localhost:5013/graphql

Смотрите результаты в файле JSON.



Scan GraphQL endpoints and extract Introspection Schema.

1. Clone the repository and build via docker (see in the link):

git - клон https://github.com/assetnote/batchql

2. Run the program using wordlist txt document and get JSON file with results:

проверка docker run -it shapeshifter - url http://example.com

Дополнительная информация для изучения

Прежде всего, документация!


Research on GraphQL – Study what is GraphQL


graphql-goat – Vulnerable GraphQL application to learn about GraphQL security


developer-security-training – All Labs of the Security for Developers Training


Все известные API-интерфейсы GraphQL для обучения и изучения


Репозиторий для демонстрации сообществу методов тестирования NestJS, включая модульные тесты, интеграционные тесты, тесты E2E, каналы, фильтры, перехватчики, GraphQL, Mongo, TypeORM и многое другое!


Graphql-Pentest – Some notes for graphql pentest during CTF



Системы GraphQL, как и любой другой API, подвержены широкому спектру уязвимостей. Понимание потенциальных опасностей имеет решающее значение для принятия мер, необходимых для эффективного пентестирования приложения.

Cybersecurity doesn’t have to be complicated. With Компанией CQR, you get a team of professionals to perform a complete security check of your app, whether it runs on REST, GraphQL, or any other API. Schedule a free demo today or learn more about our workflow.

Хотя мы рассмотрели некоторые из наиболее распространенных уязвимостей, существует множество других опасностей. Со временем разработчики устраняют некоторые уязвимости, в то время как новые уязвимости обнаруживаются и используются, атаки становятся более изощренными, а хакеры - более изобретательными.

Другие Услуги

Готовы к безопасности?

Связаться с нами