How to Use PowerShell for Microsoft Defender Live Response?

0
5
Asked By TechWhiz17 On

I'm trying to run Microsoft Defender Live Response using PowerShell, but I'm hitting a wall with a 401 error. I followed a guide but it seems like my access token might not have the right permissions. Here's what I've been using for my script:

```powershell
Connect-AzAccount
$accessToken = Get-AzAccessToken -ResourceUrl "https://api.securitycenter.microsoft.com" -AsSecureString
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($accessToken.Token)
$token = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)

$body = @{
Commands = @({
type = "RunScript"
params = @({
key = "Thisismyscript.ps1"
value = "Thisismyscript.ps1"
})
})
Comment = "$LiveResponseReason"
}

$jsonBody = $body | ConvertTo-Json -Depth 50
$apiUrl = "https://api.securitycenter.microsoft.com/api/machines/833hdgd673hcbdj7dbb3dcbh7hfbfb38hdd/runLiveResponse"
Invoke-RestMethod -Uri $apiUrl -Method POST -Headers @{Authorization = "Bearer $token"; "Content-Type" = "application/json"} -Body $jsonBody
```
Could anyone help me figure out why I keep getting this error?

4 Answers

Answered By CodeMaster99 On

A 401 error indicates you're unauthorized, which means the access token you're using doesn't have the proper permissions. Double-check that your account has the necessary permissions for Live Response. You can decode your token at https://jwt.ms to see what permissions it actually has.

ScriptNinja88 -

Got it! My PIM wasn't active. Now I'm hitting a 400 Bad Request instead.

Answered By PowerUser73 On

I can't run the code right now since I'm on my phone, but it looks like your script's key-value pairs might be off. In the example they mention the key should be just `ScriptName`, and the value being the actual script name. Also, ensure the machine ID is in GUID format. A good tip is to check the network tools in the browser to see how the request looks with real values.

Answered By HelpDeskHero On

p.s. If you want to format your code here better, you can copy and paste it into a PowerShell editor, indent it all, and then paste it here. It'll make it much easier to read!

Answered By HackGuru54 On

I read in the blog that the key you should use is `ScriptName`, with the value being your script's name. Now that you've tackled that 401 error, try revising your code to reflect that key name. Here’s an adjusted snippet for clarity:

```powershell
$ScriptName = 'Thisismyscript.ps1'
$apiUrl = 'https://api.securitycenter.microsoft.com/api/machines/833hdgd673hcbdj7dbb3dcbh7hfbfb38hdd/runLiveResponse'
... same rest of your code
```
Just make sure to integrate the correct key name in your parameters next time you try!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.