Forum Discussion
Use powershell to add a tag to a MS Defender device
Thanks for the tip. I was already able to do a part of the job, which is extracting the "machineid" from Defender, with this code:
$apiUrl = "https://api-eu.securitycenter.microsoft.com/api/machines?`$filter=computerDnsName eq '$hostname'"
$response = Invoke-RestMethod -Method Get -Uri $apiUrl -Headers $headers
$machineId = $response.value[0].idAnd it's fine as I got the "machineid". But then I'm using this code for the addition of the tag.
$Tag = "tag-test"
$apiUrl = "https://api-eu.securitycenter.microsoft.com/api/machines/$machineId/tags"
$Body = @{"Value"=$Tag;"Action"="Add"}
$Body = $Body | ConvertTo-Json
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $body -Uri $apiUrlAnd I've got the error:
"code": "Unauthorized",
"message": "Invalid Authorization payload."
But on the api permissions I've added the permissions which are written on the documentation, which are "Machine.ReadWriteAll" and "Machine.ReadWrite".
Is there any way I can try to debug why doesn't this session has the permission to write the tag?
Thanks
- jbmartin6Aug 21, 2024Iron ContributorMS offers a JWT token decoder https://adfshelp.microsoft.com/JwtDecoder/GetToken
- dmarquesgnAug 21, 2024Iron Contributor
I did that and don't know how but the token issue seems that is solved. Now I've got the same piece of code but with another error, which is:
Invoke-RestMethod:
{
"error": {
"code": "InvalidRequestBody",
"message": "Request body is incorrect",
"target": "|5ca2fd80-4d6cdfba5c72ce16."
}
}But the code is just the same. The $body variable has this content:
{
"Value": "Vulnerability-Update",
"Action": "Add"
}Which is aligned with the body which is used on the API Explorer in MDE portal.
Any way to debug this?
Thanks
- jbmartin6Aug 21, 2024Iron ContributorThat's a puzzle. It should work as you describe, and that's how my code works as well. I would work through your code line by line, and replace your variables with static strings until you determine if something is altering the data in a way MDE API doesn't like.