Building Multi-Tenant Dashboards with Sophos Central API’s - Part 3: Cases

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 final post in a 3 posts series covering Multi-Tenant Dashboards created using Sophos Central API's. In this post we will use the Cases API and to build a Multi-Tenant Cases 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.

  1. 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.

  2. 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; }
    
    /* Flex Container */
    .container { display: flex; background-color: DodgerBlue; }
    .container-l { flex: 20%; flex-basis: 250px; background-color: #f1f1f1; padding: 10px; }
    .container-r { flex: 80%; background-color: #f1f1f1; padding: 10px; }
    
    /* Summary Container */
    .summary { display: flex; flex-wrap: wrap; justify-content: center; text-align: center; background-color: white; padding 20px; }
    #sumCri { border-radius: 10px; background: #d63d00; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center; color: white;}
    #sumHig { border-radius: 10px; background: #ec6500; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center;}
    #sumMed { border-radius: 10px; background: #ff8f00; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center;}
    #sumLow { border-radius: 10px; background: #696a6b; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center; color: white;}
    #sumInf { border-radius: 10px; background: #dadce0; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center;}
    #sumNa  { border-radius: 10px; background: #066fd8; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center; color: white;}
    #sumClo { border-radius: 10px; background: #57ee9bfb; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center;}
    #sumTot { border-radius: 10px; background: #F0F2F4; margin: 10px; padding: 16px; width: 200px; height: 75px; text-align: center;}
    #sumSep { border-radius: 10px; width: 200px; height: 10px; text-align: center;}
    #sumVal { font-size: 25px; font-weight: bold; }
    
    /* Details Container */
    .details { background-color: white; }
    table { border-collapse: collapse; width: 100%; }
    th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; border-right: 1px solid #ddd;}
    th.top { border-bottom: 0px; }
    th.number, td.number { width: 7%; text-align: right; }
    th.open { width: 7%; text-align: center; }
    tr.aktvive { background: #FFFFFF; color: #000000; }
    tr.inaktive { background: #FFFFFF; color: #b3afaf; }
    
    /* severity colors */
    .critical { background: #d63d0080 !important; color: #000000;}
    .high { background: #ec650080; color: #000000;}
    .medium { background: #ff8f0080; color: #000000;}
    .low { background: #696a6b80; color: #000000;}
    .info { background: #dadce080; color: #000000;}
    .new { background: #577bc480; color: #000000;}
    
    /* 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) {
        var tbody = '<tr><th class="name top"></th><th colspan="6" class="open top">Open</th><th class="number top"></th></tr>';
    	tbody += '<tr><th class="name">Tenant Name</th><th class="number">Critical</th><th class="number">High</th><th class="number">Medium</th><th class="number">Low</th><th class="number">Info</th><th class="number">New</th><th class="number">Closed</th></tr>';
    	var sumT = sumC = sumH = sumM = sumL = sumI = sumN = sumX = 0;
    
    	// build table and totals
    	for (var i = 0; i < dataTable.length; i++) {
    
    		if(dataTable[i].hasOwnProperty('Name')) {
    			if(dataTable[i].Cases_OCR !== 0) {
    				var row = '<tr class="aktive">';
    				var sev = " critical";
    			} else if(dataTable[i].Cases_OHI !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = " high";
    			} else if(dataTable[i].Cases_OME !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = " medium";
    			} else if(dataTable[i].Cases_OLO !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = " low";
    			} else if(dataTable[i].Cases_OIN !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = " info";
    			} else if(dataTable[i].Cases_ONA !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = "";
    			} else if(dataTable[i].Cases_CLO !== 0) {
    				var row = '<tr class="aktive">';
    				var	sev = "";
    			} else {
    				var row = '<tr class="inaktive">';
    				var	sev = "";
    			}
    
    			row += '<td class="name' + sev +'">' + dataTable[i].Name + "</td>";
    			row += '<td class="number numC' + sev +'">' + dataTable[i].Cases_OCR + "</td>";
    			row += '<td class="number numH' + sev +'">' + dataTable[i].Cases_OHI + "</td>";
    			row += '<td class="number numM' + sev +'">' + dataTable[i].Cases_OME + "</td>";
    			row += '<td class="number numL' + sev +'">' + dataTable[i].Cases_OLO + "</td>";
    			row += '<td class="number numI' + sev +'">' + dataTable[i].Cases_OIN + "</td>";
    
    			if(dataTable[i].Cases_ONA !== 0) {
    				row += '<td class="number numN new">' + dataTable[i].Cases_ONA + "</td>";
    			} else {
    				row += '<td class="number numN">' + dataTable[i].Cases_ONA + "</td>";
    			}
    			
    			row += '<td class="number numX none">' + dataTable[i].Cases_CLO + "</td>";
    			tbody += row + "</tr>";
    			
    			sumT += parseInt(dataTable[i].Cases_TOT);
    			sumC += parseInt(dataTable[i].Cases_OCR);
    			sumH += parseInt(dataTable[i].Cases_OHI);
    			sumM += parseInt(dataTable[i].Cases_OME);
    			sumL += parseInt(dataTable[i].Cases_OLO);
    			sumI += parseInt(dataTable[i].Cases_OIN);
    			sumN += parseInt(dataTable[i].Cases_ONA);
    			sumX += parseInt(dataTable[i].Cases_CLO);
    		}
    	}
    
    	// update webpage
    	$("output").html(
    	  '<table class="table"><tbody>' + tbody + "</tbody></table>"
    	);
    	
    	document.getElementById("sumCVal").innerHTML=sumC;
    	document.getElementById("sumHVal").innerHTML=sumH;
    	document.getElementById("sumMVal").innerHTML=sumM;
    	document.getElementById("sumLVal").innerHTML=sumL;
    	document.getElementById("sumIVal").innerHTML=sumI;
    	document.getElementById("sumNVal").innerHTML=sumN;
    	document.getElementById("sumXVal").innerHTML=sumX;
    	document.getElementById("sumTVal").innerHTML=sumT;
    }
    
    function parseCases(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);
    			}
    		});
    	})
    }
    
    parseCases("cases.csv", updatePage);
    
    setInterval(function(){
    	parseCases("cases.csv", updatePage);
    }, 30000); //refresh every 30 seconds
    	
    </s#c#r#i#p#t>
    
    
    <!-- Header -->
    <div class="header">
      <h1>Multi-Tenant Cases Dashboard</h1>
    </div>
    
    <!-- The flexible grid (content) -->
    <div class="container">
    	<div class="container-l">
    		<h2 class="center">SUMMARY</h2>
    		<div class="summary">
    			<div id="sumCri"><div id="sumVal"><div id="sumCVal">0</div></div>Critical</div><br>
    			<div id="sumHig"><div id="sumVal"><div id="sumHVal">0</div></div>High</div><br>
    			<div id="sumMed"><div id="sumVal"><div id="sumMVal">0</div></div>Medium</div><br><br>
    			<div id="sumLow"><div id="sumVal"><div id="sumLVal">0</div></div>Low</div><br>
    			<div id="sumInf"><div id="sumVal"><div id="sumIVal">0</div></div>Info</div><br>
    			<div id="sumNa"><div id="sumVal"><div id="sumNVal">0</div></div>New</div><br>
    			<div id="sumClo"><div id="sumVal"><div id="sumXVal">0</div></div>Closed</div><br>
    			<div id="sumTot"><div id="sumVal"><div id="sumTVal">0</div></div>Total</div><br>
    		</div>
    	</div>
    	<div class="container-r">
    		<h2><div id="lastUpdated">TENANT DETAILS</div></h2>
    		<div class="details">
    			<output>make sure that detections.csv is stored in the same directory as this page...</output>
    		</div>
    	</div>
    </div>
    
    <!-- Footer -->
    <div class="footer">
      <h4>Powered by the Cases API of Sophos Central, for more info see: <a href="https://developer.sophos.com/cases" target="_blank">developer.sophos.com/cases</a></h4>
    </div>
    
    </body>
    </html>

    Note: Do not place and run the PowerShell script in this directory!

  3. Create a directory in which you store the Get-Central-Cases.ps1 from the following code block:

    param ([switch] $SaveCredentials, [switch] $Export, [string] $Path = "." )
    <#
    	Description: Gather case counts for all tenants
    	Parameters: -SaveCredentials -> will store then entered credentials locally on the PC, this is needed once
    				-Export -> Export the results to "cases.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
    	}
    }
    
    # Setup datatable to store case counters
    $CasesList = New-Object System.Data.Datatable
    [void]$CasesList.Columns.Add("ID")
    [void]$CasesList.Columns.Add("Cases_OCR")
    [void]$CasesList.Columns.Add("Cases_OHI")
    [void]$CasesList.Columns.Add("Cases_OME")
    [void]$CasesList.Columns.Add("Cases_OLO")
    [void]$CasesList.Columns.Add("Cases_OIN")
    [void]$CasesList.Columns.Add("Cases_ONA")
    [void]$CasesList.Columns.Add("Cases_CLO")
    [void]$CasesList.Columns.Add("Cases_TOT")
    [void]$CasesList.Columns.Add("Name")
    $CasesView = New-Object System.Data.DataView($CasesList)
    
    Clear-Host
    Write-Output "==============================================================================="
    Write-Output "Sophos API - Count cases created in the last 30 days"
    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";
    		}
    
    		$Cases_TOT = 0
    		$Cases_OCR = 0
    		$Cases_OHI = 0
    		$Cases_OME = 0
    		$Cases_OLO = 0
    		$Cases_OIN = 0
    		$Cases_ONA = 0
    		$Cases_CLO = 0
    		$Cases_TOT = 0
    		
    		# Check Protection Status using the Health Check API
    		if (-not $null -eq $TenantDataRegion) {
    			try {
    
    				$Page = 1
    				do {
    					$Cases = (Invoke-RestMethod -Method Get -Uri $TenantDataRegion"/cases/v1/cases?page=$($page)&createdAfter=-P30D&pageSize=5000" -Headers $TenantHeaders -ErrorAction SilentlyContinue -ErrorVariable ScriptError)
    					foreach ($Case in $Cases.items) {
    
    						$Cases_TOT += 1
    						if ($Case.status -eq "closed") {
    							$Cases_CLO += 1
    						} else {
    							switch ($Case.severity) {
    								"Informational" {$Cases_OIN += 1}
    								"low"           {$Cases_OLO += 1}
    								"medium"        {$Cases_OME += 1}
    								"high"          {$Cases_OHI += 1}
    								"critical"      {$Cases_OCR += 1}
    								Default         {$Cases_ONA += 1}
    							}
    						}
    					}
    					$Page += 1
    				} while ($Page -le $Cases.pages.total)
    				[void]$CasesList.Rows.Add($Tenant.id, $Cases_OCR, $Cases_OHI, $Cases_OME, $Cases_OLO, $Cases_OIN, $Cases_ONA, $Cases_CLO, $Cases_TOT, $Tenant.name)
    				Write-Host ("   --> Total Cases: $($Cases_TOT)    Open Cases: $($Cases_OIN + $Cases_OLO+ $Cases_OME + $Cases_OHI + $Cases_OCR + $Cases_ONA)    Closed Cases: $($Cases_CLO)")
    			} 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 case counters were save to the following file:"
    	Write-Host "$($Path.TrimEnd('\'))\cases.csv"
    	$CasesList.Select("", "Cases_OCR DESC, Cases_OHI DESC, Cases_OME DESC, Cases_OLO DESC, Cases_OIN DESC, Cases_ONA DESC, Name ASC") | Export-Csv $path"\cases.csv" -Encoding UTF8 -NoTypeInformation
    } else {
    	Write-Host "Results:"    
    	$CasesList.Select("","Cases_OCR DESC, Cases_OHI DESC, Cases_OME DESC, Cases_OLO DESC, Cases_OIN DESC, Cases_ONA DESC, Name ASC") | select Name, Cases_OCR, Cases_OHI, Cases_OME, Cases_OLO, Cases_OIN, Cases_ONA, Cases_CLO | Format-Table
    }

  4. 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-Cases.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 case details could be retrieved successfully. 

  5. 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).

  6. For the next step we need to run the PowerShell script with the following parameters:
    -Export -Path <path where to store the cases.csv file> for example:

    C:\Dashboards\Get-Central-Cases.ps1 -Export C:\Dashboards\wwwroot

    If you now check the webpage in your browser, just remember that the cases.csv file needs to be stored in the same directory, then you should see the dashboard populated with the data from the CSV-File.

  7. 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: 

PS. The PowerShell script included in this post was used with PowerShell 5.1 on Windows and PowerShell 7.4 on Linux.



Added links to part 1 & 2
[edited by: Marcel at 11:07 AM (GMT -7) on 2 Jul 2024]