From 0d08106c76c3b8e2c2cd663de8e47beba54fa6e9 Mon Sep 17 00:00:00 2001 From: JesseEsquivel <33558203+JesseEsquivel@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:33:12 -0400 Subject: [PATCH] Update pull-alerts-using-rest-api.md Add PowerShell and Bash samples for testing the MDATP SIEM API. --- .../pull-alerts-using-rest-api.md | 101 +++++++++++++++++- 1 file changed, 98 insertions(+), 3 deletions(-) diff --git a/windows/security/threat-protection/microsoft-defender-atp/pull-alerts-using-rest-api.md b/windows/security/threat-protection/microsoft-defender-atp/pull-alerts-using-rest-api.md index e52e94be42..f2c30ec2e4 100644 --- a/windows/security/threat-protection/microsoft-defender-atp/pull-alerts-using-rest-api.md +++ b/windows/security/threat-protection/microsoft-defender-atp/pull-alerts-using-rest-api.md @@ -175,7 +175,7 @@ Here is an example return value: ## Code examples ### Get access token -The following code example demonstrates how to obtain an access token and call the Microsoft Defender ATP API. +The following code examples demonstrate how to obtain an access token for calling the Microsoft Defender ATP SIEM API. ```csharp AuthenticationContext context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId)); @@ -183,19 +183,114 @@ ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret AuthenticationResult authenticationResult = context.AcquireTokenAsync(detectionsResource, clientCredentials).GetAwaiter().GetResult(); ``` -### Use token to connect to the detections endpoint +```PowerShell +#Get current working directory +$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent +#Paste below your Tenant ID, App ID and App Secret (App key). +$tenantId = '' ### Paste your tenant ID here +$appId = '' ### Paste your Application ID here +$appSecret = '' ### Paste your Application secret here + +$resourceAppIdUri = 'https://graph.windows.net' +$oAuthUri = "https://login.windows.net/$tenantId/oauth2/token" +$authBody = [Ordered] @{ + resource = "$resourceAppIdUri" + client_id = "$appId" + client_secret = "$appSecret" + grant_type = 'client_credentials' +} + +#call API +$authResponse = Invoke-RestMethod -Method Post -Uri $oAuthUri -Body $authBody -ErrorAction Stop +$authResponse +Out-File -FilePath "$scriptDir\LatestSIEM-token.txt" -InputObject $authResponse.access_token ``` + +```Bash +tenantId='' ### Paste your tenant ID here +appId='' ### Paste your Application ID here +appSecret='' ### Paste your Application secret here +resourceAppIdUri='https://graph.windows.net' +oAuthUri="https://login.windows.net/$tenantId/oauth2/token" +scriptDir=$(pwd) + +apiResponse=$(curl -s X POST "$oAuthUri" -d "resource=$resourceAppIdUri&client_id=$appId&client_secret=$appSecret&\ + grant_type=client_credentials" | cut -d "{" -f2 | cut -d "}" -f1) +IFS="," +apiResponseArr=($apiResponse) +IFS=":" +tokenArr=(${apiResponseArr[6]}) +echo ${tokenArr[1]} | cut -d "\"" -f2 | cut -d "\"" -f1 >> $scriptDir/LatestSIEM-token.txt +``` + +### Use token to connect to the detections endpoint +The following code examples demonstrate how to use an access token for calling the Microsoft Defender ATP SIEM API to get alerts. + +```csharp HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authenticationResult.AccessTokenType, authenticationResult.AccessToken); HttpResponseMessage response = httpClient.GetAsync("https://wdatp-alertexporter-eu.windows.com/api/alert").GetAwaiter().GetResult(); string detectionsJson = response.Content.ReadAsStringAsync().Result; Console.WriteLine("Got detections list: {0}", detectionsJson); - ``` +```PowerShell +#Get current working directory +$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent +#run the script Get-Token.ps1 - make sure you are running this script from the same folder of Get-SIEMToken.ps1 +$token = Get-Content "$scriptDir\LatestSIEM-token.txt" +#Get Alert from the last xx hours 200 in this example. Make sure you have alerts in that time frame. +$dateTime = (Get-Date).ToUniversalTime().AddHours(-200).ToString("o") + +#test SIEM API +$url = 'https://wdatp-alertexporter-us.windows.com/api/alerts?limit=20&sinceTimeUtc=2020-01-01T00:00:00.000' + +#Set the WebRequest headers +$headers = @{ + 'Content-Type' = 'application/json' + Accept = 'application/json' + Authorization = "Bearer $token" +} + +#Send the webrequest and get the results. +$response = Invoke-WebRequest -Method Get -Uri $url -Headers $headers -ErrorAction Stop +$response +Write-Host + +#Extract the alerts from the results. This works for SIEM API: +$alerts = $response.Content | ConvertFrom-Json | ConvertTo-Json + +#Get string with the execution time. We concatenate that string to the output file to avoid overwrite the file +$dateTimeForFileName = Get-Date -Format o | foreach {$_ -replace ":", "."} + +#Save the result as json and as csv +$outputJsonPath = "$scriptDir\Latest Alerts $dateTimeForFileName.json" +$outputCsvPath = "$scriptDir\Latest Alerts $dateTimeForFileName.csv" + +Out-File -FilePath $outputJsonPath -InputObject $alerts +Get-Content -Path $outputJsonPath -Raw | ConvertFrom-Json | Select-Object -ExpandProperty value | Export-CSV $outputCsvPath -NoTypeInformation +``` + +```Bash +#Get current working directory +scriptDir=$(pwd) + +#get the token +token=$(<$scriptDir/LatestSIEM-token.txt) + +#test the SIEM API, get alerts since 1/1/2020 +url='https://wdatp-alertexporter-us.windows.com/api/alerts?limit=20&sinceTimeUtc=2020-01-01T00:00:00.000' + +#send web requst to API and echo JSON content +apiResponse=$(curl -s X GET "$url" -H "Content-Type: application/json" -H "Accept: application/json"\ + -H "Authorization: Bearer $token" | cut -d "[" -f2 | cut -d "]" -f1) +echo "If you see Alert info in JSON format, congratulations you accessed the MDATP SIEM API!" +echo +echo $apiResponse +``` ## Error codes The Microsoft Defender ATP REST API returns the following error codes caused by an invalid request.