Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/

This commit is contained in:
Translator
2024-12-31 20:42:16 +00:00
parent 4ecda9fe96
commit 92eaf7ce11
245 changed files with 9813 additions and 12533 deletions

View File

@@ -6,103 +6,99 @@
## VCS
VCS stands for **Version Control System**, this systems allows developers to **manage their source code**. The most common one is **git** and you will usually find companies using it in one of the following **platforms**:
VCS означає **Систему Контролю Версій**, ця система дозволяє розробникам **управляти своїм вихідним кодом**. Найбільш поширеною є **git**, і ви зазвичай знайдете компанії, які використовують його на одній з наступних **платформ**:
- Github
- Gitlab
- Bitbucket
- Gitea
- Cloud providers (they offer their own VCS platforms)
- Хмарні провайдери (вони пропонують свої власні платформи VCS)
## CI/CD Pipelines
CI/CD pipelines enable developers to **automate the execution of code** for various purposes, including building, testing, and deploying applications. These automated workflows are **triggered by specific actions**, such as code pushes, pull requests, or scheduled tasks. They are useful for streamlining the process from development to production.
CI/CD пайплайни дозволяють розробникам **автоматизувати виконання коду** для різних цілей, включаючи створення, тестування та розгортання додатків. Ці автоматизовані робочі процеси **ініціюються конкретними діями**, такими як пуші коду, запити на злиття або заплановані завдання. Вони корисні для спрощення процесу від розробки до виробництва.
However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**.
Однак ці системи потрібно **виконувати десь** і зазвичай з **привілейованими обліковими даними для розгортання коду або доступу до чутливої інформації**.
## VCS Pentesting Methodology
> [!NOTE]
> 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 that contains the source code of your project contains sensitive information and people need to be very careful with the permissions granted inside this platform. These are some common problems across VCS platforms that attacker could abuse:
Платформи, які містять вихідний код вашого проекту, містять чутливу інформацію, і людям потрібно бути дуже обережними з правами, наданими всередині цієї платформи. Ось деякі поширені проблеми на платформах VCS, які зловмисник може зловживати:
- **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)
- **Витоки**: Якщо ваш код містить витоки в комітах, і зловмисник може отримати доступ до репозиторію (оскільки він публічний або тому, що у нього є доступ), він може виявити витоки.
- **Доступ**: Якщо зловмисник може **отримати доступ до облікового запису всередині платформи VCS**, він може отримати **більшу видимість і права**.
- **Реєстрація**: Деякі платформи дозволяють зовнішнім користувачам створювати обліковий запис.
- **SSO**: Деякі платформи не дозволяють користувачам реєструватися, але дозволяють будь-кому отримати доступ з дійсним SSO (тому зловмисник може використовувати свій обліковий запис github для входу, наприклад).
- **Облікові дані**: Ім'я користувача + пароль, особисті токени, ssh ключі, Oauth токени, куки... є кілька видів токенів, які користувач може вкрасти, щоб отримати доступ до репозиторію.
- **Webhooks**: Платформи VCS дозволяють генерувати вебхуки. Якщо вони **не захищені** невидимими секретами, **зловмисник може зловживати ними**.
- Якщо секрет не встановлений, зловмисник може зловживати вебхуком третьої сторони.
- Якщо секрет у URL, те ж саме відбувається, і зловмисник також має секрет.
- **Компрометація коду:** Якщо зловмисник має якийсь вид **доступу на запис** до репозиторіїв, він може спробувати **впровадити шкідливий код**. Щоб досягти успіху, йому може знадобитися **обійти захист гілок**. Ці дії можуть бути виконані з різними цілями на увазі:
- Компрометація основної гілки для **компрометації виробництва**.
- Компрометація основної (або інших гілок) для **компрометації машин розробників** (оскільки вони зазвичай виконують тести, terraform або інші речі всередині репозиторію на своїх машинах).
- **Компрометація пайплайна** (перевірте наступний розділ).
## Pipelines Pentesting Methodology
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.
Найпоширеніший спосіб визначити пайплайн - це використання **файлу конфігурації CI, розміщеного в репозиторії**, який будує пайплайн. Цей файл описує порядок виконуваних завдань, умови, які впливають на потік, і налаштування середовища збірки.\
Ці файли зазвичай мають послідовну назву та формат, наприклад — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI) та YAML файли GitHub Actions, розташовані під .github/workflows. Коли пайплайн ініціюється, завдання пайплайна **витягує код** з вибраного джерела (наприклад, коміт / гілка) і **виконує команди, зазначені у файлі конфігурації CI** проти цього коду.
Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**.
Отже, остаточна мета зловмисника полягає в тому, щоб якимось чином **компрометувати ці файли конфігурації** або **команди, які вони виконують**.
### PPE - Poisoned Pipeline Execution
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.
Шлях Poisoned Pipeline Execution (PPE) експлуатує права в репозиторії SCM для маніпуляції CI пайплайном і виконання шкідливих команд. Користувачі з необхідними правами можуть змінювати файли конфігурації CI або інші файли, які використовуються завданням пайплайна, щоб включити шкідливі команди. Це "отруює" CI пайплайн, що призводить до виконання цих шкідливих команд.
For a malicious actor to be successful performing a PPE attack he needs to be able to:
Щоб зловмисник успішно виконав атаку PPE, йому потрібно:
- 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**.
- Мати **доступ на запис до платформи VCS**, оскільки зазвичай пайплайни ініціюються, коли виконується пуш або запит на злиття. (Перевірте методологію пентестингу VCS для підсумку способів отримання доступу).
- Зверніть увагу, що іноді **зовнішній PR вважається "доступом на запис"**.
- Навіть якщо у нього є права на запис, йому потрібно бути впевненим, що він може **змінити файл конфігурації CI або інші файли, на які покладається конфігурація**.
- Для цього йому може знадобитися мати можливість **обійти захист гілок**.
There are 3 PPE flavours:
Існує 3 варіанти PPE:
- **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**.
- **D-PPE**: Атака **Прямого PPE** відбувається, коли зловмисник **змінює файл конфігурації CI**, який буде виконано.
- **I-DDE**: Атака **Непрямого PPE** відбувається, коли зловмисник **змінює** **файл**, на який **покладається** файл конфігурації CI, що буде виконано (наприклад, make файл або конфігурацію terraform).
- **Public PPE або 3PE**: У деяких випадках пайплайни можуть бути **ініційовані користувачами, які не мають доступу на запис у репозиторії** (і які можуть навіть не бути частиною організації), оскільки вони можуть надіслати PR.
- **3PE Command Injection**: Зазвичай CI/CD пайплайни **встановлюють змінні середовища** з **інформацією про PR**. Якщо це значення може контролюватися зловмисником (наприклад, заголовок PR) і **використовується** в **небезпечному місці** (наприклад, виконуючи **sh команди**), зловмисник може **впроваджувати команди туди**.
### Exploitation Benefits
Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation:
Знаючи 3 варіанти отруєння пайплайна, давайте перевіримо, що зловмисник може отримати після успішної експлуатації:
- **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**.
- **Секрети**: Як вже згадувалося раніше, пайплайни вимагають **привілеїв** для своїх завдань (отримання коду, його збірка, розгортання...) і ці привілеї зазвичай **надаються в секретах**. Ці секрети зазвичай доступні через **змінні середовища або файли всередині системи**. Тому зловмисник завжди намагатиметься ексфільтрувати якомога більше секретів.
- Залежно від платформи пайплайна зловмисник **може знадобитися вказати секрети в конфігурації**. Це означає, що якщо зловмисник не може змінити конфігурацію CI пайплайна (**I-PPE**, наприклад), він може **лише ексфільтрувати секрети, які має цей пайплайн**.
- **Обчислення**: Код виконується десь, залежно від того, де він виконується, зловмисник може мати можливість подальшого переміщення.
- **On-Premises**: Якщо пайплайни виконуються на місці, зловмисник може опинитися в **внутрішній мережі з доступом до більше ресурсів**.
- **Cloud**: Зловмисник може отримати доступ до **інших машин у хмарі**, але також може **ексфільтрувати** токени IAM ролей/облікових записів **з нього**, щоб отримати **додатковий доступ всередині хмари**.
- **Платформи машини**: Іноді завдання виконуються всередині **машин платформи пайплайнів**, які зазвичай знаходяться в хмарі з **без додаткового доступу**.
- **Вибрати це:** Іноді **платформа пайплайнів має налаштовані кілька машин**, і якщо ви можете **змінити файл конфігурації CI**, ви можете **вказати, де хочете виконати шкідливий код**. У цій ситуації зловмисник, ймовірно, запустить зворотний шелл на кожній можливій машині, щоб спробувати експлуатувати її далі.
- **Компрометація виробництва**: Якщо ви знаходитесь всередині пайплайна, і фінальна версія будується та розгортається з нього, ви можете **компрометувати код, який буде виконуватися в виробництві**.
## More relevant info
### Tools & CIS Benchmark
- [**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.
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) є інструментом з відкритим кодом для аудиту вашого стеку постачання програмного забезпечення на предмет відповідності безпеці на основі нового [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Аудит зосереджується на всьому процесі SDLC, де він може виявити ризики від часу коду до часу розгортання.
### Top 10 CI/CD Security Risk
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/)
Перевірте цю цікаву статтю про топ 10 ризиків CI/CD відповідно до 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)
- На кожній платформі, яку ви можете запустити локально, ви знайдете, як запустити її локально, щоб ви могли налаштувати її так, як вам потрібно, щоб протестувати.
- Лабораторія Gitea + Jenkins: [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** is a static code analysis tool for infrastructure-as-code.
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** є інструментом статичного аналізу коду для інфраструктури як коду.
## 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)
{{#include ../banners/hacktricks-training.md}}