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.
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
azlogin#This will open the browserazlogin-u<username>-p<password>#Specify user and passwordazlogin--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 principalaz 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)azaccountget-access-token# Request access token for different resource. Supported tokens: aad-graph, arm, batch, data-lake, media, ms-graph, oss-rdbms
azaccountget-access-token--resource-typeaad-graph# If you want to configure some defaultsazconfigure# Get user logged-in alreadyazadsigned-in-usershow# Helpazfind"vm"# Find vm commandsazvm-h# Get subdomainsazaduserlist--query-examples# Get examples
Connect-AzureAD#Open browser# Using credentials$passwd =ConvertTo-SecureString"Welcome2022!"-AsPlainText -Force$creds =New-Object System.Management.Automation.PSCredential ("test@corp.onmicrosoft.com", $passwd)Connect-AzureAD-Credential $creds# Using tokens## AzureAD cannot request tokens, but can use AADGraph and MSGraph tokens to connectConnect-AzureAD-AccountId test@corp.onmicrosoft.com -AadAccessToken $token
Connect-AzAccount#Open browser# Using credentials$passwd =ConvertTo-SecureString"Welcome2022!"-AsPlainText -Force$creds =New-Object System.Management.Automation.PSCredential("test@corp.onmicrosoft.com", $passwd)Connect-AzAccount-Credential $creds# Get Access Token(Get-AzAccessToken).Token# Request access token to other endpoints: AadGraph, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, MSGraph, OperationalInsights, ResourceManager, Storage, Synapse
Get-AzAccessToken-ResourceTypeName MSGraph(Get-AzAccessToken-Resource "https://graph.microsoft.com").Token# Conenct with access tokenConnect-AzAccount-AccountId test@corp.onmicrosoft.com -AccessToken $tokenConnect-AzAccount-AccessToken $token -GraphAccessToken $graphaccesstoken -AccountId <ACCOUNT-ID>## The -AccessToken is from management.azure.com# Connect with Service principal/enterprise app secret$password =ConvertTo-SecureString'KWEFNOIRFIPMWL.--DWPNVFI._EDWWEF_ADF~SODNFBWRBIF'-AsPlainText -Force$creds =New-ObjectSystem.Management.Automation.PSCredential('2923847f-fca2-a420-df10-a01928bec653', $password)Connect-AzAccount-ServicePrincipal -Credential $creds -Tenant 29sd87e56-a192-a934-bca3-0398471ab4e7d#All the Azure AD cmdlets have the format *-AzAD*Get-Command*azad*#Cmdlets for other Azure resources have the format *Az*Get-Command*az*
# Request tokens to access endpoints# ARMcurl"$IDENTITY_ENDPOINT?resource=https://management.azure.com&api-version=2017-09-01"-Hsecret:$IDENTITY_HEADER# Vaultcurl"$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01"-Hsecret:$IDENTITY_HEADER
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 usersazaduserlist--outputtableazaduserlist--query"[].userPrincipalName"# Get info of 1 userazadusershow--id"test@corp.onmicrosoft.com"# Search "admin" usersazaduserlist--query"[].displayName"|findstr/i"admin"azaduserlist--query"[?contains(displayName,'admin')].displayName"# Search attributes containing the word "password"azaduserlist|findstr/i"password"|findstr/v"null,"# All users from AzureADazaduserlist--query"[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi==null]"azaduserlist--query"[?onPremisesSecurityIdentifier==null].displayName"# All users synced from on-premazaduserlist--query"[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi!=null]"azaduserlist--query"[?onPremisesSecurityIdentifier!=null].displayName"# Get groups where the user is a memberazaduserget-member-groups--id<email># Get roles assigned to the userazroleassignmentlist--include-groups--include-classic-administratorstrue--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 UsersGet-AzureADUser-All $trueGet-AzureADUser-All $true| select UserPrincipalName# Get info of 1 userGet-AzureADUser-ObjectId test@corp.onmicrosoft.com | fl# Search "admin" usersGet-AzureADUser-SearchString "admin"#Search admin at the begining of DisplayName or userPrincipalNameGet-AzureADUser-All $true|?{$_.Displayname-match"admin"} #Search "admin" word in DisplayName# Get all attributes of a userGet-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 AzureADGet-AzureADUser-All $true|?{$_.OnPremisesSecurityIdentifier-eq$null}# All users synced from on-premGet-AzureADUser-All $true|?{$_.OnPremisesSecurityIdentifier-ne$null}# Objects created by a/any userGet-AzureADUser [-ObjectId<email>] |Get-AzureADUserCreatedObject# Devices owned by a userGet-AzureADUserOwnedDevice-ObjectId test@corp.onmicrosoft.com# Objects owned by a specific userGet-AzureADUserOwnedObject-ObjectId test@corp.onmicrosoft.com# Get groups & roles where the user is a memberGet-AzureADUserMembership-ObjectId 'test@corp.onmicrosoft.com'# Get devices owned by a userGet-AzureADUserOwnedDevice-ObjectId test@corp.onmicrosoft.com# Get devices registered by a userGet-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:
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 usersGet-AzADUser# Get details of a userGet-AzADUser-UserPrincipalName test@defcorphq.onmicrosoft.com# Search user by stringGet-AzADUser-SearchString "admin"#Search at the beginnig of DisplayNameGet-AzADUser|?{$_.Displayname-match"admin"}# Get roles assigned to a userGet-AzRoleAssignment-SignInName test@corp.onmicrosoft.com
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:
# Enumerate groupsaz ad group listaz ad group list --query "[].[displayName]"-o table# Get info of 1 groupaz ad group show --group <group># Get "admin" groupsaz ad group list --query "[].displayName"| findstr /i "admin"az ad group list --query "[?contains(displayName,'admin')].displayName"# All groups from AzureADaz 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-premaz ad group list --query "[].{osi:onPremisesSecurityIdentifier,displayName:displayName,description:description}[?osi!=null]"
az ad group list --query "[?onPremisesSecurityIdentifier!=null].displayName"# Get members of groupaz ad group member list --group <group>--query "[].userPrincipalName"-o table# Check if member of groupaz ad group member check --group "VM Admins"--member-id <id># Get which groups a group is member ofaz 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
Enumerate users
Use tools like Azure AD Recon to gather information about users in the Azure AD tenant.
Enumerate groups
Identify Azure AD groups and their members using tools like Azure AD Recon.
Enumerate applications
Discover applications registered in Azure AD using tools like Azure AD Recon.
Exploitation
Password spraying
Perform password spraying attacks against Azure AD accounts to identify weak passwords.
Phishing attacks
Use phishing techniques to trick users into revealing their credentials, which can then be used to compromise Azure AD accounts.
Brute force attacks
Conduct brute force attacks against Azure AD authentication endpoints to guess user passwords.
Post-Exploitation
Privilege escalation
Exploit misconfigurations or vulnerabilities to escalate privileges within Azure AD.
Data exfiltration
Extract sensitive data from Azure AD, such as user information or application secrets.
Persistence
Maintain access to Azure AD by establishing backdoors or creating rogue accounts.
# Enumerate GroupsGet-AzureADGroup-All $true# Get info of 1 groupGet-AzADGroup-DisplayName <resource_group_name>| fl# Get "admin" groupsGet-AzureADGroup-SearchString "admin"| fl #Groups starting by "admin"Get-AzureADGroup-All $true|?{$_.Displayname-match"admin"} #Groups with the word "admin"# Get groups allowing dynamic membershipGet-AzureADMSGroup|?{$_.GroupTypes-eq'DynamicMembership'}# All groups that are from Azure ADGet-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 groupGet-AzureADGroupMember-ObjectId <group_id># Get roles of groupGet-AzureADMSGroup-SearchString "Contoso_Helpdesk_Administrators"#Get group idGet-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:
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 groupsGet-AzADGroup# Get details of a groupGet-AzADGroup-ObjectId <id># Search group by stringGet-AzADGroup-SearchString "admin"| fl *#Search at the beginnig of DisplayNameGet-AzADGroup|?{$_.Displayname-match"admin"}# Get members of groupGet-AzADGroupMember-GroupDisplayName <resource_group_name># Get roles of groupGet-AzRoleAssignment-ResourceGroupName <resource_group_name>
Agregar usuario a grupo
Los propietarios del grupo pueden agregar nuevos usuarios al grupo
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:
Tenga en cuenta que el Service Principal en la terminología de PowerShell se llamaEnterprise Applications en el portal de Azure (web).
# Get Service Principalsazadsplist--allazadsplist--all--query"[].[displayName]"-otable# Get details of one SPazadspshow--id00000000-0000-0000-0000-000000000000# Search SP by stringazadsplist--all--query"[?contains(displayName,'app')].displayName"# Get owner of service principalazadspownerlist--id<id>--query"[].[displayName]"-otable# Get service principals owned by the current userazadsplist--show-mine# List apps that have password credentialsazadsplist--all--query"[?passwordCredentials != null].displayName"# List apps that have key credentials (use of certificate authentication)azadsplist-all--query"[?keyCredentials != null].displayName"
Azure AD
Enumeration
Enumerate Azure AD users using tools like Azure AD Recon.
Password Spraying
Perform password spraying attacks against Azure AD using tools like Spray.
Phishing
Conduct phishing campaigns to target Azure AD users and steal their credentials.
Brute Force
Perform brute force attacks against Azure AD authentication portals to crack weak passwords.
Token Impersonation
Use stolen tokens or perform token impersonation attacks to gain unauthorized access to Azure AD resources.
Password Policies
Check Azure AD password policies to identify weak configurations that could be exploited.
Multi-Factor Authentication Bypass
Attempt to bypass multi-factor authentication controls implemented in Azure AD to gain access with only username and password.
Privilege Escalation
Exploit misconfigurations or vulnerabilities in Azure AD to escalate privileges and gain higher levels of access.
Data Exfiltration
Attempt to exfiltrate sensitive data stored in Azure AD by exploiting weaknesses in access controls or misconfigured permissions.
Account Takeover
Take over Azure AD user accounts by leveraging stolen credentials or exploiting vulnerabilities in authentication mechanisms.
Federation Attacks
Perform federation attacks to compromise trust relationships between Azure AD and other identity providers.
Insider Threats
Identify and exploit insider threats within Azure AD to gain unauthorized access to sensitive information or resources.
Monitoring Evasion
Evade detection mechanisms in Azure AD to maintain persistence and avoid being detected during attacks.
Persistence
Establish persistence mechanisms within Azure AD to maintain access even after initial compromise.
Reporting
Generate detailed reports of findings and recommendations for improving security posture in Azure AD.
Compliance Checks
Conduct compliance checks to ensure Azure AD configurations align with industry standards and best practices.
Remediation
Provide guidance on remediating identified vulnerabilities and improving overall security in Azure AD.
Training
Offer training sessions to educate Azure AD administrators and users on security best practices and threat awareness.
Documentation
Document all findings, methodologies, and outcomes of Azure AD security assessments for future reference and analysis.
# Get Service PrincipalsGet-AzureADServicePrincipal-All $true# Get details about a SPGet-AzureADServicePrincipal-ObjectId <id>| fl *# Get SP by string name or IdGet-AzureADServicePrincipal-All $true|?{$_.DisplayName-match"app"} | flGet-AzureADServicePrincipal-All $true|?{$_.AppId-match"103947652-1234-5834-103846517389"}# Get owner of SPGet-AzureADServicePrincipal-ObjectId <id>|Get-AzureADServicePrincipalOwner|fl *# Get objects owned by a SPGet-AzureADServicePrincipal-ObjectId <id>|Get-AzureADServicePrincipalOwnedObject# Get objects created by a SPGet-AzureADServicePrincipal-ObjectId <id>|Get-AzureADServicePrincipalCreatedObject# Get groups where the SP is a memberGet-AzureADServicePrincipal|Get-AzureADServicePrincipalMembershipGet-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:
Instale el módulo Az PowerShell si aún no lo ha hecho:
Install-Module-Name Az -AllowClobber -Scope CurrentUser
Inicie sesión en su cuenta de Azure utilizando el siguiente comando y siga las instrucciones en pantalla:
Connect-AzAccount
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 SPsGet-AzADServicePrincipal# Get info of 1 SPGet-AzADServicePrincipal-ObjectId <id># Search SP by stringGet-AzADServicePrincipal|?{$_.DisplayName-match"app"}# Get roles of a SPGet-AzRoleAssignment-ServicePrincipalName <String>
</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
Enumerate Azure AD users using tools like Azure AD Recon.
Password Attacks
Perform password spraying attacks against Azure AD accounts.
Phishing
Conduct phishing campaigns to target Azure AD users.
Brute Force
Perform brute force attacks against Azure AD authentication.
Token Manipulation
Manipulate Azure AD tokens to escalate privileges.
Password Policies
Identify and assess Azure AD password policies for weaknesses.
Multi-Factor Authentication (MFA) Bypass
Attempt to bypass MFA controls in Azure AD.
Account Lockout Policies
Test Azure AD account lockout policies for effectiveness.
User Impersonation
Impersonate Azure AD users to gain unauthorized access.
Federation Trust
Exploit misconfigurations in Azure AD federation trust settings.
Application Permissions
Review and analyze Azure AD application permissions for potential abuse.
Conditional Access Policies
Evaluate Azure AD conditional access policies for security gaps.
Privileged Identity Management (PIM)
Assess Azure AD PIM configurations for vulnerabilities.
Sign-In Risk Policies
Review Azure AD sign-in risk policies for weaknesses.
Security Defaults
Check Azure AD security defaults configuration for misconfigurations.
Legacy Authentication
Identify and assess risks associated with legacy authentication in Azure AD.
Guest Accounts
Review Azure AD guest accounts for security implications.
Group Membership
Enumerate Azure AD group memberships to identify potential targets.
Device Registration
Assess security risks related to Azure AD device registration.
Passwordless Authentication
Evaluate the security of Azure AD passwordless authentication methods.
Risky Sign-Ins
Monitor and investigate risky sign-ins in Azure AD for potential threats.
Insider Threats
Identify and mitigate insider threats within Azure AD environments.
Data Exfiltration
Detect and prevent data exfiltration from Azure AD environments.
Monitoring and Logging
Review Azure AD logs and monitoring settings for security insights.
Reporting
Generate reports on Azure AD security findings and recommendations.
Compliance
Ensure Azure AD security compliance with relevant standards and regulations.
Incident Response
Develop incident response procedures for Azure AD security breaches.
Training and Awareness
Provide training and awareness programs for Azure AD users on security best practices.
Secure Configuration
Implement secure configurations for Azure AD to enhance overall security posture.
Vulnerability Management
Conduct vulnerability assessments and management for Azure AD environments.
Third-Party Integrations
Assess security risks associated with third-party integrations in Azure AD.
Automation
Implement automation for routine Azure AD security tasks to improve efficiency.
Best Practices
Follow best practices for securing Azure AD environments to mitigate risks.
Collaboration
Foster collaboration between security teams and Azure AD administrators for effective security measures.
Continuous Improvement
Continuously improve Azure AD security posture through feedback and lessons learned.
Red Team Exercises
Conduct red team exercises to simulate real-world attacks and test Azure AD defenses.
Threat Intelligence
Utilize threat intelligence to enhance detection and response capabilities in Azure AD environments.
Research
Stay informed about the latest security trends and research in Azure AD security.
Community Engagement
Engage with the security community to share knowledge and insights on Azure AD security.
Legal and Ethical Considerations
Adhere to legal and ethical guidelines when performing security assessments on Azure AD.
Conclusion
Conclude security assessments with comprehensive reports and recommendations for Azure AD security enhancements.
# Get all available role templatesGet-AzureADDirectoryroleTemplate# Get enabled roles (Assigned roles)Get-AzureADDirectoryRoleGet-AzureADDirectoryRole-ObjectId <roleID>#Get info about the role# Get custom roles - use AzureAdPreviewGet-AzureADMSRoleDefinition|?{$_.IsBuiltin-eq$False} | select DisplayName# Users assigned a role (Global Administrator)Get-AzureADDirectoryRole-Filter "DisplayName eq 'Global Administrator'"|Get-AzureADDirectoryRoleMemberGet-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:
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 subscriptionGet-AzRoleDefinition# Get Role definitionGet-AzRoleDefinition-Name "Virtual Machine Command Executor"# Get roles of a user or resourceGet-AzRoleAssignment-SignInName test@corp.onmicrosoft.comGet-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 = $URIHeaders =@{'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 DevicesGet-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 devicesGet-AzureADDevice-All $true|Get-AzureADDeviceRegisteredOwnerGet-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredOwner -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}}
# Registred users of all the devicesGet-AzureADDevice-All $true|Get-AzureADDeviceRegisteredUserGet-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredUser -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}}
# Get dives managed using IntuneGet-AzureADDevice-All $true|?{$_.IsCompliant-eq"True"}# Get devices owned by a userGet-AzureADUserOwnedDevice-ObjectId test@corp.onmicrosoft.com# Get Administrative Units of a deviceGet-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 Appsazadapplistazadapplist--query"[].[displayName]"-otable# Get info of 1 Appazadappshow--id00000000-0000-0000-0000-000000000000# Search App by stringazadapplist--query"[?contains(displayName,'app')].displayName"# Get the owner of an applicationazadappownerlist--id<id>--query"[].[displayName]"-otable# List all the apps with an application passwordazadapplist--query"[?passwordCredentials != null].displayName"# List apps that have key credentials (use of certificate authentication)azadapplist--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 applicationsGet-AzureADApplication-All $true# Get details of an applicationGet-AzureADApplication-ObjectId <id>| fl *# List all the apps with an application passwordGet-AzureADApplication-All $true|%{if(Get-AzureADApplicationPasswordCredential-ObjectID $_.ObjectID){$_}}# Get owner of an applicationGet-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
Abra Az PowerShell.
Ejecute el siguiente comando para iniciar sesión en Azure AD:
Connect-AzAccount
Se le pedirá que inicie sesión a través de una ventana emergente. Ingrese sus credenciales de Azure AD.
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 AppsGet-AzADApplication# Get details of one AppGet-AzADApplication-ObjectId <id># Get App searching by stringGet-AzADApplication|?{$_.DisplayName-match"app"}# Get Apps with passwordGet-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 principaldentro 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
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
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
Enumerate Azure AD users using the Graph API:
GET https://graph.windows.net/myorganization/users?api-version=1.6
Enumerate Azure AD groups using the Graph API:
GET https://graph.windows.net/myorganization/groups?api-version=1.6
Brute Force
Brute force Azure AD accounts using the Azure AD authentication endpoint:
POST https://login.microsoftonline.com/myorganization/oauth2/token
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
Perform password spraying attacks against Azure AD accounts:
POST https://graph.windows.net/myorganization/users/{user_id}/checkMemberGroups?api-version=1.6
Perform password spraying attacks using the Azure AD authentication endpoint:
POST https://login.microsoftonline.com/myorganization/oauth2/token
Token Extraction
Extract tokens from Azure AD responses to gain unauthorized access:
POST https://graph.windows.net/myorganization/users/{user_id}/checkMemberGroups?api-version=1.6
Extract tokens from Azure AD authentication responses:
POST https://login.microsoftonline.com/myorganization/oauth2/token
Privilege Escalation
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
Escalate privileges by modifying Azure AD group membership:
# 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:
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.
El servicio utiliza algoritmos de aprendizaje automático para analizar estos datos y detectar posibles amenazas de seguridad.
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.