read

When I need quick PowerShell example to make sure I have configured the hosting/infrastructure/egress-allow correctly I use this small example.

Note: endpoint hostnames depend on your cloud. If you are in Commercial use microsoftonline.com / graph.microsoft.com; if you are in GCC High or DoD use microsoftonline.us / graph.microsoft.us.

To set it up in Azure I go to “app registrations” and click through the defaults for a new registration. I grant it directory.read.all as an app permission. Then I create a secret. You’ll see each of these configuration options in the UI for app registrations (“Certificates and Secrets” and “App Permissions”).

Then, based on this new configuration I create the three environment variables you see below, the first three things used in this small script. The hosting platform will have it’s own approach for environment variable configurations and this is a good way to test that you’ve figured it out.

# Get env variables
$TenantId = (Get-Item -Path Env:TenantId).Value
$ClientId = (Get-Item -Path Env:ClientId).Value
$ClientSecret = (Get-Item -Path Env:ClientSecret).Value

# Select cloud endpoints. Set Env:AzureCloud to either "Public" or "USGov"
$AzureCloud = (Get-Item -Path Env:AzureCloud -ErrorAction SilentlyContinue).Value
if ($AzureCloud -eq "USGov") {
    $AuthorityHost = "login.microsoftonline.us"
    $GraphHost = "graph.microsoft.us"
} else {
    $AuthorityHost = "login.microsoftonline.com"
    $GraphHost = "graph.microsoft.com"
}

# Request Body for auth
$Body = @{
    'tenant' = $TenantId
    'client_id' = $ClientId
    'scope' = "https://$GraphHost/.default"
    'client_secret' = $ClientSecret
    'grant_type' = 'client_credentials'
}

# Auth Params including request body from above. 
$Params = @{
    'Uri' = "https://$AuthorityHost/$TenantId/oauth2/v2.0/token"
    'Method' = 'Post'
    'Body' = $Body
    'ContentType' = 'application/x-www-form-urlencoded'
}

$Response = Invoke-RestMethod @Params

$Headers = @{
    'Authorization' = "Bearer $($Response.access_token)"
}

$Result = Invoke-RestMethod -Uri "https://$GraphHost/v1.0/users" -Headers $Headers

Write-Host $Result.value
Blog Logo

Chad Duffey


Published

Image

Chad Duffey

Blue Team -> Exploit Development & things in-between

Back to Overview