Методологія тестування на проникнення 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:
https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/graphql.txt
| ./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-вояджер для того, щоб візуалізувати залежності між параметрами схеми немає.
Але що, якщо самоаналіз відключений? По-перше, деякі запити не можуть бути відключені! Спробуйте всі можливі їх варіанти.
Спробуйте виконати пошук піддоменів з допомогою /dev.example.com і /staging.example.com кінцеві точки. Самоаналіз можна відключити в процесі виробництва, але не на стадії розробки. Також спробуйте помістити всі поля, які логічно можуть бути в схемі, і перевірити наявність конфіденційної інформації в тілі відповіді. Пам'ятайте, що якщо ви досить близько підійдете до потрібного поля, GraphQL запропонує правильне (це особливість 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.
Авторизація
Оскільки платформа GraphQL не надає ніяких засобів для захисту ваших даних (а також перевірки вхідних даних, внесення в білий список запитів, обмеження швидкості), розробники відповідають за реалізацію контролю доступу, як зазначено в документації. Авторизація не є вбудованою функцією, тому логіка авторизації повинна бути реалізована розробниками. До речі, контроль доступу і розкриття даних найбільш поширені уразливості у 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.
Іноді авторизація включена тільки для визначених запитів, але не для інших викликів API (особливо коли мова йде про нові функції полів складання).
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).
Наприклад, з допомогою Burp Suite:

Інший спосіб обійти аутентифікацію - використовувати вкладені запити в якості кореневих, просто залишивши у відповіді тільки вкладений запит.
Example below:

Ін'єкції SQL та NoSQL
When the application doesn’t have, for example, параметризрвані запити реалізація він може бути уразливим для атак з використанням SQL-ін'єкцій. GraphQL сам по собі не має ніякої перевірки вхідних даних, так що це залежить від розробників. Інша проблема полягає в тому, що деякі змінні не очищається належним чином перед рендерингом і призводять до використання навіть старих корисних навантажень SQL-ін'єкцій.
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.
Зверніть увагу! Ви можете використовувати такі інструменти, як sqlmap, для пошуку шляхів впровадження, зберігши свій HTTP-запит з полями запиту request.txt запишіть і протестуйте його там.
DoS - атака
Відправляє дорогий запит, призначений для перевантаження сервера і збільшення його витрат на запити. Типовим прикладом атаки може бути глибоко вкладений запит. При неправильній обробці такі запити виконуються цілу вічність і споживають всі обчислювальні потужності сервера, що робить його несприйнятливим до іншим користувачам. Приклад циклічних вкладених запитів:

Але більш поширений і зручний запит буде надходити у формі JSON через HTTP POST-запит, подібний до цього, і тут ми маємо справу з кількістю байтів JSON, що надходять на сервер.

Інструменти безпеки GraphQL
Налаштування середовища тестування.
• Чертовски вразливе додаток GraphQL на Kali Linux
https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application
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. Клонуйте репозиторій:
git - клон https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application
2. Відкрийте папку з додатком cd Чертовски уразливий-GraphQL-Application/ і запустити:
sudo збірка docker -t dvga .
sudo запуск docker -t -p 5013:5013 -e WEB_HOST=0.0.0.0 dvga
3. Відкрийте браузер і перейдіть до http://localhost:5013
Готово! Переконайтеся, що всі вимоги до додатка виконані. Тепер ми можемо протестувати всі інструменти, використовуючи http://localhost:5013

