Disclaimer: This information is provided as-is for the benefit of the Community. Please contact Sophos Professional Services if you require assistance with your specific environment.
Also note that by using or accessing the Software below, you agree to be bound by the terms of the Sophos End User License Agreement
This is the second post in a 3 posts series covering Multi-Tenant Dashboards created using Sophos Central API's. In this post we will use the Account Health Check API and to build a Multi-Tenant Health Dashboard as shown in the screenshot above.
Steps:
The steps below should guide you through setting up your own dashboard. You yourself are responsible for setting up the webserver on which the dashboard will be hosted, I will therefore also not provide instructions on how to set up the webserver, define possible access controls, etc.
- Create a Service Principal with the Service Principal ReadOnly role (other roles can be used as well but the ReadOnly role has the least privileges). How this is done is described in Gettings Started as a Partner respectively Getting Started as an Organization. If you already created a Service Principal then you can reuse it for this dashboard as well.
- Create a html file from the code block below in a directory served by your webserver. Due to security implications we cannot use the "script" html-tag when posting code, you therefore have to replace all "s#c#r#i#p#t" entries within the file "script" when you create your html-file.
<!DOCTYPE html> <html> <head> <style> * { box-sizing: border-box; } body { font-family: Arial; margin: 0; } .header { padding: 10px; text-align: center; background: #0000FF; color: white; } h2 { margin: 0px; padding: 10px; background: #FFFFFF;} h2.center { text-align: center; } h3 { margin: 0px; } /* Flex Container */ .container { display: flex; flex-wrap: wrap; justify-content: center; background-color: #ffffff; } .container-h { width: 600px; height: 170px; background-color: #dddddd;; padding: 5px; margin: 0.5rem;} /* Details Container */ .details { display: grid; grid-template-columns: 23% 36% 36%; gap: 10px; background-color: #ffffff; padding: 1px; margin: 0px; } .tenant { padding: 10px; text-align: center; background: #dddddd; color: #000000; } /* Progress Circle */ .circle_normal { grid-row: 1 / span 2; position: relative; width: 100px; height: 100px; margin: 0.5rem; border-radius: 50%; background: conic-gradient(#FFA500 var(--percentage, 0), #00FF00 0); overflow: hidden; } .circle_snooze { grid-row: 1 / span 2; position: relative; width: 100px; height: 100px; margin: 0.5rem; border-radius: 50%; background: conic-gradient(#a7a7a5 var(--percentage, 0), #00FF00 0); overflow: hidden; } .circle_inner { display: flex; justify-content: center; align-items: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 65px; height: 65px; background: #FFF; border-radius: 50%; font-size: 1.5em; font-weight: bold;; color: rgba(0, 0, 0, 0.75); } /* Progress Bar */ .progress_boxt {height: 35px; margin-top: 10px} .progress_boxb {height: 35px; } .progress_normal { height: 10px; border-radius: 10px; background: linear-gradient(to left, #FFA500 var(--percentage, 0), #00FF00 0); } .progress_snooze { height: 10px; border-radius: 10px; background: linear-gradient(to left, #a7a7a5 var(--percentage, 0), #00FF00 0); } /* Footer */ .footer { padding: 3px; text-align: center; background: #ddd; } /* Automatically adjust for small screens */ @media screen and (max-width: 900px) { .container { flex-direction: column; }} </style> </head> <s#c#r#i#p#t src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></s#c#r#i#p#t> <s#c#r#i#p#t src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></s#c#r#i#p#t> <body> <s#c#r#i#p#t> function updatePage(dataTable) { health = '<div class="container">' // build health widget for each customer for (var i = 0; i < dataTable.length; i++) { var widget = ''; if(dataTable[i].hasOwnProperty('Name')) { widget += '<div class="container-h"><div class="tenant"><h3>' + dataTable[i].Name + '</h3></div><div class="details">'; if(dataTable[i].HOvSn == "False") { widget += '<div class="circle_normal" style="--percentage:' + (100 - dataTable[i].HOvSc) + '%;"><div class="circle_inner">' + dataTable[i].HOvSc + '</div></div>'; } else { widget += '<div class="circle_snooze" style="--percentage:' + (100 - dataTable[i].HOvSc) + '%;"><div class="circle_inner"> ' + dataTable[i].HOvSc + '</div></div>'; } if(dataTable[i].HPrSn == "False") { widget += '<div class="progress_boxt">Protection Installed<br><div class="progress_normal" style="--percentage:' + (100 - dataTable[i].HPrSc) + '%;"></div></div>'; } else { widget += '<div class="progress_boxt">Protection Installed<br><div class="progress_snooze" style="--percentage:' + (100 - dataTable[i].HPrSc) + '%;"></div></div>'; } if(dataTable[i].HTaSn == "False") { widget += '<div class="progress_boxt">Tamper Protection<br><div class="progress_normal" style="--percentage:' + (100 - dataTable[i].HTaSc) + '%;"></div></div>'; } else { widget += '<div class="progress_boxt">Tamper Protection<br><div class="progress_snooze" style="--percentage:' + (100 - dataTable[i].HTaSc) + '%;"></div></div>'; } if(dataTable[i].HPoSn == "False") { widget += '<div class="progress_boxb">Policies<br><div class="progress_normal" style="--percentage:' + (100 - dataTable[i].HPoSc) + '%;"></div></div>'; } else { widget += '<div class="progress_boxb">Policies<br><div class="progress_snooze" style="--percentage:' + (100 - dataTable[i].HPoSc) + '%;"></div></div>'; } if(dataTable[i].HExSn == "False") { widget += '<div class="progress_boxb">Exclusions<br><div class="progress_normal" style="--percentage:' + (100 - dataTable[i].HExSc) + '%;"></div></div>'; } else { widget += '<div class="progress_boxb">Exclusions<br><div class="progress_snooze" style="--percentage:' + (100 - dataTable[i].HExSc) + '%;"></div></div>'; } widget += '</div></div>' health += widget; } } health += '</div>' // update webpage $("output").html(health); } function parseHealth(url, callBack) { var lastUpdated = null; fetch(url, {method: "HEAD"}).then(r => { if(r.status === 403) { return; }; lastUpdated = r.headers.get('Last-Modified'); const formattedDate = lastUpdated.toLocaleString('en-US', { timeZoneName: 'short' }); document.getElementById("lastUpdated").innerHTML="TENANT DETAILS from " + formattedDate; Papa.parse(url+"?_="+ (new Date).getTime(), { download: true, dynamicTyping: true, header: true, complete: function(results) { // console.log(results); callBack(results.data); } }); }) } parseHealth("healthscores.csv", updatePage); setInterval(function(){ parseHealth("healthscores.csv", updatePage); }, 1800000); //refresh every 30 minutes </s#c#r#i#p#t> <!-- Header --> <div class="header"> <h1>Multi-Tenant Health Dashboard</h1> </div> <h2><div id="lastUpdated">TENANT DETAILS</div></h2> <!-- The flexible grid (content) --> <output>make sure that healthscores.csv is stored in the same directory as this page...</output> <!-- Footer --> <div class="footer"> <h4>Powered by the Account Health Check API of Sophos Central, for more info see: <a href="https://developer.sophos.com/account-health-check" target="_blank">developer.sophos.com/account-health-check</a></h4> </div> </body> </html>
Note: Do not place and run the PowerShell script in this directory! - Create a directory in which you store the Get-Central-Healthscores.ps1 from the following code block:
param ([switch] $SaveCredentials, [switch] $Export, [string] $Path = "." ) <# Description: Gather health scores for all tenants Parameters: -SaveCredentials -> will store then entered credentials locally on the PC, this is needed once -Export -> Export the results to "healtscores.csv" -Path -> Specify another directory to export to #> # Error Parser for Web Request function ParseWebError($WebError) { if ($PSVersionTable.PSVersion.Major -lt 6) { $resultStream = New-Object System.IO.StreamReader($WebError.Exception.Response.GetResponseStream()) $resultBody = $resultStream.readToEnd() | ConvertFrom-Json } else { $resultBody = $WebError.ErrorDetails | ConvertFrom-Json } if ($null -ne $resultBody.message) { return $resultBody.message } else { return $WebError.Exception.Response.StatusCode } } # Function to extract the lowest score and linked snoozed status from an array function ParseScores($Values) { $Score = 100 $Snoozed = $False Foreach ($Value in $Values) { if ($null -ne $Value) { if ($Score -gt $Value.Score) { $Score = $Value.Score $Snoozed = $Value.Snoozed } elseif (($Score -eq $Value.Score) -and ($ture -eq $Value.Snoozed)) { $Snoozed = $true } } } return @{"Score" = $Score; "Snoozed" = $Snoozed} } # Setup datatable to store health scores $HealthList = New-Object System.Data.Datatable [void]$HealthList.Columns.Add("ID") [void]$HealthList.Columns.Add("HOvSc",[int]) [void]$HealthList.Columns.Add("HOvSn",[boolean]) [void]$HealthList.Columns.Add("HPrSc",[int]) [void]$HealthList.Columns.Add("HPrSn",[boolean]) [void]$HealthList.Columns.Add("HTaSc",[int]) [void]$HealthList.Columns.Add("HTaSn",[boolean]) [void]$HealthList.Columns.Add("HPoSc",[int]) [void]$HealthList.Columns.Add("HPoSn",[boolean]) [void]$HealthList.Columns.Add("HExSc",[int]) [void]$HealthList.Columns.Add("HExSn",[boolean]) [void]$HealthList.Columns.Add("Name") $HealthView = New-Object System.Data.DataView($HealthList) Clear-Host Write-Output "===============================================================================" Write-Output "Sophos API - Get health scoures for all tenants" Write-Output "===============================================================================" # Define the filename and path for the credential file $CredentialFile = (Get-Item $PSCommandPath ).DirectoryName+"\"+(Get-Item $PSCommandPath ).BaseName+".json" # Check if Central API Credentials have been stored, if not then prompt the user to enter the credentials if (((Test-Path $CredentialFile) -eq $false) -or $SaveCredentials){ # Prompt for Credentials $clientId = Read-Host "Please Enter your Client ID" $clientSecret = Read-Host "Please Enter your Client Secret" -AsSecureString } else { # Read Credentials from JSON File $credentials = Get-Content $CredentialFile | ConvertFrom-Json $clientId = $credentials[0] $clientSecret = $credentials[1] | ConvertTo-SecureString } # We are making use of the PSCredentials object to store the API credentials # The Client Secret will be encrypted for the user excuting the script # When scheduling execution of the script remember to use the same user context $SecureCredentials = New-Object System.Management.Automation.PSCredential -ArgumentList $clientId , $clientSecret # SOPHOS OAuth URL $TokenURI = "https://id.sophos.com/api/v2/oauth2/token" # TokenRequestBody for oAuth2 $TokenRequestBody = @{ "grant_type" = "client_credentials"; "client_id" = $SecureCredentials.GetNetworkCredential().Username; "client_secret" = $SecureCredentials.GetNetworkCredential().Password; "scope" = "token"; } $TokenRequestHeaders = @{ "content-type" = "application/x-www-form-urlencoded"; } # Set TLS Version [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Post Request to SOPHOS for OAuth2 token try { $APIAuthResult = (Invoke-RestMethod -Method Post -Uri $TokenURI -Body $TokenRequestBody -Headers $TokenRequestHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError) if ($SaveCredentials) { $clientSecret = $clientSecret | ConvertFrom-SecureString ConvertTo-Json $ClientID, $ClientSecret | Out-File $CredentialFile -Force } } catch { # If there's an error requesting the token, say so, display the error, and break: Write-Output "" Write-Output "AUTHENTICATION FAILED - Unable to retreive SOPHOS API Authentication Token" Write-Output "Please verify the credentials used!" Write-Output "" Write-Output "If you are working with saved credentials then you can reset them by calling" Write-Output "this script with the -SaveCredentials parameter" Write-Output "" Read-Host -Prompt "Press ENTER to continue..." Break } # Set the Token for use later on: $Token = $APIAuthResult.access_token # SOPHOS Whoami URI: $WhoamiURI = "https://api.central.sophos.com/whoami/v1" # SOPHOS Whoami Headers: $WhoamiRequestHeaders = @{ "Content-Type" = "application/json"; "Authorization" = "Bearer $Token"; } # Post Request to SOPHOS for Whoami Details: $WhoamiResult = (Invoke-RestMethod -Method Get -Uri $WhoamiURI -Headers $WhoamiRequestHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError) # Save Response details $WhoamiID = $WhoamiResult.id $WhoamiType = $WhoamiResult.idType # Check if we are using partner/organization credentials if (-not (($WhoamiType -eq "partner") -or ($WhoamiType -eq "organization"))) { Write-Output "Aborting script - idType does not match partner or organization!" Break } # SOPHOS Partner/Organization API Headers: if ($WhoamiType -eq "partner") { $GetTenantsHeaders = @{ "Authorization" = "Bearer $Token"; "X-Partner-ID" = "$WhoamiID"; } } else { $GetTenantsHeaders = @{ "Authorization" = "Bearer $Token"; "X-Organization-ID" = "$WhoamiID"; } } # Get all Tenants Write-Host ("Checking:") $GetTenantsPage = 1 do { if ($WhoamiType -eq "partner") { $GetTenants = (Invoke-RestMethod -Method Get -Uri "https://api.central.sophos.com/partner/v1/tenants?pageTotal=true&pageSize=100&page=$GetTenantsPage" -Headers $GetTenantsHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError) } else { $GetTenants = (Invoke-RestMethod -Method Get -Uri "https://api.central.sophos.com/organization/v1/tenants?pageTotal=true&pageSize=100&page=$GetTenantsPage" -Headers $GetTenantsHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError) } foreach ($Tenant in $GetTenants.items) { # Codepage stuff to ensure that powershell displays those nasty Umlauts and other special characters correctly $ShowAs = $Tenant.showAs $ShowAs = [System.Text.Encoding]::GetEncoding(28591).GetBytes($ShowAs) $ShowAs = [System.Text.Encoding]::UTF8.GetString($ShowAs) Write-Host ("+- $($ShowAs)... $(" " * 75)".Substring(0,75)) $TenantID = $Tenant.id $TenantDataRegion = $Tenant.apiHost # SOPHOS Endpoint API Headers: $TenantHeaders = @{ "Authorization" = "Bearer $Token"; "X-Tenant-ID" = "$TenantID"; "Content-Type" = "application/json"; } # Check Protection Status using the Health Check API if (-not $null -eq $TenantDataRegion) { try { $HealthCheck = (Invoke-RestMethod -Method Get -Uri $TenantDataRegion"/account-health-check/v1/health-check" -Headers $TenantHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError) $HPR = ParseScores ($HealthCheck.Endpoint.Protection.Computer,$HealthCheck.Endpoint.Protection.Server) $HTA = ParseScores ($HealthCheck.Endpoint.TamperProtection.Computer, $HealthCheck.Endpoint.TamperProtection.Server, $HealthCheck.Endpoint.TamperProtection.GlobalDetail) $HPO = ParseScores ($HealthCheck.Endpoint.Policy.Computer."threat-protection", $HealthCheck.Endpoint.Policy.Server."server-threat-protection") $HEX = ParseScores ($HealthCheck.Endpoint.Exclusions.Global, $HealthCheck.Endpoint.Exclusions.Policy.Computer, $HealthCheck.Endpoint.Exclusions.Policy.Server) $HOV = ParseScores ($HPR, $HTA, $HPO, $HEX) [void]$HealthList.Rows.Add($Tenant.id, $HOV.Score, $HOV.Snoozed, $HPR.Score, $HPR.Snoozed, $HTA.Score, $HTA.Snoozed, $HPO.Score, $HPO.Snoozed, $HEX.Score, $HEX.Snoozed, $ShowAs) Write-Host (" --> Health Score: $($HOV.Score) - Snoozed: $($HOV.Snoozed)") } catch { # Something went wrong, get error details... $WebError = ParseWebError($_) Write-Host " --> $($WebError)" } } else { Write-Host (" --> Account not activated") } Start-Sleep -Milliseconds 50 # Slow down processing to prevent hitting the API rate limit } $GetTenantsPage++ } while ($GetTenantsPage -le $GetTenants.pages.total) Write-Output "===============================================================================" Write-Output "Check completed!" Write-Output "===============================================================================" if ($Export) { Write-Host "" Write-Host "The health scores were saved to the following file:" Write-Host "$($Path)\healthscores.csv" $HealthList.Select("", "HOvSc ASC, Name ASC") | Export-Csv $Path"\healthscores.csv" -Encoding UTF8 -NoTypeInformation } else { Write-Host "Results:" $HealthList.Select("", "HOvSc ASC, Name ASC") | Format-Table Name,HOvSc,HOvSn,HPrSc,HTaSc,HPoSc,HExSc }
- Now that everything is prepared, we are going to run our PowerShell script for the first time with the parameter -SaveCredentials. This parameter stores the credentials of our Service Principal in a JSON-file, we do this so that we do not have to enter these credentials every time we run the script, for example:
C:\Dashboards\Get-Central-HealthScores.ps1 -SaveCredentials
This will scan all tenants linked to your partner or organization account, during the scan it will display the tenant name and whether the health score could be retrieved successfully. - From this point on you should call the PowerShell script without the -SaveCredentials parameter (unless your credentials are no longer valid, and you need to update them).
- For the next step we need to run the PowerShell script with the following parameters:
-Export -Path <path where to store the healthscores.csv file> for example:
C:\Dashboards\Get-Central-HealthScores.ps1 -Export C:\Dashboards\wwwroot
If you now check the webpage in your browser, just remember that the healtscores.csv file needs to be stored in the same directory, then you should see the dashboard populated with the data from the CSV-File. - Now that we have verified that everything works the only thing left is to schedule the PowerShell script with the -Export parameter on a regular basis. Under Windows you could for example use the Windows Task Scheduler.
I hope that you found the information in this recommended read post useful. If you did then please klick the like button on the right.
If you have not done so I recommend that you have a look at the other two posts in this series as well:
- Building Multi-Tenant Dashboards with Sophos Central API’s - Part 1: Detections
- Building Multi-Tenant Dashboards with Sophos Central API’s - Part 3: Cases
PS. The PowerShell script included in this post was used with PowerShell 5.1 on Windows and PowerShell 7.4 on Linux.
Updated links to Part 1 & 3 of the series
[edited by: Marcel at 11:06 AM (GMT -7) on 2 Jul 2024]