mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-04-28 12:03:08 -07:00
Translated ['', 'src/pentesting-ci-cd/pentesting-ci-cd-methodology.md']
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Pentesting CI/CD Методологія
|
||||
# Методологія Pentesting CI/CD
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
||||
|
||||
@@ -6,51 +6,51 @@
|
||||
|
||||
## VCS
|
||||
|
||||
VCS означає **система контролю версій (Version Control System)**, ця система дозволяє розробникам **керувати своїм вихідним кодом**. Найпоширеніша — **git**, і зазвичай ви знайдете компанії, що використовують її на одній з наступних **платформ**:
|
||||
VCS означає **Version Control System**, ці системи дозволяють розробникам **керувати своїм source code**. Найпоширеніша — **git**, і зазвичай компанії використовують її на одній із таких **platforms**:
|
||||
|
||||
- Github
|
||||
- Gitlab
|
||||
- Bitbucket
|
||||
- Gitea
|
||||
- Gitblit
|
||||
- Cloud providers (they offer their own VCS platforms)
|
||||
- Cloud providers (вони пропонують власні VCS platforms)
|
||||
|
||||
|
||||
## CI/CD Pipelines
|
||||
|
||||
CI/CD pipelines дають змогу розробникам **автоматизувати виконання коду** для різних цілей — збірки, тестування та деплою додатків. Ці автоматизовані робочі процеси **тригеряться певними діями**, такими як code pushes, pull requests або заплановані завдання. Вони корисні для оптимізації процесу від розробки до продакшн.
|
||||
CI/CD pipelines дозволяють розробникам **автоматизувати виконання code** для різних цілей, зокрема build, testing і deployment applications. Ці автоматизовані workflows **запускаються певними діями**, такими як code pushes, pull requests або заплановані tasks. Вони корисні для спрощення процесу від development до production.
|
||||
|
||||
Однак такі системи потрібно **виконувати десь**, зазвичай з **привілейованими обліковими даними** для деплою коду або доступу до чутливої інформації.
|
||||
Однак ці systems потрібно **виконувати десь**, і зазвичай із **privileged credentials для deploy code або доступу до sensitive information**.
|
||||
|
||||
## VCS Pentesting Methodology
|
||||
|
||||
> [!NOTE]
|
||||
> Навіть якщо деякі VCS платформи дозволяють створювати pipelines, у цьому розділі ми будемо аналізувати лише потенційні атаки на контроль за вихідним кодом.
|
||||
> Even if some VCS platforms allow to create pipelines for this section we are going to analyze only potential attacks to the control of the source code.
|
||||
|
||||
Платформи, що містять вихідний код вашого проєкту, містять чутливу інформацію, тому потрібно дуже уважно ставитися до дозволів, наданих у цій платформі. Ось деякі поширені проблеми у VCS платформах, якими нападник може зловживати:
|
||||
Platforms, які містять source code вашого проєкту, містять sensitive information, і людям потрібно бути дуже обережними з permissions, granted inside this platform. Ось деякі поширені проблеми на VCS platforms, якими attacker could abuse:
|
||||
|
||||
- **Leaks**: Якщо ваш код містить leaks у комітах і нападник має доступ до репо (бо воно публічне або він має доступ), він може виявити ці leaks.
|
||||
- **Access**: Якщо нападник може **доступитися до акаунту на VCS платформі**, він може отримати **більшу видимість і дозволи**.
|
||||
- **Register**: Деякі платформи просто дозволяють зовнішнім користувачам створювати акаунт.
|
||||
- **SSO**: Деякі платформи не дозволяють реєстрацію, але дозволяють будь-кому зайти з валідним SSO (наприклад, нападник може використати свій github акаунт, щоб увійти).
|
||||
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... існує кілька типів токенів, які користувач може вкрасти, щоб отримати доступ до репозиторію.
|
||||
- **Webhooks**: VCS платформи дозволяють генерувати webhooks. Якщо вони **не захищені** невидимими секретами, **нападник може ними зловживати**.
|
||||
- Якщо секрету немає, нападник може зловживати webhook третьої сторони.
|
||||
- Якщо секрет знаходиться в URL, відбувається те саме і нападник також отримує секрет.
|
||||
- **Code compromise:** Якщо зловмисник має якийсь вид **write** доступу до репозиторіїв, він може спробувати **впровадити шкідливий код**. Щоб це зробити, можливо, доведеться **обійти branch protections**. Ці дії можуть виконуватися з різними цілями:
|
||||
- Скомпрометувати main branch, щоб **скомпрометувати production**.
|
||||
- Скомпрометувати main (або інші гілки), щоб **скомпрометувати машини розробників** (оскільки вони зазвичай виконують тестування, terraform чи інше в репо на своїх машинах).
|
||||
- **Compromise the pipeline** (див. наступний розділ)
|
||||
- **Leaks**: If your code contains leaks in the commits and the attacker can access the repo (because it's public or because he has access), he could discover the leaks.
|
||||
- **Access**: If an attacker can **access to an account inside the VCS platform** he could gain **more visibility and permissions**.
|
||||
- **Register**: Some platforms will just allow external users to create an account.
|
||||
- **SSO**: Some platforms won't allow users to register, but will allow anyone to access with a valid SSO (so an attacker could use his github account to enter for example).
|
||||
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... there are several kind of tokens a user could steal to access in some way a repo.
|
||||
- **Webhooks**: VCS platforms allow to generate webhooks. If they are **not protected** with non visible secrets an **attacker could abuse them**.
|
||||
- If no secret is in place, the attacker could abuse the webhook of the third party platform
|
||||
- If the secret is in the URL, the same happens and the attacker also have the secret
|
||||
- **Code compromise:** If a malicious actor has some kind of **write** access over the repos, he could try to **inject malicious code**. In order to be successful he might need to **bypass branch protections**. These actions can be performed with different goals in mid:
|
||||
- Compromise the main branch to **compromise production**.
|
||||
- Compromise the main (or other branches) to **compromise developers machines** (as they usually execute test, terraform or other things inside the repo in their machines).
|
||||
- **Compromise the pipeline** (check next section)
|
||||
|
||||
## Pipelines Pentesting Methodology
|
||||
|
||||
Найпоширеніший спосіб визначити pipeline — використовувати **CI configuration file, розміщений у репозиторії**, який будує pipeline. Цей файл описує порядок виконуваних jobs, умови, що впливають на потік, та налаштування середовища збірки.\
|
||||
Ці файли зазвичай мають послідовну назву та формат, наприклад — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), і YAML-файли GitHub Actions під .github/workflows. Після тригера job pipeline **пулить код** із вибраного джерела (наприклад, commit / branch) і **виконує команди, вказані в CI configuration file**, проти цього коду.
|
||||
The most common way to define a pipeline, is by using a **CI configuration file hosted in the repository** the pipeline builds. This file describes the order of executed jobs, conditions that affect the flow, and build environment settings.\
|
||||
These files typically have a consistent name and format, for example — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), and the GitHub Actions YAML files located under .github/workflows. When triggered, the pipeline job **pulls the code** from the selected source (e.g. commit / branch), and **runs the commands specified in the CI configuration file** against that code.
|
||||
|
||||
Отже, кінцева мета нападника — якимось чином **скомпрометувати ці конфігураційні файли** або **команди, що вони виконують**.
|
||||
Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**.
|
||||
|
||||
> [!TIP]
|
||||
> Деякі hosted builders дозволяють контриб’юторам вибирати Docker build context та Dockerfile path. Якщо контекст контролюється нападником, ви можете вказати його поза репо (наприклад, ".."), щоб інжектити файли хоста під час збірки і витягувати секрети. Див.:
|
||||
> Some hosted builders let contributors choose the Docker build context and Dockerfile path. If the context is attacker-controlled, you may set it outside the repo (e.g., "..") to ingest host files during build and exfiltrate secrets. See:
|
||||
>
|
||||
>{{#ref}}
|
||||
>docker-build-context-abuse.md
|
||||
@@ -58,57 +58,78 @@ CI/CD pipelines дають змогу розробникам **автомати
|
||||
|
||||
### PPE - Poisoned Pipeline Execution
|
||||
|
||||
Poisoned Pipeline Execution (PPE) шлях експлуатує дозволи в SCM репозиторії для маніпуляції CI pipeline та виконання шкідливих команд. Користувачі з необхідними дозволами можуть змінювати CI configuration files або інші файли, які використовуються job-ом pipeline, щоб включити шкідливі команди. Це "отруює" CI pipeline, і в результаті виконуються ці шкідливі команди.
|
||||
The Poisoned Pipeline Execution (PPE) path exploits permissions in an SCM repository to manipulate a CI pipeline and execute harmful commands. Users with the necessary permissions can modify CI configuration files or other files used by the pipeline job to include malicious commands. This "poisons" the CI pipeline, leading to the execution of these malicious commands.
|
||||
|
||||
Щоб зловмисник успішно провів PPE атаку, йому потрібно:
|
||||
For a malicious actor to be successful performing a PPE attack he needs to be able to:
|
||||
|
||||
- Мати **write access to the VCS platform**, оскільки зазвичай pipelines тригеряться при push або pull request. (Див. VCS pentesting methodology для підсумку способів отримати доступ).
|
||||
- Зверніть увагу, що іноді **external PR рахується як "write access"**.
|
||||
- Навіть якщо він має write permissions, йому потрібно переконатися, що він може **змінити CI config file або інші файли, від яких залежить конфіг**.
|
||||
- Для цього можливо доведеться **обійти branch protections**.
|
||||
- Have **write access to the VCS platform**, as usually pipelines are triggered when a push or a pull request is performed. (Check the VCS pentesting methodology for a summary of ways to get access).
|
||||
- Note that sometimes an **external PR count as "write access"**.
|
||||
- Even if he has write permissions, he needs to be sure he can **modify the CI config file or other files the config is relying on**.
|
||||
- For this, he might need to be able to **bypass branch protections**.
|
||||
|
||||
Існує 3 варіанти PPE:
|
||||
There are 3 PPE flavours:
|
||||
|
||||
- **D-PPE**: **Direct PPE** відбувається, коли актор **модифікує CI config** файл, який буде виконано.
|
||||
- **I-DDE**: **Indirect PPE** відбувається, коли актор **модифікує** файл, на який покладається CI config (наприклад make file або terraform config).
|
||||
- **Public PPE or 3PE**: Іноді pipelines можуть бути **тригеровані користувачами, які не мають write access у репо** (і навіть не є частиною org), тому що вони можуть надіслати PR.
|
||||
- **3PE Command Injection**: Зазвичай CI/CD pipelines будуть **встановлювати environment variables** з **інформацією про PR**. Якщо цим значенням може керувати нападник (наприклад, title of the PR) і воно **використовується** в **небезпечному місці** (наприклад при виконанні sh commands), нападник може **впровадити туди команди**.
|
||||
- **D-PPE**: A **Direct PPE** attack occurs when the actor **modifies the CI config** file that is going to be executed.
|
||||
- **I-DDE**: An **Indirect PPE** attack occurs when the actor **modifies** a **file** the CI config file that is going to be executed **relays on** (like a make file or a terraform config).
|
||||
- **Public PPE or 3PE**: In some cases the pipelines can be **triggered by users that doesn't have write access in the repo** (and that might not even be part of the org) because they can send a PR.
|
||||
- **3PE Command Injection**: Usually, CI/CD pipelines will **set environment variables** with **information about the PR**. If that value can be controlled by an attacker (like the title of the PR) and is **used** in a **dangerous place** (like executing **sh commands**), an attacker might **inject commands in there**.
|
||||
|
||||
### Exploitation Benefits
|
||||
|
||||
Знаючи 3 варіанти отруєння pipeline, подивимося, що може отримати нападник після успішної експлуатації:
|
||||
Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation:
|
||||
|
||||
- **Secrets**: Як було згадано раніше, pipelines потребують **привілеїв** для своїх job-ів (отримати код, зібрати його, задеплоїти...) і ці привілеї зазвичай **зберігаються в secrets**. Ці secrets зазвичай доступні через **env variables або файли всередині системи**. Тому нападник завжди намагатиметься ексфільтрувати якомога більше secrets.
|
||||
- Залежно від платформи pipeline нападник **може вимагати вказати secrets у конфігах**. Це означає, що якщо нападник не може змінити CI configuration pipeline (**I-PPE**, наприклад), він **зможе ексфільтрувати тільки ті secrets, які має цей pipeline**.
|
||||
- **Computation**: Код виконується десь; залежно від місця виконання нападник може виконати подальший pivot.
|
||||
- **On-Premises**: Якщо pipelines виконуються on-premises, нападник може опинитися в **внутрішній мережі з доступом до додаткових ресурсів**.
|
||||
- **Cloud**: Нападник може отримати доступ до **інших машин у хмарі**, а також може **ексфільтрувати** IAM roles/service accounts **tokens**, щоб отримати **додатковий доступ у cloud**.
|
||||
- **Platforms machine**: Іноді jobs виконуються всередині **машин платформи pipelines**, які зазвичай знаходяться у хмарі й мають **немає додаткових доступів**.
|
||||
- **Select it:** Іноді **платформа pipelines конфігурує кілька машин**, і якщо ви можете **змінити CI configuration file**, ви можете **вказати, де запускати шкідливий код**. У такому випадку нападник, ймовірно, запустить зворотний shell на кожній можливій машині, щоб спробувати подальшу експлуатацію.
|
||||
- **Compromise production**: Якщо ви всередині pipeline і кінцеву версію збирають і деплоять звідти, ви можете **скампрометувати код, який буде запущено у production**.
|
||||
- **Secrets**: As it was mentioned previously, pipelines require **privileges** for their jobs (retrieve the code, build it, deploy it...) and this privileges are usually **granted in secrets**. These secrets are usually accessible via **env variables or files inside the system**. Therefore an attacker will always try to exfiltrate as much secrets as possible.
|
||||
- Depending on the pipeline platform the attacker **might need to specify the secrets in the config**. This means that is the attacker cannot modify the CI configuration pipeline (**I-PPE** for example), he could **only exfiltrate the secrets that pipeline has**.
|
||||
- **Computation**: The code is executed somewhere, depending on where is executed an attacker might be able to pivot further.
|
||||
- **On-Premises**: If the pipelines are executed on premises, an attacker might end in an **internal network with access to more resources**.
|
||||
- **Cloud**: The attacker could access **other machines in the cloud** but also could **exfiltrate** IAM roles/service accounts **tokens** from it to obtain **further access inside the cloud**.
|
||||
- **Platforms machine**: Sometimes the jobs will be execute inside the **pipelines platform machines**, which usually are inside a cloud with **no more access**.
|
||||
- **Select it:** Sometimes the **pipelines platform will have configured several machines** and if you can **modify the CI configuration file** you can **indicate where you want to run the malicious code**. In this situation, an attacker will probably run a reverse shell on each possible machine to try to exploit it further.
|
||||
- **Compromise production**: If you ware inside the pipeline and the final version is built and deployed from it, you could **compromise the code that is going to end running in production**.
|
||||
|
||||
### Dependency & Registry Supply-Chain Abuse
|
||||
|
||||
Compromising a CI/CD pipeline or stealing credentials from it can let an attacker move from **pipeline execution** to **ecosystem-wide code execution** by backdooring dependencies or release tooling:
|
||||
|
||||
- **Install-time code execution via package hooks**: publish a package version that adds `preinstall`, `postinstall`, `prepare`, or similar hooks so the payload runs automatically on developer workstations and CI runners during dependency installation.
|
||||
- **Secondary execution paths**: even if targets install with `--ignore-scripts`, a malicious package can still register a **common CLI name** in the `bin` field so the attacker-controlled wrapper is symlinked into `PATH` and executes later when the command is used.
|
||||
- **Runtime bootstrapping**: a small installer can download a second runtime or toolchain during installation (for example Bun or a packed interpreter) and then launch the main payload with it, avoiding local dependency requirements.
|
||||
- **Credential harvesting from build environments**: once code runs inside CI, check environment variables, `~/.npmrc`, `~/.git-credentials`, SSH keys, cloud CLI configs, and local tooling such as `gh auth token`. On GitHub Actions, also look for runner-specific secrets and artifacts.
|
||||
- **Workflow injection with stolen GitHub tokens**: a token with **`repo` + `workflow`** permissions is enough to create a branch, commit a malicious file inside `.github/workflows/`, trigger it, collect the produced artifacts/logs, and then delete the temporary branch/workflow run to reduce traces.
|
||||
- **Wormable registry propagation**: stolen npm tokens should be validated for **publish** permissions and whether they bypass 2FA. If they do, enumerate writable packages, download their tarballs, inject a loader such as `setup.mjs`, set `preinstall` to execute it, bump the patch version, and republish. This turns one CI compromise into downstream auto-execution in other environments.
|
||||
|
||||
#### Practical checks during an assessment
|
||||
|
||||
- Review release automation for package-manager hooks added to `package.json`, unexpected `bin` entries, or version bumps that only modify the release artifact.
|
||||
- Check whether CI stores long-lived registry credentials in plaintext files such as `~/.npmrc` instead of using short-lived OIDC or trusted publishing.
|
||||
- Verify whether GitHub tokens available in CI can write workflow files or create branches/tags.
|
||||
- If a compromised package is suspected, inspect the published tarball and not only the Git repository, because the malicious loader/runtime may exist only in the published artifact.
|
||||
- Hunt for unexpected package-manager execution inside CI such as `npm install` instead of `npm ci`, unexpected Bun downloads/execution, or new workflow artifacts generated from transient branches.
|
||||
|
||||
## More relevant info
|
||||
|
||||
### Tools & CIS Benchmark
|
||||
|
||||
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) — open-source інструмент для аудиту вашого software supply chain стеку на предмет відповідності безпеці, базований на новому [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Аудит фокусується на всьому SDLC процесі, де він може виявити ризики від часу коду до часу деплою.
|
||||
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) is an open-source tool for auditing your software supply chain stack for security compliance based on a new [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). The auditing focuses on the entire SDLC process, where it can reveal risks from code time into deploy time.
|
||||
|
||||
### Top 10 CI/CD Security Risk
|
||||
|
||||
Перегляньте цікаву статтю про топ-10 CI/CD ризиків за версією Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/)
|
||||
Check this interesting article about the top 10 CI/CD risks according to Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/)
|
||||
|
||||
### Labs
|
||||
|
||||
- На кожній платформі, яку ви можете запускати локально, ви знайдете інструкцію, як запустити її локально, щоб ви могли налаштувати її на свій розсуд для тестування
|
||||
- On each platform that you can run locally you will find how to launch it locally so you can configure it as you want to test it
|
||||
- Gitea + Jenkins lab: [https://github.com/cider-security-research/cicd-goat](https://github.com/cider-security-research/cicd-goat)
|
||||
|
||||
### Automatic Tools
|
||||
|
||||
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** — інструмент статичного аналізу коду для infrastructure-as-code.
|
||||
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** is a static code analysis tool for infrastructure-as-code.
|
||||
|
||||
## References
|
||||
|
||||
- [https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm_source=github\&utm_medium=github_page\&utm_campaign=ci%2fcd%20goat_060422](https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm_source=github&utm_medium=github_page&utm_campaign=ci%2fcd%20goat_060422)
|
||||
- [The npm Threat Landscape: Attack Surface and Mitigations](https://unit42.paloaltonetworks.com/monitoring-npm-supply-chain-attacks/)
|
||||
- [Checkmarx Security Update: April 22, 2026](https://checkmarx.com/blog/checkmarx-security-update-april-22/?p=108469)
|
||||
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
||||
|
||||
Reference in New Issue
Block a user