• graphw00f
https://github.com/dolevf/graphw00f
Це допоможе вам визначити кінцеві точки на веб-сайті, специфічні для реалізації GraphQL. Наприклад, у нас є example.com і шукати example.com/graphql
Це допоможе вам ідентифікувати веб–сайт за відбитками пальців, тобто визначити тип і версію веб-сервера, на якому працює веб-сайт. Знаючи цю інформацію, ми можемо перевірити, які конфігурації і відомі уразливості існують для сервера, і спробувати їх використовувати.
1. Клонуйте репозиторій:
git - клон https://github.com/dolevf/graphw00f.git
2. Відкрийте папку з додатком cd graphw00f/ і виконати пошук кінцевих точок виявлення:
python3 main.py -д -т http://localhost:5013/
3. Тепер ми можемо перевірити кінцеву точку http://localhost:5013/graphql для зняття відбитків пальців:
python3 main.py -ф -т http://localhost:5013/graphql
• GraphQL Cop
https://github.com/dolevf/graphql-cop
Це утиліта python, яка допомагає вам тестувати поширені уразливості в GraphQL. Після отримання результатів ви повинні вручну перевірити потенційні уразливості, але все ж цей інструмент дає вам підказку для потоків, які ви повинні перевірити в першу чергу. Навіть якщо ви не знаєте кінцеву точку з допомогою graphql на веб-сайті, цей інструмент знайде її сам з допомогою -f команда.
1. Клонуйте репозиторій:
git - клон https://github.com/dolevf/graphql-cop
2. Відкрийте папку з додатком cd graphql-cop/ і запустіть сканер:
пітон graphql-cop.py -т http://localhost:5013
• Nozaki
https://github.com/htrgouvea/nozaki
Це допоможе вам зробити розмивання и грубий примус з його бібліотеками (цифри, слова і т. д.) для тестування уразливості типу "Відмова в обслуговуванні" і пошуку кінцевих точок, прийнятих заголовків, HTTP методів і шляхів.
1. Завантажте і відкрийте папку за допомогою інструменту:
git - клон https://github.com/NozakiLabs/nozaki && cd нозаки
2. Встановіть:
установка cpan Знайти::Lib JSON YAML::Tiny Mojo::UserAgent
3. Приклад сканування (повертає тільки 200 результатів відповіді ОК):
perl nozaki.pl --url-адресу http://localhost:5013/ --повернення 200
4. Задайте конкретний список слів і метод HTTP.:
perl nozaki.pl -м GET -у http://localhost:5013/ --повернення 200 -список слів example.txt
• BatchQL
https://github.com/assetnote/batchql
Це допоможе вам виявити можливу пакетну атаку (можливість відправки повторюваних запитів з параметрами в одному запиті на запит, що призводить до перевантаження сервера і може збільшити витрати на запит сервером). Крім того, він визначає, якщо Самоаналіз увімкнено, якщо підробка міжсайтових запитів це можливо.
1. Клонуйте репозиторій:
git - клон https://github.com/assetnote/batchql
2. Відкрийте папку з додатком cd пакетний sql / і запустити сканер:
пітон batch.py -е http://localhost:5013/graphql
• GraphQLmap
https://github.com/swisskyrepo/GraphQLmap
Це допоможе вам використовувати самоаналіз, тест SQL и NoSQL ін'єкції. Щоб протестувати ін'єкції SQL / NoSQL, ви повинні надати будь-які запити цільової URL-адреси.
1. Клонуйте репозиторій:
git - клон https://github.com/swisskyrepo/GraphQLmap
2. Відкрийте папку з додатком cd GraphQLmap/ та встановити:
sudo python setup.py встановити
3. Запустіть сканер. Зверніть увагу, що URL-адресу повинен мати /qraphql кінцева точка:
graphqlmap графічна карта -у http://localhost:5013/graphql
4. друк dump_via_интроспекция команда.
• Clairvoyance
https://github.com/nikitastupin/clairvoyance
Корисний інструмент для грубий примус Схема коли самоаналіз відключений. Якщо ви зіткнулися з проблемами під час запуску інструменту, спробуйте встановити і запустити як корінь користувач через кореневий термінал. Також ви можете зіткнутися з проблемами при спробі сканування локального хостингу.
1. Установка через pip:
установка pip ясновидіння
2. Запустіть програму, використовуючи текстовий документ wordlist, і отримаєте файл JSON з результатами:
python3 -m ясновидіння -o результат.json http://localhost:5013/graphql
Дивіться результати у файлі JSON.
• ShapeShifter
https://github.com/szski/shapeshifter
Сканування кінцевих точок GraphQL і витяг Схема самоаналізу.
1. Клонуйте репозиторій і створіть його з допомогою docker (див. Посилання).:
git - клон https://github.com/assetnote/batchql
2. Запустіть програму, використовуючи текстовий документ wordlist, і отримаєте файл JSON з результатами:
перевірка docker run -it shapeshifter - url http://example.com
Додаткова інформація для вивчення
• Насамперед, документація!
• Research on GraphQL – Study what is GraphQL
https://github.com/righettod/poc-graphql
• graphql-goat – Vulnerable GraphQL application to learn about GraphQL security
https://github.com/amanvir/graphql-goat
• developer-security-training – All Labs of the Security for Developers Training
https://github.com/NovatecConsulting/developer-security-training
• Всі відомі API-інтерфейси GraphQL для навчання та вивчення
https://github.com/IvanGoncharov/graphql-apis
• Сховище для демонстрації спільноти методів тестування NestJS, включаючи модульні тести, інтеграційні тести, тести E2E, канали, фільтри, перехоплювачі, GraphQL, Mongo, TypeORM і багато іншого!
https://github.com/jmcdo29/testing-nestjs
• Graphql-Pentest – Some notes for graphql pentest during CTF
https://github.com/robyfirnandoyusuf/Graphql-Pentest
Висновок
Системи 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.
Хоча ми розглянули деякі з найбільш поширених вразливостей, існує безліч інших небезпек. З часом розробники усувають деякі уразливості, в те час як нові уразливості виявляються і використовуються, атаки стають більш витонченими, а хакери - більш винахідливими.
Інші Послуги
Insomnia Security Scanner
AI-powered web application security scanner by CQR. Automated vulnerability discovery, exploit verification, and detailed reporting for modern applications.
Дізнатися більшеЗахист інфраструктури CRYEYE
Аудит безпеки за допомогою CryEye забезпечує інформаційну безпеку підприємства, захищаючи всю інфраструктуру.
Дізнатися більшеТестування на проникнення
Знайдіть вразливості у всій інфраструктурі вашого бізнесу раніше, ніж це зроблять хакери! У межах консалтингу з тестування на проникнення ми підберемо методи пентестів та інші індивідуальні рекомендації з кібербезпеки для вашого бізнесу.
Дізнатися більшеСоціальна Інженерія
Simulate real-world phishing, vishing, and pretexting attacks to measure and improve your team's security awareness and response capabilities.
Дізнатися більшеТестування Продуктивності
Усі види тестування навантаження і продуктивності вашої системи від компанії CQR, що спеціалізується на онлайн-безпеці.
Дізнатися більшеAI-Powered Vulnerability Assessment
Leverage artificial intelligence to discover, prioritize, and remediate vulnerabilities across your digital assets faster and more accurately than traditional scanners.
Дізнатися більшеCloud Security Audit (AWS / GCP / Azure)
Comprehensive security review of your cloud environments — IAM policies, network controls, data exposure, and misconfigurations across all major cloud platforms.
Дізнатися більшеDevSecOps Integration
Embed security into every stage of your CI/CD pipeline. Automated SAST, DAST, SCA, and secret scanning so vulnerabilities are caught before they reach production.
Дізнатися більшеAPI Security Testing
In-depth testing of REST, GraphQL, and SOAP APIs for authentication flaws, authorization bypasses, injection vulnerabilities, and data leakage risks.
Дізнатися більшеMobile Application Penetration Testing
Manual and automated security testing for iOS and Android applications — reverse engineering, runtime analysis, traffic interception, and backend API assessment.
Дізнатися більшеIoT Security Assessment
Evaluate firmware, communication protocols, cloud backends, and physical interfaces of IoT devices to identify vulnerabilities before attackers do.
Дізнатися більшеBlockchain & Smart Contract Audit
Formal verification and manual code review of smart contracts on Ethereum, Solana, and other chains. Detect reentrancy, overflow, and logic flaws before deployment.
Дізнатися більшеRed Team Operations
Advanced adversary simulation using real attacker TTPs (MITRE ATT&CK) to test your detection, response, and overall security posture under realistic conditions.
Дізнатися більшеThreat Intelligence & Monitoring
Continuous monitoring of threat feeds, dark web, and attacker infrastructure to provide actionable intelligence specific to your organization and industry.
Дізнатися більшеZero Trust Architecture Review
Assess and design your Zero Trust security model — identity verification, micro-segmentation, least-privilege access, and continuous validation controls.
Дізнатися більшеCompliance Consulting (PCI DSS / SOC 2 / GDPR)
Expert guidance to achieve and maintain compliance with major security frameworks. Gap analysis, remediation roadmaps, and audit-readiness support.
Дізнатися більшеDark Web Monitoring
Continuous surveillance of dark web forums, marketplaces, and breach databases for leaked credentials, sensitive data, or mentions of your organization.
Дізнатися більшеPhishing Simulation & Awareness Training
Controlled phishing campaigns combined with interactive security awareness training to build a human firewall across your entire organization.
Дізнатися більшеSupply Chain Security Audit
Assess third-party vendor risks, open-source dependencies, and software supply chain integrity to prevent attacks like SolarWinds and Log4Shell.
Дізнатися більшеContainer & Kubernetes Security
Security review of Docker images, Kubernetes clusters, RBAC policies, network policies, and runtime configurations to harden your container infrastructure.
Дізнатися більшеWeb Application Firewall (WAF) Deployment
Professional WAF setup, rule tuning, and ongoing management to block SQL injection, XSS, CSRF, and other OWASP Top 10 threats in real time.
Дізнатися більшеBug Bounty Program Management
Full lifecycle management of your bug bounty program — scope definition, researcher coordination, triage, validation, and remediation tracking.
Дізнатися більшеOSINT Investigation Services
Open-source intelligence gathering on individuals, organizations, and infrastructure. Ideal for pre-engagement recon, fraud investigation, and competitive analysis.
Дізнатися більшеDigital Forensics & Incident Response
Rapid response to security breaches — evidence collection, malware analysis, attacker timeline reconstruction, and actionable remediation recommendations.
Дізнатися більше